blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
288ecdd0d3af210827c7b5bce80eff00076614f9 | [
"self.bname = bname\nself.bdata = dict()\nparent_folder = pathlib.Path(__file__).parent.absolute()\nbench_filename = '{b}.json'.format(b=bname)\nbench_path = parent_folder.joinpath('..', '..', 'bench_info', bench_filename)\ntry:\n with open(bench_path) as json_file:\n self.info = json.load(json_file)['ben... | <|body_start_0|>
self.bname = bname
self.bdata = dict()
parent_folder = pathlib.Path(__file__).parent.absolute()
bench_filename = '{b}.json'.format(b=bname)
bench_path = parent_folder.joinpath('..', '..', 'bench_info', bench_filename)
try:
with open(bench_path... | A class for reading and benchmark information and initializing bechmark data. | Benchmark | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
<|body_0|>
def get_data(self, preset: str='L') -> Dict[str, Any]:
"... | stack_v2_sparse_classes_75kplus_train_002400 | 2,800 | permissive | [
{
"docstring": "Reads benchmark information. :param bname: The benchmark name.",
"name": "__init__",
"signature": "def __init__(self, bname: str)"
},
{
"docstring": "Initializes the benchmark data. :param preset: The data-size preset (S, M, L, paper).",
"name": "get_data",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_039404 | Implement the Python class `Benchmark` described below.
Class description:
A class for reading and benchmark information and initializing bechmark data.
Method signatures and docstrings:
- def __init__(self, bname: str): Reads benchmark information. :param bname: The benchmark name.
- def get_data(self, preset: str='... | Implement the Python class `Benchmark` described below.
Class description:
A class for reading and benchmark information and initializing bechmark data.
Method signatures and docstrings:
- def __init__(self, bname: str): Reads benchmark information. :param bname: The benchmark name.
- def get_data(self, preset: str='... | f2f545afe3603d5c8f1771f26d660f25ce4a3cda | <|skeleton|>
class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
<|body_0|>
def get_data(self, preset: str='L') -> Dict[str, Any]:
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
self.bname = bname
self.bdata = dict()
parent_folder = pathlib.Path(__file__)... | the_stack_v2_python_sparse | npbench/infrastructure/benchmark.py | learning-chip/npbench | train | 0 |
126225f1b76f2639c9e66f13885d1eb6bba9756c | [
"if not s_name.endswith('.pickle'):\n s_name += '.pickle'\nimport os\nf = open(os.path.join(s_cache_dir, s_name), 'w')\ncPickle.dump(obj, f)\nf.close()",
"if not s_file.endswith('.pickle'):\n s_file += '.pickle'\nf = open(s_file)\nx = cPickle.load(f)\nf.close()\nreturn x"
] | <|body_start_0|>
if not s_name.endswith('.pickle'):
s_name += '.pickle'
import os
f = open(os.path.join(s_cache_dir, s_name), 'w')
cPickle.dump(obj, f)
f.close()
<|end_body_0|>
<|body_start_1|>
if not s_file.endswith('.pickle'):
s_file += '.pickle... | MyUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUtils:
def dump_object(obj, s_name='untitled', s_cache_dir='.'):
"""use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_cache_dir: str, filepath, defaults to current folder '.' no return"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_002401 | 1,258 | permissive | [
{
"docstring": "use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_cache_dir: str, filepath, defaults to current folder '.' no return",
"name": "dump_object",
"signature": "def dump_object(obj, s_name='untitled', s_cache_dir='.')"
},... | 2 | stack_v2_sparse_classes_30k_train_016852 | Implement the Python class `MyUtils` described below.
Class description:
Implement the MyUtils class.
Method signatures and docstrings:
- def dump_object(obj, s_name='untitled', s_cache_dir='.'): use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_ca... | Implement the Python class `MyUtils` described below.
Class description:
Implement the MyUtils class.
Method signatures and docstrings:
- def dump_object(obj, s_name='untitled', s_cache_dir='.'): use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_ca... | 261901657bef5e1060f1ae86a2a3913d1e4c87c4 | <|skeleton|>
class MyUtils:
def dump_object(obj, s_name='untitled', s_cache_dir='.'):
"""use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_cache_dir: str, filepath, defaults to current folder '.' no return"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUtils:
def dump_object(obj, s_name='untitled', s_cache_dir='.'):
"""use to dump any object s_name: str, filename, defaults to 'untitled', filename will be appended with suffix '.pickle' s_cache_dir: str, filepath, defaults to current folder '.' no return"""
if not s_name.endswith('.pickle'):... | the_stack_v2_python_sparse | database/myutils.py | data2code/Metascape | train | 3 | |
33f1ab5fd64e6ea1de0c9ca5ad4e12310ef1bcfd | [
"CR = ConfigReader()\nfor key in CR.configSectionMap('const'):\n val = CR.configSectionMap('const')[key]\n setattr(self, key.upper(), val)",
"if self.__dict__.has_key(name):\n raise self.ConstError(\"Can't rebind const {}\".format(name))\nself.__dict__[name] = value"
] | <|body_start_0|>
CR = ConfigReader()
for key in CR.configSectionMap('const'):
val = CR.configSectionMap('const')[key]
setattr(self, key.upper(), val)
<|end_body_0|>
<|body_start_1|>
if self.__dict__.has_key(name):
raise self.ConstError("Can't rebind const {}"... | Const class that reads config stored values and presents them as constant values that can be imported | const | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class const:
"""Const class that reads config stored values and presents them as constant values that can be imported"""
def __init__(self):
"""Initialises and sets sel attributes from configreader values in 'const' section"""
<|body_0|>
def __setattr__(self, name, value):
... | stack_v2_sparse_classes_75kplus_train_002402 | 1,592 | permissive | [
{
"docstring": "Initialises and sets sel attributes from configreader values in 'const' section",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Overriding setattr method catching overwrites @param name: Attribute name @param value: Attribute value",
"name": "__seta... | 2 | stack_v2_sparse_classes_30k_train_014759 | Implement the Python class `const` described below.
Class description:
Const class that reads config stored values and presents them as constant values that can be imported
Method signatures and docstrings:
- def __init__(self): Initialises and sets sel attributes from configreader values in 'const' section
- def __s... | Implement the Python class `const` described below.
Class description:
Const class that reads config stored values and presents them as constant values that can be imported
Method signatures and docstrings:
- def __init__(self): Initialises and sets sel attributes from configreader values in 'const' section
- def __s... | 270664cc116cd8907026831e6f1ee0df46adffae | <|skeleton|>
class const:
"""Const class that reads config stored values and presents them as constant values that can be imported"""
def __init__(self):
"""Initialises and sets sel attributes from configreader values in 'const' section"""
<|body_0|>
def __setattr__(self, name, value):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class const:
"""Const class that reads config stored values and presents them as constant values that can be imported"""
def __init__(self):
"""Initialises and sets sel attributes from configreader values in 'const' section"""
CR = ConfigReader()
for key in CR.configSectionMap('const'):... | the_stack_v2_python_sparse | AIMSDataManager/Const.py | linz/QGIS-AIMS-Plugin | train | 3 |
7ace8af4c4d0ce3cb11cf98acb6990b856469105 | [
"super().save_model(request, obj, form, change)\nfrom zCelery_Tool.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncache.delete('index_page_data')",
"super().delete_model(request, obj)\nfrom zCelery_Tool.tasks import generate_static_index_html\ngenerate_static_index_html.delay()\ncach... | <|body_start_0|>
super().save_model(request, obj, form, change)
from zCelery_Tool.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
<|end_body_0|>
<|body_start_1|>
super().delete_model(request, obj)
from zCelery_To... | BaseModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().save_model(request, obj, form, change)
... | stack_v2_sparse_classes_75kplus_train_002403 | 2,006 | no_license | [
{
"docstring": "新增或更新表中的数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除表中的数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026434 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中的数据时调用
- def delete_model(self, request, obj): 删除表中的数据时调用 | Implement the Python class `BaseModelAdmin` described below.
Class description:
Implement the BaseModelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增或更新表中的数据时调用
- def delete_model(self, request, obj): 删除表中的数据时调用
<|skeleton|>
class BaseModelAdmin:
def save_m... | 8104d3f142e0e8bcad2a2853c865fd99feebc8ca | <|skeleton|>
class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""删除表中的数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseModelAdmin:
def save_model(self, request, obj, form, change):
"""新增或更新表中的数据时调用"""
super().save_model(request, obj, form, change)
from zCelery_Tool.tasks import generate_static_index_html
generate_static_index_html.delay()
cache.delete('index_page_data')
def del... | the_stack_v2_python_sparse | theSystem/admin.py | Im3Childe/LBicycleRentSystem | train | 0 | |
0bd88d8918a121a95d402ab517fa0779bddd8b86 | [
"super(ChangePrompt, self).__init__()\nself.adapter = adapter\nself.length = length\nself.variable = variable\nself._prompt = prompt\nreturn",
"if self._prompt is None:\n source = ascii_letters + digits\n self._prompt = random.choice(ascii_letters) + EMPTY_STRING.join((random.choice(source) for x in repeat(... | <|body_start_0|>
super(ChangePrompt, self).__init__()
self.adapter = adapter
self.length = length
self.variable = variable
self._prompt = prompt
return
<|end_body_0|>
<|body_start_1|>
if self._prompt is None:
source = ascii_letters + digits
... | Changes a prompt. | ChangePrompt | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangePrompt:
"""Changes a prompt."""
def __init__(self, adapter, length=10, variable='PS1', prompt=None):
""":param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters to use for the prompt. - `variable`: The name of the prom... | stack_v2_sparse_classes_75kplus_train_002404 | 2,314 | permissive | [
{
"docstring": ":param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters to use for the prompt. - `variable`: The name of the prompt variable on the device. - `prompt`: A prompt to use [default is a random one].",
"name": "__init__",
"signature... | 3 | stack_v2_sparse_classes_30k_train_025038 | Implement the Python class `ChangePrompt` described below.
Class description:
Changes a prompt.
Method signatures and docstrings:
- def __init__(self, adapter, length=10, variable='PS1', prompt=None): :param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters ... | Implement the Python class `ChangePrompt` described below.
Class description:
Changes a prompt.
Method signatures and docstrings:
- def __init__(self, adapter, length=10, variable='PS1', prompt=None): :param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters ... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class ChangePrompt:
"""Changes a prompt."""
def __init__(self, adapter, length=10, variable='PS1', prompt=None):
""":param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters to use for the prompt. - `variable`: The name of the prom... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangePrompt:
"""Changes a prompt."""
def __init__(self, adapter, length=10, variable='PS1', prompt=None):
""":param: - `adapter`: The connection adapter for the device (needs exec_command) - `length`: The number of characters to use for the prompt. - `variable`: The name of the prompt variable o... | the_stack_v2_python_sparse | apetools/commands/changeprompt.py | russell-n/oldape | train | 0 |
bc0304deed3f742fd4dfc310d57913bafb369052 | [
"self.s = kep_to_state(params.kep).flatten()\nself.t0 = params.epoch\nself.t = params.t0 - params.period\nself.period = params.period\nself.speed = params.speed\nself.op_writer = params.op_writer\nself.s = propagate_state(self.s, self.t0, self.t)\nself.t0 = self.t\nself.calc_thr = None\nself.is_running = False",
... | <|body_start_0|>
self.s = kep_to_state(params.kep).flatten()
self.t0 = params.epoch
self.t = params.t0 - params.period
self.period = params.period
self.speed = params.speed
self.op_writer = params.op_writer
self.s = propagate_state(self.s, self.t0, self.t)
... | A class for the simulator. | Simulator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
"""A class for the simulator."""
def __init__(self, params):
"""Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing"""
<|body_0|>
def simulate(self):
"""Starts the calculation thr... | stack_v2_sparse_classes_75kplus_train_002405 | 5,313 | permissive | [
{
"docstring": "Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Starts the calculation thread and waits for keyboard input. Press q or C... | 4 | null | Implement the Python class `Simulator` described below.
Class description:
A class for the simulator.
Method signatures and docstrings:
- def __init__(self, params): Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing
- def simulate(self): Start... | Implement the Python class `Simulator` described below.
Class description:
A class for the simulator.
Method signatures and docstrings:
- def __init__(self, params): Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing
- def simulate(self): Start... | 1aec8919ba42978e73aab4eaefe407adeb6287e9 | <|skeleton|>
class Simulator:
"""A class for the simulator."""
def __init__(self, params):
"""Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing"""
<|body_0|>
def simulate(self):
"""Starts the calculation thr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Simulator:
"""A class for the simulator."""
def __init__(self, params):
"""Initializes the simulator. Args: params: A SimParams object containing kep,t0,t,period,speed, and op_writer Returns: nothing"""
self.s = kep_to_state(params.kep).flatten()
self.t0 = params.epoch
sel... | the_stack_v2_python_sparse | orbitdeterminator/propagation/simulator.py | aerospaceresearch/orbitdeterminator | train | 179 |
62c3f39e9197c6cd1e4b4b76525f7d4362a2db73 | [
"super().__init__()\nself.forward_operator = forward_operator\nself.backward_operator = backward_operator\nself._coil_dim = 1\nself._complex_dim = -1\nself._spatial_dims = (2, 3)\nif standardization:\n self.standardization = StandardizationLayer(self._coil_dim, self._complex_dim)\nself.unet = MultiDomainUnet2d(f... | <|body_start_0|>
super().__init__()
self.forward_operator = forward_operator
self.backward_operator = backward_operator
self._coil_dim = 1
self._complex_dim = -1
self._spatial_dims = (2, 3)
if standardization:
self.standardization = StandardizationLaye... | Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge. | MultiDomainNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiDomainNet:
"""Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, standardization: bool=True, num_filters: int=16, num_pool_layers: int=4, dropout_probabilit... | stack_v2_sparse_classes_75kplus_train_002406 | 5,599 | permissive | [
{
"docstring": "Inits :class:`MultiDomainNet`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. standardization: bool If True standardization is used. Default: True. num_filters: int Number of filters for the :class:`MultiDomainUnet` module. Defau... | 3 | stack_v2_sparse_classes_30k_train_038194 | Implement the Python class `MultiDomainNet` described below.
Class description:
Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, standardization: bool=T... | Implement the Python class `MultiDomainNet` described below.
Class description:
Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, standardization: bool=T... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class MultiDomainNet:
"""Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, standardization: bool=True, num_filters: int=16, num_pool_layers: int=4, dropout_probabilit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiDomainNet:
"""Feature-level multi-domain module. Inspired by AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, standardization: bool=True, num_filters: int=16, num_pool_layers: int=4, dropout_probability: float=0.0,... | the_stack_v2_python_sparse | direct/nn/multidomainnet/multidomainnet.py | NKI-AI/direct | train | 151 |
b90dbbdc3fbb2f9c7d1e2bb74b7d41c93996ba93 | [
"allWord = Word.__getAllWordForLevel(level)\nrandomNumber = randint(0, len(allWord) - 1)\nrandomWord = allWord[randomNumber]\nreturn randomWord",
"if level == 'easy':\n myWordFile = open('mot_pendu/word.easy.txt', 'r')\n allWord = myWordFile.readlines()\n myWordFile.close()\nelse:\n myWordFile = open(... | <|body_start_0|>
allWord = Word.__getAllWordForLevel(level)
randomNumber = randint(0, len(allWord) - 1)
randomWord = allWord[randomNumber]
return randomWord
<|end_body_0|>
<|body_start_1|>
if level == 'easy':
myWordFile = open('mot_pendu/word.easy.txt', 'r')
... | Word | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
<|body_0|>
def __getAllWordForLevel(level):
"""Return a list of all word according to the specified level in a list form"""
<|body_1|>
def getHiddenWordFromWord(correctWord, numberO... | stack_v2_sparse_classes_75kplus_train_002407 | 3,092 | no_license | [
{
"docstring": "Return a word from the specifed",
"name": "getWordFromLevel",
"signature": "def getWordFromLevel(level)"
},
{
"docstring": "Return a list of all word according to the specified level in a list form",
"name": "__getAllWordForLevel",
"signature": "def __getAllWordForLevel(l... | 5 | stack_v2_sparse_classes_30k_train_035517 | Implement the Python class `Word` described below.
Class description:
Implement the Word class.
Method signatures and docstrings:
- def getWordFromLevel(level): Return a word from the specifed
- def __getAllWordForLevel(level): Return a list of all word according to the specified level in a list form
- def getHiddenW... | Implement the Python class `Word` described below.
Class description:
Implement the Word class.
Method signatures and docstrings:
- def getWordFromLevel(level): Return a word from the specifed
- def __getAllWordForLevel(level): Return a list of all word according to the specified level in a list form
- def getHiddenW... | 303e333b9601d5be8f17e4de31a44a8bdb7c6a59 | <|skeleton|>
class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
<|body_0|>
def __getAllWordForLevel(level):
"""Return a list of all word according to the specified level in a list form"""
<|body_1|>
def getHiddenWordFromWord(correctWord, numberO... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
allWord = Word.__getAllWordForLevel(level)
randomNumber = randint(0, len(allWord) - 1)
randomWord = allWord[randomNumber]
return randomWord
def __getAllWordForLevel(level):
"""Return a... | the_stack_v2_python_sparse | python/mr_rochel/mot_pendu/Word.py | Ryuka25/leetCode-training | train | 0 | |
a6245e055ae07a284f8bae51081f99b04d2be487 | [
"if not os.path.isdir(document_cache_path):\n raise DocumentCacheException(f'Path to document cache {document_cache_path} does not exist')\nself.document_cache_path = os.path.realpath(document_cache_path)",
"if cache_format not in CACHE_FORMATS:\n raise DocumentCacheFormatException(f'Invalid cache file form... | <|body_start_0|>
if not os.path.isdir(document_cache_path):
raise DocumentCacheException(f'Path to document cache {document_cache_path} does not exist')
self.document_cache_path = os.path.realpath(document_cache_path)
<|end_body_0|>
<|body_start_1|>
if cache_format not in CACHE_FORM... | Document cache session class. | DocumentCacheSession | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentCacheSession:
"""Document cache session class."""
def __init__(self, document_cache_path: str) -> None:
"""Initialize the document cache session."""
<|body_0|>
def get_cache_file_path(self, docmeta: DocMetadata, cache_format: str) -> Optional[str]:
"""Get... | stack_v2_sparse_classes_75kplus_train_002408 | 3,313 | permissive | [
{
"docstring": "Initialize the document cache session.",
"name": "__init__",
"signature": "def __init__(self, document_cache_path: str) -> None"
},
{
"docstring": "Get the absolute path of the cache file/directory if it exists.",
"name": "get_cache_file_path",
"signature": "def get_cache... | 2 | null | Implement the Python class `DocumentCacheSession` described below.
Class description:
Document cache session class.
Method signatures and docstrings:
- def __init__(self, document_cache_path: str) -> None: Initialize the document cache session.
- def get_cache_file_path(self, docmeta: DocMetadata, cache_format: str) ... | Implement the Python class `DocumentCacheSession` described below.
Class description:
Document cache session class.
Method signatures and docstrings:
- def __init__(self, document_cache_path: str) -> None: Initialize the document cache session.
- def get_cache_file_path(self, docmeta: DocMetadata, cache_format: str) ... | 22521762bca20cf0c42ea5966a997d38ce48e68a | <|skeleton|>
class DocumentCacheSession:
"""Document cache session class."""
def __init__(self, document_cache_path: str) -> None:
"""Initialize the document cache session."""
<|body_0|>
def get_cache_file_path(self, docmeta: DocMetadata, cache_format: str) -> Optional[str]:
"""Get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentCacheSession:
"""Document cache session class."""
def __init__(self, document_cache_path: str) -> None:
"""Initialize the document cache session."""
if not os.path.isdir(document_cache_path):
raise DocumentCacheException(f'Path to document cache {document_cache_path} d... | the_stack_v2_python_sparse | browse/services/document/cache.py | arXiv/arxiv-browse | train | 94 |
c2cf732e64032ca5ce6494f55dc85f22bd3ca39f | [
"if x < 0:\n return -self.reverse(-x)\nresult = 0\nwhile x:\n result = result * 10 + x % 10\n x /= 10\nreturn result if result <= 2147483647 else 0",
"if x < 0:\n x = int(str(x)[::-1][-1] + str(x)[::-1][:-1])\nelse:\n x = int(str(x)[::-1])\nx = 0 if abs(x) > 2147483647 else x\nreturn x"
] | <|body_start_0|>
if x < 0:
return -self.reverse(-x)
result = 0
while x:
result = result * 10 + x % 10
x /= 10
return result if result <= 2147483647 else 0
<|end_body_0|>
<|body_start_1|>
if x < 0:
x = int(str(x)[::-1][-1] + str(x)[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return -self.reverse(-x)
result = 0
wh... | stack_v2_sparse_classes_75kplus_train_002409 | 2,045 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016135 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int ... | ec3c0d4bd368dd1039f0fed2a07bf89e645a89c3 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
if x < 0:
return -self.reverse(-x)
result = 0
while x:
result = result * 10 + x % 10
x /= 10
return result if result <= 2147483647 else 0
def reverse2(self, x):
... | the_stack_v2_python_sparse | Reverse_Integer.py | Built00/Leetcode | train | 0 | |
4a31409f2998b9a99c6ba1950827eac7e1074029 | [
"serializer_class = WellListSerializerV2\nif self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():\n serializer_class = WellListAdminSerializerV2\nreturn serializer_class",
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists(... | <|body_start_0|>
serializer_class = WellListSerializerV2
if self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():
serializer_class = WellListAdminSerializerV2
return serializer_class
<|end_body_0|>
<|body_start... | List and create wells get: returns a list of wells | WellListAPIViewV2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellListAPIViewV2:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permiss... | stack_v2_sparse_classes_75kplus_train_002410 | 21,320 | permissive | [
{
"docstring": "Returns a different serializer class for admin users.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(... | 2 | stack_v2_sparse_classes_30k_train_017860 | Implement the Python class `WellListAPIViewV2` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users... | Implement the Python class `WellListAPIViewV2` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class WellListAPIViewV2:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permiss... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WellListAPIViewV2:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
serializer_class = WellListSerializerV2
if self.request.user and self.request.user.is_authenticated and self.requ... | the_stack_v2_python_sparse | app/backend/wells/views_v2.py | bcgov/gwells | train | 39 |
1d2b14172d99fffb50e82f7fe4dc6ea1c41bbf5e | [
"super(RCNN, self).__init__()\nself.fc = nn.Sequential(nn.Linear(in_channels * in_size[0] * in_size[1], num_channels), nn.ReLU(), nn.Linear(num_channels, num_channels), nn.ReLU())\nself.reg = nn.Linear(num_channels, 4)\nself.cls = nn.Linear(num_channels, num_classes + 1)",
"x = rois.view(rois.size(0), -1)\nx = se... | <|body_start_0|>
super(RCNN, self).__init__()
self.fc = nn.Sequential(nn.Linear(in_channels * in_size[0] * in_size[1], num_channels), nn.ReLU(), nn.Linear(num_channels, num_channels), nn.ReLU())
self.reg = nn.Linear(num_channels, 4)
self.cls = nn.Linear(num_channels, num_classes + 1)
<|e... | Refines the predictions of the RPN. | RCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RCNN:
"""Refines the predictions of the RPN."""
def __init__(self, in_channels, num_classes, in_size=(7, 7), num_channels=1024):
"""The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type]): [description] in_channels ([type]): Number of channels ... | stack_v2_sparse_classes_75kplus_train_002411 | 1,900 | permissive | [
{
"docstring": "The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type]): [description] in_channels ([type]): Number of channels of the input feature map num_classes ([type]): Number of target classes. in_size (tuple, optional): Size of the input feauture map after RoI-Poo... | 2 | stack_v2_sparse_classes_30k_train_024973 | Implement the Python class `RCNN` described below.
Class description:
Refines the predictions of the RPN.
Method signatures and docstrings:
- def __init__(self, in_channels, num_classes, in_size=(7, 7), num_channels=1024): The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type])... | Implement the Python class `RCNN` described below.
Class description:
Refines the predictions of the RPN.
Method signatures and docstrings:
- def __init__(self, in_channels, num_classes, in_size=(7, 7), num_channels=1024): The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type])... | 152c52515426a545508580a21687e15706312f99 | <|skeleton|>
class RCNN:
"""Refines the predictions of the RPN."""
def __init__(self, in_channels, num_classes, in_size=(7, 7), num_channels=1024):
"""The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type]): [description] in_channels ([type]): Number of channels ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RCNN:
"""Refines the predictions of the RPN."""
def __init__(self, in_channels, num_classes, in_size=(7, 7), num_channels=1024):
"""The RCNN can be adopted to the Faster-RCNN backbone through these parameters. Args: nn ([type]): [description] in_channels ([type]): Number of channels of the input ... | the_stack_v2_python_sparse | lib/rcnn.py | mctigger/understandable-faster-rcnn | train | 1 |
53ab77236f54a745751ec9f1284ea986eaf49ed1 | [
"image.setDisplayMode(IJ.COMPOSITE)\nwidth, height, nChannels, nSlices, nFrames = image.getDimensions()\ncurrentC, currentZ, currentT = (image.getC(), image.getZ(), image.getT())\nimage.setPosition(nChannels, currentZ, currentT)\nIJ.run(image, 'Add Slice', 'add=channel')\nimage.setPosition(currentC, currentZ, curre... | <|body_start_0|>
image.setDisplayMode(IJ.COMPOSITE)
width, height, nChannels, nSlices, nFrames = image.getDimensions()
currentC, currentZ, currentT = (image.getC(), image.getZ(), image.getT())
image.setPosition(nChannels, currentZ, currentT)
IJ.run(image, 'Add Slice', 'add=channe... | A collection of utility methods for working with 5D-images (Hyperstacks) | HyperstackUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperstackUtils:
"""A collection of utility methods for working with 5D-images (Hyperstacks)"""
def addEmptyChannel(image):
"""Add a new, empty channel to the image and restore the original position."""
<|body_0|>
def copyStackTo(image, stack, channel, frame, lut=None, o... | stack_v2_sparse_classes_75kplus_train_002412 | 4,689 | permissive | [
{
"docstring": "Add a new, empty channel to the image and restore the original position.",
"name": "addEmptyChannel",
"signature": "def addEmptyChannel(image)"
},
{
"docstring": "Copy the stack into the given channel and frame of image. The slices of the stack are copied with a transparent zero ... | 3 | null | Implement the Python class `HyperstackUtils` described below.
Class description:
A collection of utility methods for working with 5D-images (Hyperstacks)
Method signatures and docstrings:
- def addEmptyChannel(image): Add a new, empty channel to the image and restore the original position.
- def copyStackTo(image, st... | Implement the Python class `HyperstackUtils` described below.
Class description:
A collection of utility methods for working with 5D-images (Hyperstacks)
Method signatures and docstrings:
- def addEmptyChannel(image): Add a new, empty channel to the image and restore the original position.
- def copyStackTo(image, st... | 53de8bd5b153f9fa8d58637901151a08c520c930 | <|skeleton|>
class HyperstackUtils:
"""A collection of utility methods for working with 5D-images (Hyperstacks)"""
def addEmptyChannel(image):
"""Add a new, empty channel to the image and restore the original position."""
<|body_0|>
def copyStackTo(image, stack, channel, frame, lut=None, o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HyperstackUtils:
"""A collection of utility methods for working with 5D-images (Hyperstacks)"""
def addEmptyChannel(image):
"""Add a new, empty channel to the image and restore the original position."""
image.setDisplayMode(IJ.COMPOSITE)
width, height, nChannels, nSlices, nFrames ... | the_stack_v2_python_sparse | volker/toolsets/spine_analyzer/stackutil.py | MontpellierRessourcesImagerie/imagej_macros_and_scripts | train | 34 |
754bf5f852ebda036bb67db77c8ddaf0b3238fae | [
"name_key = Organization.all_of_property_key('name')\nself.assertIsNone(memcache.get(name_key))\norgNames = Organization.get_all_of_property('name')\nself.assertEqual(orgNames, memcache.get(name_key))",
"name_key = Organization.all_of_property_key('name')\nself.test_all_organization_names_caches()\nOrganization.c... | <|body_start_0|>
name_key = Organization.all_of_property_key('name')
self.assertIsNone(memcache.get(name_key))
orgNames = Organization.get_all_of_property('name')
self.assertEqual(orgNames, memcache.get(name_key))
<|end_body_0|>
<|body_start_1|>
name_key = Organization.all_of_pr... | Test uses of memcache to speed up queries. | MemcacheTest | [
"JSON",
"Unlicense",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemcacheTest:
"""Test uses of memcache to speed up queries."""
def test_all_organization_names_caches(self):
"""After the first query, all names should be cached."""
<|body_0|>
def test_all_organization_names_recache(self):
"""After writing an org, the cache shou... | stack_v2_sparse_classes_75kplus_train_002413 | 957 | permissive | [
{
"docstring": "After the first query, all names should be cached.",
"name": "test_all_organization_names_caches",
"signature": "def test_all_organization_names_caches(self)"
},
{
"docstring": "After writing an org, the cache should clear.",
"name": "test_all_organization_names_recache",
... | 2 | null | Implement the Python class `MemcacheTest` described below.
Class description:
Test uses of memcache to speed up queries.
Method signatures and docstrings:
- def test_all_organization_names_caches(self): After the first query, all names should be cached.
- def test_all_organization_names_recache(self): After writing a... | Implement the Python class `MemcacheTest` described below.
Class description:
Test uses of memcache to speed up queries.
Method signatures and docstrings:
- def test_all_organization_names_caches(self): After the first query, all names should be cached.
- def test_all_organization_names_recache(self): After writing a... | 20b945adf7b62e67db60be3cc451ffb16113fe33 | <|skeleton|>
class MemcacheTest:
"""Test uses of memcache to speed up queries."""
def test_all_organization_names_caches(self):
"""After the first query, all names should be cached."""
<|body_0|>
def test_all_organization_names_recache(self):
"""After writing an org, the cache shou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemcacheTest:
"""Test uses of memcache to speed up queries."""
def test_all_organization_names_caches(self):
"""After the first query, all names should be cached."""
name_key = Organization.all_of_property_key('name')
self.assertIsNone(memcache.get(name_key))
orgNames = Or... | the_stack_v2_python_sparse | unit_testing/test_memcache.py | Stanford-PERTS/neptune | train | 0 |
c40dcb3ebbac21ef940d239897b0c12bd2374741 | [
"self.vault_id = vault_id\nself.vault_name = vault_name\nself.vault_type = vault_type",
"if dictionary is None:\n return None\nvault_id = dictionary.get('vaultId')\nvault_name = dictionary.get('vaultName')\nvault_type = dictionary.get('vaultType')\nreturn cls(vault_id, vault_name, vault_type)"
] | <|body_start_0|>
self.vault_id = vault_id
self.vault_name = vault_name
self.vault_type = vault_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
vault_id = dictionary.get('vaultId')
vault_name = dictionary.get('vaultName')
vault_... | Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster. vault_name (string): Name of the Archival Vault. vault_type (VaultTypeArchivalExternalT... | ArchivalExternalTarget | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivalExternalTarget:
"""Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster. vault_name (string): Name of the Arch... | stack_v2_sparse_classes_75kplus_train_002414 | 2,202 | permissive | [
{
"docstring": "Constructor for the ArchivalExternalTarget class",
"name": "__init__",
"signature": "def __init__(self, vault_id=None, vault_name=None, vault_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | stack_v2_sparse_classes_30k_train_040692 | Implement the Python class `ArchivalExternalTarget` described below.
Class description:
Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster... | Implement the Python class `ArchivalExternalTarget` described below.
Class description:
Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ArchivalExternalTarget:
"""Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster. vault_name (string): Name of the Arch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArchivalExternalTarget:
"""Implementation of the 'ArchivalExternalTarget' model. Specifies settings about the Archival External Target (such as Tape or AWS). Attributes: vault_id (long|int): Specifies the id of Archival Vault assigned by the Cohesity Cluster. vault_name (string): Name of the Archival Vault. v... | the_stack_v2_python_sparse | cohesity_management_sdk/models/archival_external_target.py | cohesity/management-sdk-python | train | 24 |
259b0cdd91da9e992f786d673d6b414b5a3a97a2 | [
"super(ResidualCBNFFNNBlock, self).__init__()\nself.linear_layer_1 = nn.Linear(in_features=in_features, out_features=out_features, bias=True)\nself.linear_layer_2 = nn.Linear(in_features=out_features, out_features=out_features, bias=True)\nself.activation = activation()\nself.final_activation = activation()\nself.d... | <|body_start_0|>
super(ResidualCBNFFNNBlock, self).__init__()
self.linear_layer_1 = nn.Linear(in_features=in_features, out_features=out_features, bias=True)
self.linear_layer_2 = nn.Linear(in_features=out_features, out_features=out_features, bias=True)
self.activation = activation()
... | This class implements a simple residual feed-forward neural network block with two linear layers and CBN. | ResidualCBNFFNNBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualCBNFFNNBlock:
"""This class implements a simple residual feed-forward neural network block with two linear layers and CBN."""
def __init__(self, in_features: int, out_features: int, latent_features: int, activation: Type[nn.Module]=PAU, dropout: float=0.0) -> None:
"""Constru... | stack_v2_sparse_classes_75kplus_train_002415 | 11,223 | permissive | [
{
"docstring": "Constructor method :param in_features: (int) Number of input features :param out_features: (int) Number of output features :param latent_features: (int) Number of latent features :param activation: (Type[nn.Module]) Type of activation function to be utilized :param dropout: (float) Dropout rate ... | 2 | stack_v2_sparse_classes_30k_train_051865 | Implement the Python class `ResidualCBNFFNNBlock` described below.
Class description:
This class implements a simple residual feed-forward neural network block with two linear layers and CBN.
Method signatures and docstrings:
- def __init__(self, in_features: int, out_features: int, latent_features: int, activation: ... | Implement the Python class `ResidualCBNFFNNBlock` described below.
Class description:
This class implements a simple residual feed-forward neural network block with two linear layers and CBN.
Method signatures and docstrings:
- def __init__(self, in_features: int, out_features: int, latent_features: int, activation: ... | 7d0066990822bf63ac6f40523a53e8ea938cd9a1 | <|skeleton|>
class ResidualCBNFFNNBlock:
"""This class implements a simple residual feed-forward neural network block with two linear layers and CBN."""
def __init__(self, in_features: int, out_features: int, latent_features: int, activation: Type[nn.Module]=PAU, dropout: float=0.0) -> None:
"""Constru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResidualCBNFFNNBlock:
"""This class implements a simple residual feed-forward neural network block with two linear layers and CBN."""
def __init__(self, in_features: int, out_features: int, latent_features: int, activation: Type[nn.Module]=PAU, dropout: float=0.0) -> None:
"""Constructor method :... | the_stack_v2_python_sparse | oss_net/decoder.py | ChristophReich1996/OSS-Net | train | 22 |
21790df1a4bc34589c2f8b438ac17a548ce5ff2b | [
"node = TestNode(names=[('logging', None)], lineno=15)\nself.checker.visit_import(node)\nself.assertEqual(self.results, [('R9301', '', 15, None)])",
"node = TestNode(names=[('myModule', None)], lineno=15)\nself.checker.visit_import(node)\nself.assertEqual(self.results, [])"
] | <|body_start_0|>
node = TestNode(names=[('logging', None)], lineno=15)
self.checker.visit_import(node)
self.assertEqual(self.results, [('R9301', '', 15, None)])
<|end_body_0|>
<|body_start_1|>
node = TestNode(names=[('myModule', None)], lineno=15)
self.checker.visit_import(node)... | Tests for ChromiteLoggingChecker module | ChromiteLoggingCheckerTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChromiteLoggingCheckerTest:
"""Tests for ChromiteLoggingChecker module"""
def testLoggingImported(self):
"""Test that import logging is flagged."""
<|body_0|>
def testLoggingNotImported(self):
"""Test that importing something else (not logging) is not flagged."""... | stack_v2_sparse_classes_75kplus_train_002416 | 11,497 | permissive | [
{
"docstring": "Test that import logging is flagged.",
"name": "testLoggingImported",
"signature": "def testLoggingImported(self)"
},
{
"docstring": "Test that importing something else (not logging) is not flagged.",
"name": "testLoggingNotImported",
"signature": "def testLoggingNotImpor... | 2 | stack_v2_sparse_classes_30k_train_034828 | Implement the Python class `ChromiteLoggingCheckerTest` described below.
Class description:
Tests for ChromiteLoggingChecker module
Method signatures and docstrings:
- def testLoggingImported(self): Test that import logging is flagged.
- def testLoggingNotImported(self): Test that importing something else (not loggin... | Implement the Python class `ChromiteLoggingCheckerTest` described below.
Class description:
Tests for ChromiteLoggingChecker module
Method signatures and docstrings:
- def testLoggingImported(self): Test that import logging is flagged.
- def testLoggingNotImported(self): Test that importing something else (not loggin... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ChromiteLoggingCheckerTest:
"""Tests for ChromiteLoggingChecker module"""
def testLoggingImported(self):
"""Test that import logging is flagged."""
<|body_0|>
def testLoggingNotImported(self):
"""Test that importing something else (not logging) is not flagged."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChromiteLoggingCheckerTest:
"""Tests for ChromiteLoggingChecker module"""
def testLoggingImported(self):
"""Test that import logging is flagged."""
node = TestNode(names=[('logging', None)], lineno=15)
self.checker.visit_import(node)
self.assertEqual(self.results, [('R9301... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/lint_unittest.py | metux/chromium-suckless | train | 5 |
74cf2663c72e62fd7acaea89e5afe5b93977d1ae | [
"plan = QueryPlansAcquired.objects.filter(is_active=True, queryplansclient__client=pk, available_queries__gt=0, expiration_date__gte=datetime.now().date()).order_by('id').values('id', 'plan_name', 'is_active', 'validity_months', 'query_quantity', 'available_queries', 'expiration_date', 'queries_to_pay').annotate(is... | <|body_start_0|>
plan = QueryPlansAcquired.objects.filter(is_active=True, queryplansclient__client=pk, available_queries__gt=0, expiration_date__gte=datetime.now().date()).order_by('id').values('id', 'plan_name', 'is_active', 'validity_months', 'query_quantity', 'available_queries', 'expiration_date', 'queries_... | Vista para obetener todos los planes de un cliente. | ClientPlansView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
<|body_0|>
def get(self, request):
"""Obtener la lista con todos los planes del cliente."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_002417 | 44,248 | no_license | [
{
"docstring": "Obtener lista de planes.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Obtener la lista con todos los planes del cliente.",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027217 | Implement the Python class `ClientPlansView` described below.
Class description:
Vista para obetener todos los planes de un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener lista de planes.
- def get(self, request): Obtener la lista con todos los planes del cliente. | Implement the Python class `ClientPlansView` described below.
Class description:
Vista para obetener todos los planes de un cliente.
Method signatures and docstrings:
- def get_object(self, pk): Obtener lista de planes.
- def get(self, request): Obtener la lista con todos los planes del cliente.
<|skeleton|>
class C... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class ClientPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
<|body_0|>
def get(self, request):
"""Obtener la lista con todos los planes del cliente."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientPlansView:
"""Vista para obetener todos los planes de un cliente."""
def get_object(self, pk):
"""Obtener lista de planes."""
plan = QueryPlansAcquired.objects.filter(is_active=True, queryplansclient__client=pk, available_queries__gt=0, expiration_date__gte=datetime.now().date()).or... | the_stack_v2_python_sparse | api/views/plan.py | darwinv/api-chat-lnk | train | 0 |
bdde4edf4a3e15831aa4e97f7673ce539175d87e | [
"HRSampler.__init__(self, model, thinning, seed=seed)\nif model.solver.is_integer:\n raise TypeError('sampling does not work with integer problems :(')\nself.model = model.copy()\nself.thinning = thinning\nif nproj is None:\n self.nproj = int(min(len(self.model.variables) ** 3, 1000000.0))\nelse:\n self.np... | <|body_start_0|>
HRSampler.__init__(self, model, thinning, seed=seed)
if model.solver.is_integer:
raise TypeError('sampling does not work with integer problems :(')
self.model = model.copy()
self.thinning = thinning
if nproj is None:
self.nproj = int(min(l... | GeneralizedHRSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralizedHRSampler:
def __init__(self, model, thinning, nproj=None, seed=None):
"""Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initialize a new sampler object."""
<|body_0|>
def generate_fva_warmup(self):
"""Adapted from c... | stack_v2_sparse_classes_75kplus_train_002418 | 7,875 | permissive | [
{
"docstring": "Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initialize a new sampler object.",
"name": "__init__",
"signature": "def __init__(self, model, thinning, nproj=None, seed=None)"
},
{
"docstring": "Adapted from cobra.flux_analysis.sampling.py ... | 2 | null | Implement the Python class `GeneralizedHRSampler` described below.
Class description:
Implement the GeneralizedHRSampler class.
Method signatures and docstrings:
- def __init__(self, model, thinning, nproj=None, seed=None): Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initial... | Implement the Python class `GeneralizedHRSampler` described below.
Class description:
Implement the GeneralizedHRSampler class.
Method signatures and docstrings:
- def __init__(self, model, thinning, nproj=None, seed=None): Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initial... | d4de7b9830bb67c6244b2b0b2a3a0d95793b1b87 | <|skeleton|>
class GeneralizedHRSampler:
def __init__(self, model, thinning, nproj=None, seed=None):
"""Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initialize a new sampler object."""
<|body_0|>
def generate_fva_warmup(self):
"""Adapted from c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeneralizedHRSampler:
def __init__(self, model, thinning, nproj=None, seed=None):
"""Adapted from cobra.flux_analysis.sampling.py _________________________________________ Initialize a new sampler object."""
HRSampler.__init__(self, model, thinning, seed=seed)
if model.solver.is_intege... | the_stack_v2_python_sparse | pytfa/analysis/sampling.py | EPFL-LCSB/pytfa | train | 35 | |
925e71d53e0776d0806cd074eed7b6d25d9b6350 | [
"minio_client: Minio = MinioService._get_client()\ncurrent_app.logger.debug(f'Get Minio file {bucket_name}/{file_name}')\nreturn minio_client.get_object(bucket_name, file_name)",
"minio_client: Minio = MinioService._get_client()\ncurrent_app.logger.debug(f'Put Minio file {bucket_name}/{file_name}')\nvalue_as_stre... | <|body_start_0|>
minio_client: Minio = MinioService._get_client()
current_app.logger.debug(f'Get Minio file {bucket_name}/{file_name}')
return minio_client.get_object(bucket_name, file_name)
<|end_body_0|>
<|body_start_1|>
minio_client: Minio = MinioService._get_client()
current... | Document Storage class. | MinioService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinioService:
"""Document Storage class."""
def get_minio_file(bucket_name: str, file_name: str):
"""Return the file from Minio."""
<|body_0|>
def put_minio_file(bucket_name: str, file_name: str, value_as_bytes: bytearray):
"""Return the file from Minio."""
... | stack_v2_sparse_classes_75kplus_train_002419 | 2,396 | permissive | [
{
"docstring": "Return the file from Minio.",
"name": "get_minio_file",
"signature": "def get_minio_file(bucket_name: str, file_name: str)"
},
{
"docstring": "Return the file from Minio.",
"name": "put_minio_file",
"signature": "def put_minio_file(bucket_name: str, file_name: str, value_... | 4 | stack_v2_sparse_classes_30k_train_032690 | Implement the Python class `MinioService` described below.
Class description:
Document Storage class.
Method signatures and docstrings:
- def get_minio_file(bucket_name: str, file_name: str): Return the file from Minio.
- def put_minio_file(bucket_name: str, file_name: str, value_as_bytes: bytearray): Return the file... | Implement the Python class `MinioService` described below.
Class description:
Document Storage class.
Method signatures and docstrings:
- def get_minio_file(bucket_name: str, file_name: str): Return the file from Minio.
- def put_minio_file(bucket_name: str, file_name: str, value_as_bytes: bytearray): Return the file... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class MinioService:
"""Document Storage class."""
def get_minio_file(bucket_name: str, file_name: str):
"""Return the file from Minio."""
<|body_0|>
def put_minio_file(bucket_name: str, file_name: str, value_as_bytes: bytearray):
"""Return the file from Minio."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinioService:
"""Document Storage class."""
def get_minio_file(bucket_name: str, file_name: str):
"""Return the file from Minio."""
minio_client: Minio = MinioService._get_client()
current_app.logger.debug(f'Get Minio file {bucket_name}/{file_name}')
return minio_client.ge... | the_stack_v2_python_sparse | queue_services/account-mailer/src/account_mailer/services/minio_service.py | bcgov/sbc-auth | train | 13 |
c8a1d32c77724102fc28d8d3e53713fd0eca72f4 | [
"super(DropLineEdit, self).__init__(initial_text, parent)\nself.datatree = datatree\nif completer:\n self.setCompleter(completer)",
"if isinstance(e.mimeData(), DataIndexMime):\n e.accept()\nelse:\n super(DropLineEdit, self).dragEnterEvent(e)",
"if isinstance(e.mimeData(), DataIndexMime):\n indices ... | <|body_start_0|>
super(DropLineEdit, self).__init__(initial_text, parent)
self.datatree = datatree
if completer:
self.setCompleter(completer)
<|end_body_0|>
<|body_start_1|>
if isinstance(e.mimeData(), DataIndexMime):
e.accept()
else:
super(Dr... | This creates a LineEdit (textfield) for datatree drop operations. | DropLineEdit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropLineEdit:
"""This creates a LineEdit (textfield) for datatree drop operations."""
def __init__(self, parent, datatree, initial_text='', completer=None):
"""Construct a DropLineEdit with Qt GUI parent, initial_text, and given completer. This requires a reference to the Boxfish Dat... | stack_v2_sparse_classes_75kplus_train_002420 | 8,145 | no_license | [
{
"docstring": "Construct a DropLineEdit with Qt GUI parent, initial_text, and given completer. This requires a reference to the Boxfish DataTree to interpret dragged indices.",
"name": "__init__",
"signature": "def __init__(self, parent, datatree, initial_text='', completer=None)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_val_000865 | Implement the Python class `DropLineEdit` described below.
Class description:
This creates a LineEdit (textfield) for datatree drop operations.
Method signatures and docstrings:
- def __init__(self, parent, datatree, initial_text='', completer=None): Construct a DropLineEdit with Qt GUI parent, initial_text, and give... | Implement the Python class `DropLineEdit` described below.
Class description:
This creates a LineEdit (textfield) for datatree drop operations.
Method signatures and docstrings:
- def __init__(self, parent, datatree, initial_text='', completer=None): Construct a DropLineEdit with Qt GUI parent, initial_text, and give... | afa9c9547716909d806a0bd8165bfe896617ca7e | <|skeleton|>
class DropLineEdit:
"""This creates a LineEdit (textfield) for datatree drop operations."""
def __init__(self, parent, datatree, initial_text='', completer=None):
"""Construct a DropLineEdit with Qt GUI parent, initial_text, and given completer. This requires a reference to the Boxfish Dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DropLineEdit:
"""This creates a LineEdit (textfield) for datatree drop operations."""
def __init__(self, parent, datatree, initial_text='', completer=None):
"""Construct a DropLineEdit with Qt GUI parent, initial_text, and given completer. This requires a reference to the Boxfish DataTree to inte... | the_stack_v2_python_sparse | boxfish/GUIUtils.py | LLNL/boxfish | train | 4 |
6e41871984cd7a2066b90a193b584f8d0d3ac442 | [
"self.cf = cf\nself.listname = listname\nself.path = cf.etcpath(listname)\nself.srcdict = self.loadfile()\nif need_compiled_ix:\n self.records = self.compileix(self.srcdict)",
"disabled = self.path / 'disabled'\nif disabled.exists():\n return {}\nstrict = re.compile('([0-9a-f.:]*?)(\\\\|[0-9]{1,3})?(?:\\\\.... | <|body_start_0|>
self.cf = cf
self.listname = listname
self.path = cf.etcpath(listname)
self.srcdict = self.loadfile()
if need_compiled_ix:
self.records = self.compileix(self.srcdict)
<|end_body_0|>
<|body_start_1|>
disabled = self.path / 'disabled'
i... | ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip6 addresses are usually /112. Contents of the file is a set of ports, one per... | ListReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListReader:
"""ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip6 addresses are usually /112. Contents ... | stack_v2_sparse_classes_75kplus_train_002421 | 8,220 | permissive | [
{
"docstring": "Initialise with cf to find constant locations Parameters ---------- cf : Config listname : {'whitelist', 'blacklist} need_compiled_ix : bool False if caller just needs srcdict Creates srcdict and records",
"name": "__init__",
"signature": "def __init__(self, cf, listname, need_compiled_i... | 5 | stack_v2_sparse_classes_30k_train_011701 | Implement the Python class `ListReader` described below.
Class description:
ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip... | Implement the Python class `ListReader` described below.
Class description:
ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip... | 43e48d46089113e09c3a267c255d3102f3dddac7 | <|skeleton|>
class ListReader:
"""ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip6 addresses are usually /112. Contents ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListReader:
"""ListReader class when initialised reads files from either whitelist and blacklist directories Each file in these directories is named by an ip or ip6 address, possibly followed by '.auto' Names can contain a vertical bar and a mask number - ip6 addresses are usually /112. Contents of the file i... | the_stack_v2_python_sparse | nftfw/listreader.py | pcollinson/nftfw | train | 31 |
902cff0b90b6352e9cf8ec77deab52a69f9985fb | [
"self.left = left\nself.right = right\nself.value = value",
"if self.value is None:\n return [preorder(self.left), preorder(self.right)]\nelse:\n return [preorder(self, value), preorder(self.left), preorder(self.right)]",
"if self.value is None:\n return [postorder(self.left), postorder(self.right)]\ne... | <|body_start_0|>
self.left = left
self.right = right
self.value = value
<|end_body_0|>
<|body_start_1|>
if self.value is None:
return [preorder(self.left), preorder(self.right)]
else:
return [preorder(self, value), preorder(self.left), preorder(self.right... | An underclass of Node0, representing the node of a tree. | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""An underclass of Node0, representing the node of a tree."""
def __init__(self, left, right, value):
"""The defining function of the class."""
<|body_0|>
def preorder(self):
"""A function that implements the preorder method of a given node object. It retu... | stack_v2_sparse_classes_75kplus_train_002422 | 3,081 | no_license | [
{
"docstring": "The defining function of the class.",
"name": "__init__",
"signature": "def __init__(self, left, right, value)"
},
{
"docstring": "A function that implements the preorder method of a given node object. It returns the ordered tree in pre order notation. If the value of a given nod... | 3 | null | Implement the Python class `Node` described below.
Class description:
An underclass of Node0, representing the node of a tree.
Method signatures and docstrings:
- def __init__(self, left, right, value): The defining function of the class.
- def preorder(self): A function that implements the preorder method of a given... | Implement the Python class `Node` described below.
Class description:
An underclass of Node0, representing the node of a tree.
Method signatures and docstrings:
- def __init__(self, left, right, value): The defining function of the class.
- def preorder(self): A function that implements the preorder method of a given... | e89b329bc9edd37d5d9986f07ca8a63d50686882 | <|skeleton|>
class Node:
"""An underclass of Node0, representing the node of a tree."""
def __init__(self, left, right, value):
"""The defining function of the class."""
<|body_0|>
def preorder(self):
"""A function that implements the preorder method of a given node object. It retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
"""An underclass of Node0, representing the node of a tree."""
def __init__(self, left, right, value):
"""The defining function of the class."""
self.left = left
self.right = right
self.value = value
def preorder(self):
"""A function that implements the ... | the_stack_v2_python_sparse | StudentProblem/10.21.11.8/8/1569577472.py | LennartElbe/codeEvo | train | 0 |
39ec904b209ac1263abcd6a99fb489bc874cdea1 | [
"if handler_config is None:\n raise CSVFileToSQLHandlerError('None passed as handler config.')\nself.name = handler_config[CONFIG_NAME]\nself.source = handler_config[CONFIG_SOURCE]\nself.exitonfailure = handler_config[CONFIG_EXITONFAILURE]\nself.recursive = handler_config[CONFIG_RECURSIVE]\nself.delete_source = ... | <|body_start_0|>
if handler_config is None:
raise CSVFileToSQLHandlerError('None passed as handler config.')
self.name = handler_config[CONFIG_NAME]
self.source = handler_config[CONFIG_SOURCE]
self.exitonfailure = handler_config[CONFIG_EXITONFAILURE]
self.recursive = ... | Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object source: Directory to watch for files recursive: Boolean == true perform recursive file ... | CSVFileToSQLHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVFileToSQLHandler:
"""Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object source: Directory to watch for files rec... | stack_v2_sparse_classes_75kplus_train_002423 | 5,607 | permissive | [
{
"docstring": "Initialise handler attributes. Args: handler_config (ConfigDict): Handler configuration. Raises: CSVFileToSQLHandlerError: None passed as handler configuration.",
"name": "__init__",
"signature": "def __init__(self, handler_config: ConfigDict) -> None"
},
{
"docstring": "Import C... | 2 | stack_v2_sparse_classes_30k_train_051827 | Implement the Python class `CSVFileToSQLHandler` described below.
Class description:
Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object s... | Implement the Python class `CSVFileToSQLHandler` described below.
Class description:
Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object s... | abbd95b0ddd9da577b6cad69708f2e31db694d94 | <|skeleton|>
class CSVFileToSQLHandler:
"""Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object source: Directory to watch for files rec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSVFileToSQLHandler:
"""Import CSV file to MySQL database. Read in CSV file and insert/update rows within a given MySQL database/table. If no key attribute is specified then the rows are inserted otherwise updated. Attributes: name : Name of handler object source: Directory to watch for files recursive: Boole... | the_stack_v2_python_sparse | FPE/builtin/csvfile_to_sql_handler.py | clockworkengineer/Constrictor | train | 1 |
c2c26dc5578b798c62ff06fcdd6d6858a50cd1d6 | [
"self.distribution_u = distribution_mimicking_uniform\nself.inverse_cdf_fun = inverse_cdf_fun\nif self.distribution_u.mimics != 'StdUniform':\n raise TransformError('Can only apply inverse CDF transform to DiscreteDistributions mimicing StdUniform')\nself.low_discrepancy = True if 'IID' in type(self.distribution... | <|body_start_0|>
self.distribution_u = distribution_mimicking_uniform
self.inverse_cdf_fun = inverse_cdf_fun
if self.distribution_u.mimics != 'StdUniform':
raise TransformError('Can only apply inverse CDF transform to DiscreteDistributions mimicing StdUniform')
self.low_discr... | Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_measure = InverseCDFSampling( ... distribution_mimicking_uniform = Sobol(dimension=2,s... | InverseCDFSampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InverseCDFSampling:
"""Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_measure = InverseCDFSampling( ... distri... | stack_v2_sparse_classes_75kplus_train_002424 | 2,629 | permissive | [
{
"docstring": "Args: distribution_mimicking_uniform (DiscreteDistribution): DiscreteDistribution instance which mimics standard uniform inverse_cdf_fun (function): function accepting samples mimicing uniform and applying inverse CDF transform. Must have 1 input argument accepting an ndarray of size n (observat... | 2 | stack_v2_sparse_classes_30k_train_046423 | Implement the Python class `InverseCDFSampling` described below.
Class description:
Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_m... | Implement the Python class `InverseCDFSampling` described below.
Class description:
Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_m... | 96af0449bafe027191f9d976ceef47557b0127d4 | <|skeleton|>
class InverseCDFSampling:
"""Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_measure = InverseCDFSampling( ... distri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InverseCDFSampling:
"""Sampling by inverse CDF transform applied to discrete distribution samples mimics standard uniform. >>> _lambda = 1.5 >>> exp_pdf = lambda x,l=_lambda: l*exp(-l*x) >>> exp_inverse_cdf = lambda u,l=_lambda: -log(1-u)/l >>> exponential_measure = InverseCDFSampling( ... distribution_mimick... | the_stack_v2_python_sparse | deprecated/qmcpy_objs/inverse_cdf_sampling.py | QMCSoftware/QMCSoftware | train | 54 |
eb41517ae27f5344f9a79c34c1541c3dd53451dc | [
"LOG.debug('Applications:Get <EnvTemplateId: {templ_id}, Path: {path}>'.format(templ_id=env_template_id, path=path))\ntry:\n get_data = core_services.CoreServices.get_template_data\n result = get_data(env_template_id, path)\nexcept (KeyError, ValueError, AttributeError):\n msg = _('The environment template... | <|body_start_0|>
LOG.debug('Applications:Get <EnvTemplateId: {templ_id}, Path: {path}>'.format(templ_id=env_template_id, path=path))
try:
get_data = core_services.CoreServices.get_template_data
result = get_data(env_template_id, path)
except (KeyError, ValueError, Attribu... | Controller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def index(self, request, env_template_id, path):
"""Obtains services/applications for a template It obtains all the services/applications associated to a template :param request: The operation request. :param env_template_id: The environment template id with contains the serv... | stack_v2_sparse_classes_75kplus_train_002425 | 7,043 | permissive | [
{
"docstring": "Obtains services/applications for a template It obtains all the services/applications associated to a template :param request: The operation request. :param env_template_id: The environment template id with contains the services :param path: The operation path",
"name": "index",
"signatu... | 5 | null | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def index(self, request, env_template_id, path): Obtains services/applications for a template It obtains all the services/applications associated to a template :param request... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def index(self, request, env_template_id, path): Obtains services/applications for a template It obtains all the services/applications associated to a template :param request... | c898a310afbc27f12190446ef75d8b0bd12115eb | <|skeleton|>
class Controller:
def index(self, request, env_template_id, path):
"""Obtains services/applications for a template It obtains all the services/applications associated to a template :param request: The operation request. :param env_template_id: The environment template id with contains the serv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def index(self, request, env_template_id, path):
"""Obtains services/applications for a template It obtains all the services/applications associated to a template :param request: The operation request. :param env_template_id: The environment template id with contains the services :param pa... | the_stack_v2_python_sparse | murano/api/v1/template_applications.py | openstack/murano | train | 94 | |
e9560d463e5144538e379603b5e3d8e3baa7d891 | [
"grid = gd.makeGrid(grid_type, **grid_kwargs)\nwith scipyio.FortranFile(filename, mode='r') as f:\n print('Reading input from {0}'.format(filename))\n return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())",
"with scipyio.FortranFile(filename, mode='w') as f:\n print('Writing output to ... | <|body_start_0|>
grid = gd.makeGrid(grid_type, **grid_kwargs)
with scipyio.FortranFile(filename, mode='r') as f:
print('Reading input from {0}'.format(filename))
return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())
<|end_body_0|>
<|body_start_1|>
with... | Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats | SciPyFortranFileIOHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_75kplus_train_002426 | 23,117 | permissive | [
{
"docstring": "Load a field from a unformatted fortran file using a method from scipy Arguments: filename: string; full path of the file to load grid_type: string; keyword specifying what type of grid to use **grid_kwargs: keyword dictionary; keyword arguments giving parameters of the grid fieldname, timeslice... | 2 | stack_v2_sparse_classes_30k_train_022576 | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | 08b627238c4bfa39026820c6116c1ed71f453b22 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False,... | the_stack_v2_python_sparse | Dynamic_HD_Scripts/Dynamic_HD_Scripts/base/iohelper.py | ThomasRiddick/DynamicHD | train | 1 |
eea60ad92b847edb5f9854240c2da5fa07d695cd | [
"string = ''\nstack = [root]\nwhile stack:\n node = stack.pop(0)\n if node is None:\n string += 'null,'\n continue\n else:\n string += f'{node.val},'\n stack.extend([node.left, node.right])\nreturn f'[{string[:-1]}]'",
"nodes = data.strip('[').strip(']').split(',')\nheader = nodes... | <|body_start_0|>
string = ''
stack = [root]
while stack:
node = stack.pop(0)
if node is None:
string += 'null,'
continue
else:
string += f'{node.val},'
stack.extend([node.left, node.right])
re... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002427 | 1,676 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_014787 | 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:... | b47280681276ec7001efa3d0dbb9c354ca5c6abc | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
string = ''
stack = [root]
while stack:
node = stack.pop(0)
if node is None:
string += 'null,'
continue
... | the_stack_v2_python_sparse | 算法训练营/07-递归/297/广度优先遍历.py | youguanxinqing/RoadOfDSA | train | 0 | |
d2f78ecdeebd6e8cc9bf5f0c758446a9ae56dfca | [
"self.loss_function = loss_function\nself.metrics = metrics\nself._store_kwargs(kwargs, {'optimizer__', 'kernel_regularizer__', 'hidden_dense_layer__'})\nsuper().__init__(n_hidden_set_layers=n_hidden_set_layers, n_hidden_set_units=n_hidden_set_units, n_hidden_joint_layers=n_hidden_joint_layers, n_hidden_joint_units... | <|body_start_0|>
self.loss_function = loss_function
self.metrics = metrics
self._store_kwargs(kwargs, {'optimizer__', 'kernel_regularizer__', 'hidden_dense_layer__'})
super().__init__(n_hidden_set_layers=n_hidden_set_layers, n_hidden_set_units=n_hidden_set_units, n_hidden_joint_layers=n_... | FATEDiscreteChoiceFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FATEDiscreteChoiceFunction:
def __init__(self, n_hidden_set_layers=2, n_hidden_set_units=2, loss_function='categorical_hinge', metrics=('categorical_accuracy',), n_hidden_joint_layers=32, n_hidden_joint_units=32, activation='selu', kernel_initializer='lecun_normal', kernel_regularizer=l2, optimi... | stack_v2_sparse_classes_75kplus_train_002428 | 5,578 | permissive | [
{
"docstring": "Create a FATE-network architecture for leaning discrete choice function. The first-aggregate-then-evaluate approach learns an embedding of each object and then aggregates that into a context representation :math:`\\\\mu_{C(x)}` and then scores each object :math:`x` using a generalized utility fu... | 2 | null | Implement the Python class `FATEDiscreteChoiceFunction` described below.
Class description:
Implement the FATEDiscreteChoiceFunction class.
Method signatures and docstrings:
- def __init__(self, n_hidden_set_layers=2, n_hidden_set_units=2, loss_function='categorical_hinge', metrics=('categorical_accuracy',), n_hidden... | Implement the Python class `FATEDiscreteChoiceFunction` described below.
Class description:
Implement the FATEDiscreteChoiceFunction class.
Method signatures and docstrings:
- def __init__(self, n_hidden_set_layers=2, n_hidden_set_units=2, loss_function='categorical_hinge', metrics=('categorical_accuracy',), n_hidden... | d05ca1d5202f0cfd6bea0805bb1c20c86853d770 | <|skeleton|>
class FATEDiscreteChoiceFunction:
def __init__(self, n_hidden_set_layers=2, n_hidden_set_units=2, loss_function='categorical_hinge', metrics=('categorical_accuracy',), n_hidden_joint_layers=32, n_hidden_joint_units=32, activation='selu', kernel_initializer='lecun_normal', kernel_regularizer=l2, optimi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FATEDiscreteChoiceFunction:
def __init__(self, n_hidden_set_layers=2, n_hidden_set_units=2, loss_function='categorical_hinge', metrics=('categorical_accuracy',), n_hidden_joint_layers=32, n_hidden_joint_units=32, activation='selu', kernel_initializer='lecun_normal', kernel_regularizer=l2, optimizer=SGD, batch... | the_stack_v2_python_sparse | csrank/discretechoice/fate_discrete_choice.py | Charismaticzone/cs-ranking | train | 0 | |
b60abee824efde5d51e958cc28248f23a2410e01 | [
"username = self.cleaned_data.get('username')\nuser_obj = models.UserInfo.objects.filter(username=username)\nif not user_obj:\n return username\nelse:\n raise ValidationError('该用户已存在')",
"password = self.cleaned_data.get('password')\nrepwd = self.cleaned_data.get('re_pwd')\nif password == repwd:\n return... | <|body_start_0|>
username = self.cleaned_data.get('username')
user_obj = models.UserInfo.objects.filter(username=username)
if not user_obj:
return username
else:
raise ValidationError('该用户已存在')
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data.... | 注册form表单校验 | RegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
"""注册form表单校验"""
def clean_username(self):
"""校验用户是否存在 :return:"""
<|body_0|>
def clean(self):
"""校验两次输入的密码是否一致 :return:"""
<|body_1|>
def clean_email(self):
"""校验注册邮箱是否已经注册 :return:"""
<|body_2|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_002429 | 2,622 | no_license | [
{
"docstring": "校验用户是否存在 :return:",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "校验两次输入的密码是否一致 :return:",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "校验注册邮箱是否已经注册 :return:",
"name": "clean_email",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_045617 | Implement the Python class `RegisterForm` described below.
Class description:
注册form表单校验
Method signatures and docstrings:
- def clean_username(self): 校验用户是否存在 :return:
- def clean(self): 校验两次输入的密码是否一致 :return:
- def clean_email(self): 校验注册邮箱是否已经注册 :return: | Implement the Python class `RegisterForm` described below.
Class description:
注册form表单校验
Method signatures and docstrings:
- def clean_username(self): 校验用户是否存在 :return:
- def clean(self): 校验两次输入的密码是否一致 :return:
- def clean_email(self): 校验注册邮箱是否已经注册 :return:
<|skeleton|>
class RegisterForm:
"""注册form表单校验"""
... | 7768b74164ad6e3b9337b1f5aed043ec209fcddb | <|skeleton|>
class RegisterForm:
"""注册form表单校验"""
def clean_username(self):
"""校验用户是否存在 :return:"""
<|body_0|>
def clean(self):
"""校验两次输入的密码是否一致 :return:"""
<|body_1|>
def clean_email(self):
"""校验注册邮箱是否已经注册 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterForm:
"""注册form表单校验"""
def clean_username(self):
"""校验用户是否存在 :return:"""
username = self.cleaned_data.get('username')
user_obj = models.UserInfo.objects.filter(username=username)
if not user_obj:
return username
else:
raise Validatio... | the_stack_v2_python_sparse | files/ce2dcf55-e457-4610-a495-c725f3aa7ace/图书馆系统/cnblog/Blog/blog_forms.py | cs4224485/Flaskd- | train | 0 |
2d4cf910b53788f14de604a6e540f28bb9ddb851 | [
"self.columns = [NameColumn(), InitialBalanceColumn(transactionTable), InitialDateColumn(transactionTable), CurrentBalanceColumn()]\naccounts = Accounts.all()\nKaoTableWidget.__init__(self, accounts, self.columns)",
"balanceColumnIndex = self.getColumnIndex(CurrentBalanceColumn)\nfor row in range(self.rowCount())... | <|body_start_0|>
self.columns = [NameColumn(), InitialBalanceColumn(transactionTable), InitialDateColumn(transactionTable), CurrentBalanceColumn()]
accounts = Accounts.all()
KaoTableWidget.__init__(self, accounts, self.columns)
<|end_body_0|>
<|body_start_1|>
balanceColumnIndex = self.g... | The Account Table Widget View | AccountTableWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountTableWidget:
"""The Account Table Widget View"""
def __init__(self, transactionTable):
"""Initialize the Account Table Widget"""
<|body_0|>
def tabSelected(self):
"""Update the Current Balance Column"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_002430 | 1,113 | no_license | [
{
"docstring": "Initialize the Account Table Widget",
"name": "__init__",
"signature": "def __init__(self, transactionTable)"
},
{
"docstring": "Update the Current Balance Column",
"name": "tabSelected",
"signature": "def tabSelected(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021168 | Implement the Python class `AccountTableWidget` described below.
Class description:
The Account Table Widget View
Method signatures and docstrings:
- def __init__(self, transactionTable): Initialize the Account Table Widget
- def tabSelected(self): Update the Current Balance Column | Implement the Python class `AccountTableWidget` described below.
Class description:
The Account Table Widget View
Method signatures and docstrings:
- def __init__(self, transactionTable): Initialize the Account Table Widget
- def tabSelected(self): Update the Current Balance Column
<|skeleton|>
class AccountTableWid... | 57c909c8581bef3b66388038a1cf5edda426ecf9 | <|skeleton|>
class AccountTableWidget:
"""The Account Table Widget View"""
def __init__(self, transactionTable):
"""Initialize the Account Table Widget"""
<|body_0|>
def tabSelected(self):
"""Update the Current Balance Column"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountTableWidget:
"""The Account Table Widget View"""
def __init__(self, transactionTable):
"""Initialize the Account Table Widget"""
self.columns = [NameColumn(), InitialBalanceColumn(transactionTable), InitialDateColumn(transactionTable), CurrentBalanceColumn()]
accounts = Acc... | the_stack_v2_python_sparse | src/Qt/GUI/Account/account_table_widget.py | cloew/PersonalAccountingSoftware | train | 0 |
305bb73d639297ce46a08da0e2f6a2d7be0985d7 | [
"if len(set(nums1)) <= len(set(nums2)):\n return [each for each in set(nums1) if each in set(nums2)]\nreturn [each for each in set(nums2) if each in set(nums1)]",
"res = []\nfrom collections import Counter\nn1 = Counter(nums1)\nfor each in nums2:\n if each in n1.keys() and each not in res:\n res.appe... | <|body_start_0|>
if len(set(nums1)) <= len(set(nums2)):
return [each for each in set(nums1) if each in set(nums2)]
return [each for each in set(nums2) if each in set(nums1)]
<|end_body_0|>
<|body_start_1|>
res = []
from collections import Counter
n1 = Counter(nums1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]""... | stack_v2_sparse_classes_75kplus_train_002431 | 1,445 | no_license | [
{
"docstring": "Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersection",
"signature": "def intersection(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect... | 3 | stack_v2_sparse_classes_30k_train_005474 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1, nums2): Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection1(self, nums1, nums2): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1, nums2): Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersection1(self, nums1, nums2): :typ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersection1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def intersection(self, nums1, nums2):
"""Time: O(n + m) Space: O(n + m) :type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
if len(set(nums1)) <= len(set(nums2)):
return [each for each in set(nums1) if each in set(nums2)]
return [each for each in se... | the_stack_v2_python_sparse | LeetCode/BinarySearch/349_intersection_of_two_arrays.py | XyK0907/for_work | train | 0 | |
fcb18b3e0942a7b3ab26df37e331b191b6b181de | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.is_active = True\nuser.save()\nif Site._meta.installed:\n current_site = Site.objects.get_current()\nemail_subject = 'Activate Y... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.is_active = True
user.save()
if Site._meta.installed:
... | Custom user model manager where email is the unique identifiers for authentication instead of usernames. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus_train_002432 | 14,522 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | stack_v2_sparse_classes_30k_test_003015 | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | a2f26cf7dd2cb2f16fd58c0b9f3a97f74f8d26c1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueEr... | the_stack_v2_python_sparse | app/users/models.py | emuswailit/dockerized-one | train | 0 |
f2e803dd230038d8b8d23aeb5ce8df480f6dae8c | [
"super().__init__(model=model, optimizer=optimizer, criterion=criterion, train_mb_size=train_mb_size, train_epochs=train_epochs, eval_mb_size=eval_mb_size, device=device, plugins=plugins, evaluator=evaluator, eval_every=eval_every)\nself._is_fitted = False\nself._experiences: List[TDatasetExperience] = []",
"self... | <|body_start_0|>
super().__init__(model=model, optimizer=optimizer, criterion=criterion, train_mb_size=train_mb_size, train_epochs=train_epochs, eval_mb_size=eval_mb_size, device=device, plugins=plugins, evaluator=evaluator, eval_every=eval_every)
self._is_fitted = False
self._experiences: List[... | Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :py:class:`JointTraining` adapts its own d... | JointTraining | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :... | stack_v2_sparse_classes_75kplus_train_002433 | 7,173 | permissive | [
{
"docstring": "Init. :param model: PyTorch model. :param optimizer: PyTorch optimizer. :param criterion: loss function. :param train_mb_size: mini-batch size for training. :param train_epochs: number of training epochs. :param eval_mb_size: mini-batch size for eval. :param device: PyTorch device to run the mod... | 4 | stack_v2_sparse_classes_30k_train_016777 | Implement the Python class `JointTraining` described below.
Class description:
Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound f... | Implement the Python class `JointTraining` described below.
Class description:
Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound f... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :py:class:`Joi... | the_stack_v2_python_sparse | avalanche/training/supervised/joint_training.py | ContinualAI/avalanche | train | 1,424 |
aa38db5eb532ae0799f852a2b06ff8f6ea10f080 | [
"for i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] == target:\n return True\nreturn False",
"res = []\nfor x in matrix:\n res.extend(x)\nreturn target in res",
"res = []\nfor x in matrix:\n res.extend(x)\nres.sort()\nleft, right = (0, len(res) - 1)\nwhile l... | <|body_start_0|>
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] == target:
return True
return False
<|end_body_0|>
<|body_start_1|>
res = []
for x in matrix:
res.extend(x)
return target in res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
<|body_0|>
def searchMatrix1(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. ... | stack_v2_sparse_classes_75kplus_train_002434 | 1,839 | no_license | [
{
"docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)",... | 4 | stack_v2_sparse_classes_30k_train_024132 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)
- def searchMatrix1(self, matrix, target): Purpo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)
- def searchMatrix1(self, matrix, target): Purpo... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
<|body_0|>
def searchMatrix1(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
"""Purpose: searches 2D matrix, and returns True if target is found. Time complexity: O(n*2)"""
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] == target:
return True
... | the_stack_v2_python_sparse | search2dMatrix.py | tashakim/puzzles_python | train | 8 | |
c2a4def907bfa3172043466f151509bb36b94795 | [
"if isinstance(value, bool):\n return int(value)\ntry:\n result = value\n if value and isinstance(value, str):\n float_value = float(value)\n result = int(float_value)\n if result != float_value:\n raise ValueError()\n if not is_integer(result):\n raise ValueError(... | <|body_start_0|>
if isinstance(value, bool):
return int(value)
try:
result = value
if value and isinstance(value, str):
float_value = float(value)
result = int(float_value)
if result != float_value:
r... | Built-in scalar which handle int values. | ScalarInt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
<|body_0|>
def coerce_input(self, value... | stack_v2_sparse_classes_75kplus_train_002435 | 3,477 | permissive | [
{
"docstring": "Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int",
"name": "coerce_output",
"signature": "def coerce_output(self, value: Any) -> int"
},
{
"docstring": "Coerce the user input from variable value. :param va... | 3 | stack_v2_sparse_classes_30k_train_028069 | Implement the Python class `ScalarInt` described below.
Class description:
Built-in scalar which handle int values.
Method signatures and docstrings:
- def coerce_output(self, value: Any) -> int: Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: in... | Implement the Python class `ScalarInt` described below.
Class description:
Built-in scalar which handle int values.
Method signatures and docstrings:
- def coerce_output(self, value: Any) -> int: Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: in... | 421c1e937f553d6a5bf2f30154022c0d77053cfb | <|skeleton|>
class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
<|body_0|>
def coerce_input(self, value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScalarInt:
"""Built-in scalar which handle int values."""
def coerce_output(self, value: Any) -> int:
"""Coerce the resolved value for output. :param value: value to coerce :type value: Any :return: the coerced value :rtype: int"""
if isinstance(value, bool):
return int(value)... | the_stack_v2_python_sparse | tartiflette/scalar/builtins/int.py | tartiflette/tartiflette | train | 586 |
ecc393ae1bed5f81482a5b70b2ab9ba42f2d07f0 | [
"x1 = u[0]\nx2 = u[1]\ndfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])\nreturn dfdu",
"me = self.dtype_u(2)\nme[:] = spsolve(sp.eye(2) - factor * dfdu, rhs)\nreturn me"
] | <|body_start_0|>
x1 = u[0]
x2 = u[1]
dfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])
return dfdu
<|end_body_0|>
<|body_start_1|>
me = self.dtype_u(2)
me[:] = spsolve(sp.eye(2) - factor * dfdu, rhs)
return me
<|end_bo... | vanderpol_jac | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
<|body_0|>
def solve_system_jacobian(self, dfdu, rhs, factor, u0, t):
"""Simple linear solver for (I-dtA)u = rhs Args: df... | stack_v2_sparse_classes_75kplus_train_002436 | 1,228 | permissive | [
{
"docstring": "Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix",
"name": "eval_jacobian",
"signature": "def eval_jacobian(self, u)"
},
{
"docstring": "Simple linear solver for (I-dtA)u = rhs Args: dfdu: the Jacobian of the RHS of the ODE rhs: rig... | 2 | stack_v2_sparse_classes_30k_train_014319 | Implement the Python class `vanderpol_jac` described below.
Class description:
Implement the vanderpol_jac class.
Method signatures and docstrings:
- def eval_jacobian(self, u): Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix
- def solve_system_jacobian(self, dfdu, rhs... | Implement the Python class `vanderpol_jac` described below.
Class description:
Implement the vanderpol_jac class.
Method signatures and docstrings:
- def eval_jacobian(self, u): Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix
- def solve_system_jacobian(self, dfdu, rhs... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
<|body_0|>
def solve_system_jacobian(self, dfdu, rhs, factor, u0, t):
"""Simple linear solver for (I-dtA)u = rhs Args: df... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
x1 = u[0]
x2 = u[1]
dfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])
return df... | the_stack_v2_python_sparse | pySDC/projects/parallelSDC/Van_der_Pol_implicit_Jac.py | Parallel-in-Time/pySDC | train | 30 | |
a7fc9ea66c40cb77aae30d708d8a426f2d3af7b0 | [
"initial = super(ProductUpdateView, self).get_initial()\ntags = self.get_object().tag_set.all()\ninitial['tags'] = ', '.join([x.title for x in tags])\n'\\n tag_list = []\\n for x in tags:\\n tag_list.append(x.title)\\n '\nreturn initial",
"valid_data = super(ProductUpdateView, self... | <|body_start_0|>
initial = super(ProductUpdateView, self).get_initial()
tags = self.get_object().tag_set.all()
initial['tags'] = ', '.join([x.title for x in tags])
'\n tag_list = []\n for x in tags:\n tag_list.append(x.title)\n '
return initial
<|e... | Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html` | ProductUpdateView | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductUpdateView:
"""Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html`"""
def get_initial(self):
... | stack_v2_sparse_classes_75kplus_train_002437 | 19,979 | permissive | [
{
"docstring": "Retrieves initial data for the form fields.",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Saves valid data or rasies error.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | null | Implement the Python class `ProductUpdateView` described below.
Class description:
Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html`
... | Implement the Python class `ProductUpdateView` described below.
Class description:
Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html`
... | f4da02a5b475f400d41afd453bfbed6cd53ba087 | <|skeleton|>
class ProductUpdateView:
"""Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html`"""
def get_initial(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductUpdateView:
"""Displays view for seller to update product data. (ProductManagerMixin, SubmitBtnMixin, MultiSlugMixin, UpdateView) :model:`products.Product` **Context** Form for updating fields in an existing product **Template** :template:`form.html`"""
def get_initial(self):
"""Retrieves ... | the_stack_v2_python_sparse | frontend/src/products/views.py | ANRGUSC/I3-Core | train | 11 |
ecbe0dd297a7f63ad7d1f206b4fb1d042dd85d11 | [
"self.Helpers = Helpers('ClassifierServerClient')\nself.confs = self.Helpers.confs\nself.addr = 'http://' + self.confs['Classifier']['IP'] + ':' + str(self.confs['Classifier']['Port']) + '/Inference'\nself.headers = {'content-type': 'image/jpeg'}\nself.Helpers.logger.info('Classifier class initialization complete.'... | <|body_start_0|>
self.Helpers = Helpers('ClassifierServerClient')
self.confs = self.Helpers.confs
self.addr = 'http://' + self.confs['Classifier']['IP'] + ':' + str(self.confs['Classifier']['Port']) + '/Inference'
self.headers = {'content-type': 'image/jpeg'}
self.Helpers.logger.... | AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server. | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server."""
def __init__(self):
"""Initializes the AML/ALL Detection System Movidius NCS1 Classifier Server Cli... | stack_v2_sparse_classes_75kplus_train_002438 | 2,708 | permissive | [
{
"docstring": "Initializes the AML/ALL Detection System Movidius NCS1 Classifier Server Client Class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Sends image to the inference API endpoint.",
"name": "send",
"signature": "def send(self, imagePath)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_053473 | Implement the Python class `Client` described below.
Class description:
AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server.
Method signatures and docstrings:
- def __init__(self): Initializes the AML... | Implement the Python class `Client` described below.
Class description:
AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server.
Method signatures and docstrings:
- def __init__(self): Initializes the AML... | 7169d103d3f02d7d920ecd4207678d9fa5d93c35 | <|skeleton|>
class Client:
"""AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server."""
def __init__(self):
"""Initializes the AML/ALL Detection System Movidius NCS1 Classifier Server Cli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Client:
"""AML/ALL Detection System Movidius NCS1 Classifier Server Client Class Sends single or multiple images to the AML/ALL Detection System Movidius NCS1 Classifier API server."""
def __init__(self):
"""Initializes the AML/ALL Detection System Movidius NCS1 Classifier Server Client Class."""... | the_stack_v2_python_sparse | Classifiers/Movidius/NCS/Tensorflow/V1/Client.py | rishabhbanga/ALL-Detection-System-2019 | train | 0 |
eda6b273f73d98bc05a7604427661747202d6b20 | [
"queryset = MetricModel.query\ngenerator = queryset.values()\nreturn {'metrics': [value for value in generator]}",
"metrics = MetricList.parser.parse_args()['metrics']\nfor data in metrics:\n name = data['name']\n if '.' in name:\n data['package'], data['display_name'] = name.split('.')\n else:\n ... | <|body_start_0|>
queryset = MetricModel.query
generator = queryset.values()
return {'metrics': [value for value in generator]}
<|end_body_0|>
<|body_start_1|>
metrics = MetricList.parser.parse_args()['metrics']
for data in metrics:
name = data['name']
if ... | MetricList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricList:
def get(self):
"""Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved."""
<|body_0|>
def post(self):
"""Create a list of metrics. --- tags: - Metrics parameters: - name: "Request b... | stack_v2_sparse_classes_75kplus_train_002439 | 8,070 | permissive | [
{
"docstring": "Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a list of metrics. --- tags: - Metrics parameters: - name: \"Request body:\" in:... | 2 | stack_v2_sparse_classes_30k_train_030618 | Implement the Python class `MetricList` described below.
Class description:
Implement the MetricList class.
Method signatures and docstrings:
- def get(self): Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved.
- def post(self): Create a list... | Implement the Python class `MetricList` described below.
Class description:
Implement the MetricList class.
Method signatures and docstrings:
- def get(self): Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved.
- def post(self): Create a list... | c79a4906d1b9b2f5d4c167fdf932a5138d9fef5a | <|skeleton|>
class MetricList:
def get(self):
"""Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved."""
<|body_0|>
def post(self):
"""Create a list of metrics. --- tags: - Metrics parameters: - name: "Request b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetricList:
def get(self):
"""Retrieve the complete list of metrics. --- tags: - Metrics responses: 200: description: List of metrics successfully retrieved."""
queryset = MetricModel.query
generator = queryset.values()
return {'metrics': [value for value in generator]}
de... | the_stack_v2_python_sparse | src/squash/api_v1/metric.py | lsst-sqre/squash-api | train | 0 | |
13a44ff707b196421888c9cb6d4451bb9f776f21 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.find_all('span', {'typeof': 'v:Breadcrumb'})[-1].text\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = 'https://www.idqidian.us/images/noavailable.jpg'\nlogger.info('Novel cover: %s', sel... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.find_all('span', {'typeof': 'v:Breadcrumb'})[-1].text
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = 'https://www.idqidian.us/images/noav... | IdqidianCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdqidianCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002440 | 2,703 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_028832 | Implement the Python class `IdqidianCrawler` described below.
Class description:
Implement the IdqidianCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html ... | Implement the Python class `IdqidianCrawler` described below.
Class description:
Implement the IdqidianCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html ... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class IdqidianCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdqidianCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.find_all('span', {'typeof': 'v:Breadcrumb'})[-1].text
logger.info('Novel title: %... | the_stack_v2_python_sparse | lncrawl/sources/idqidian.py | NNTin/lightnovel-crawler | train | 2 | |
8a3e9d4242b3d6d14a099314dde1b9f17797ff14 | [
"group = self._client.create(name=name, domain=domain, description=description)\nif check:\n self.check_group_presence(group, must_present=True)\n assert_that(group.name, equal_to(name))\n if domain:\n assert_that(group.domain, equal_to(domain))\n if description:\n assert_that(group.descri... | <|body_start_0|>
group = self._client.create(name=name, domain=domain, description=description)
if check:
self.check_group_presence(group, must_present=True)
assert_that(group.name, equal_to(name))
if domain:
assert_that(group.domain, equal_to(domain))... | Group steps. | GroupSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupSteps:
"""Group steps."""
def create_group(self, name, domain=None, description=None, check=True):
"""Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`): the domain of the group description (str): the descript... | stack_v2_sparse_classes_75kplus_train_002441 | 4,589 | no_license | [
{
"docstring": "Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`): the domain of the group description (str): the description of the group Returns: keystoneclient.v3.groups.Group: the created group returned from server Raises: TimeoutExpired... | 5 | stack_v2_sparse_classes_30k_train_041303 | Implement the Python class `GroupSteps` described below.
Class description:
Group steps.
Method signatures and docstrings:
- def create_group(self, name, domain=None, description=None, check=True): Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`)... | Implement the Python class `GroupSteps` described below.
Class description:
Group steps.
Method signatures and docstrings:
- def create_group(self, name, domain=None, description=None, check=True): Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`)... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class GroupSteps:
"""Group steps."""
def create_group(self, name, domain=None, description=None, check=True):
"""Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`): the domain of the group description (str): the descript... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupSteps:
"""Group steps."""
def create_group(self, name, domain=None, description=None, check=True):
"""Step to create a group. Args: name (str): the name of the group domain (str or class `keystoneclient.v3.domains.Domain`): the domain of the group description (str): the description of the gr... | the_stack_v2_python_sparse | stepler/keystone/steps/groups.py | Mirantis/stepler | train | 16 |
1531b877bbfb0f250517af622409323212a06169 | [
"hosts = self.hosts_up(context)\nif not hosts:\n msg = _('Is the appropriate service running?')\n raise exception.NoValidHost(reason=msg)\nreturn random.choice(hosts)",
"dests = []\nfor container in containers:\n host = self._schedule(context)\n host_state = dict(host=host, nodename=None, limits=None)... | <|body_start_0|>
hosts = self.hosts_up(context)
if not hosts:
msg = _('Is the appropriate service running?')
raise exception.NoValidHost(reason=msg)
return random.choice(hosts)
<|end_body_0|>
<|body_start_1|>
dests = []
for container in containers:
... | Implements Scheduler as a random node selector. | ChanceScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _schedule(self, context):
"""Picks a host that is up at random."""
<|body_0|>
def select_destinations(self, context, containers, extra_spec):
"""Selects random destinations."""
<|b... | stack_v2_sparse_classes_75kplus_train_002442 | 1,614 | permissive | [
{
"docstring": "Picks a host that is up at random.",
"name": "_schedule",
"signature": "def _schedule(self, context)"
},
{
"docstring": "Selects random destinations.",
"name": "select_destinations",
"signature": "def select_destinations(self, context, containers, extra_spec)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046223 | Implement the Python class `ChanceScheduler` described below.
Class description:
Implements Scheduler as a random node selector.
Method signatures and docstrings:
- def _schedule(self, context): Picks a host that is up at random.
- def select_destinations(self, context, containers, extra_spec): Selects random destina... | Implement the Python class `ChanceScheduler` described below.
Class description:
Implements Scheduler as a random node selector.
Method signatures and docstrings:
- def _schedule(self, context): Picks a host that is up at random.
- def select_destinations(self, context, containers, extra_spec): Selects random destina... | 4fa358474ee337f27bfaf8b98e886cc8d10ada50 | <|skeleton|>
class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _schedule(self, context):
"""Picks a host that is up at random."""
<|body_0|>
def select_destinations(self, context, containers, extra_spec):
"""Selects random destinations."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChanceScheduler:
"""Implements Scheduler as a random node selector."""
def _schedule(self, context):
"""Picks a host that is up at random."""
hosts = self.hosts_up(context)
if not hosts:
msg = _('Is the appropriate service running?')
raise exception.NoValid... | the_stack_v2_python_sparse | zun/scheduler/chance_scheduler.py | openstack/zun | train | 89 |
ffd5dcbecfbd84789bdd971d207a898a480ad2a4 | [
"self.center_loc = center_loc\nself.tent_loc = tent_loc\nself.tent_list = [tent_loc]",
"for i in self.tent_list:\n if new_tent_loc.dist_from(i) < 0.5:\n return False\nlen_original = len(self.tent_list)\nlen_new = len(self.tent_list)\nfor i in self.tent_list:\n if new_tent_loc.x > i.x:\n contin... | <|body_start_0|>
self.center_loc = center_loc
self.tent_loc = tent_loc
self.tent_list = [tent_loc]
<|end_body_0|>
<|body_start_1|>
for i in self.tent_list:
if new_tent_loc.dist_from(i) < 0.5:
return False
len_original = len(self.tent_list)
len... | A MITCampus is a Campus that contains tents | MITCampus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MITCampus:
"""A MITCampus is a Campus that contains tents"""
def __init__(self, center_loc, tent_loc=Location(0, 0)):
"""Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_loc with a tent at location tent_loc"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_002443 | 8,760 | no_license | [
{
"docstring": "Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_loc with a tent at location tent_loc",
"name": "__init__",
"signature": "def __init__(self, center_loc, tent_loc=Location(0, 0))"
},
{
"docstring": "Assumes new_tent_loc is a... | 4 | stack_v2_sparse_classes_30k_train_045485 | Implement the Python class `MITCampus` described below.
Class description:
A MITCampus is a Campus that contains tents
Method signatures and docstrings:
- def __init__(self, center_loc, tent_loc=Location(0, 0)): Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_... | Implement the Python class `MITCampus` described below.
Class description:
A MITCampus is a Campus that contains tents
Method signatures and docstrings:
- def __init__(self, center_loc, tent_loc=Location(0, 0)): Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_... | 3e9c0108e9725daa1f1cf4cca98778e76cb37c48 | <|skeleton|>
class MITCampus:
"""A MITCampus is a Campus that contains tents"""
def __init__(self, center_loc, tent_loc=Location(0, 0)):
"""Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_loc with a tent at location tent_loc"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MITCampus:
"""A MITCampus is a Campus that contains tents"""
def __init__(self, center_loc, tent_loc=Location(0, 0)):
"""Assumes center_loc and tent_loc are Location objects Initializes a new Campus centered at location center_loc with a tent at location tent_loc"""
self.center_loc = cent... | the_stack_v2_python_sparse | EdX/6001/Problem Sets/final.py | traghuram/Python-Personal | train | 1 |
c21f72cd2aa1c6f6ccf9b3da5b556ae1f5f02f3e | [
"if user is None or password is None:\n user = config.basicauth_user\n password = config.basicauth_password\nif realm is None:\n if hasattr(config, 'realm'):\n realm = config.realm\n else:\n realm = 'Auth'\nself.user = user\nself.password = password\nself.realm = realm",
"self.func = fun... | <|body_start_0|>
if user is None or password is None:
user = config.basicauth_user
password = config.basicauth_password
if realm is None:
if hasattr(config, 'realm'):
realm = config.realm
else:
realm = 'Auth'
self.us... | A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here... | basicauth | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class basicauth:
"""A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here..."""
def __init__(self, user=None, password=None, realm=None):
"""An initialization method ... | stack_v2_sparse_classes_75kplus_train_002444 | 8,941 | permissive | [
{
"docstring": "An initialization method of decorator. Authentication information can be passed at initialization time, by using arguments. In case no arguments gives, it uses informations at configration. :param user : an user name of BASIC authentication. :param password : a passowrd of BASIC authentication. ... | 2 | stack_v2_sparse_classes_30k_train_003328 | Implement the Python class `basicauth` described below.
Class description:
A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here...
Method signatures and docstrings:
- def __init__(self, user=No... | Implement the Python class `basicauth` described below.
Class description:
A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here...
Method signatures and docstrings:
- def __init__(self, user=No... | e1209f7d44d1c59ff9d373b7d89d414f31a9c28b | <|skeleton|>
class basicauth:
"""A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here..."""
def __init__(self, user=None, password=None, realm=None):
"""An initialization method ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class basicauth:
"""A decorator that catch method access, supply BASIC authentication. You may decorate handler methods in controllers like this:: @basicauth() def some_funk(self): # your code here..."""
def __init__(self, user=None, password=None, realm=None):
"""An initialization method of decorator.... | the_stack_v2_python_sparse | aha/controller/decorator.py | Letractively/aha-gae | train | 0 |
1cdf9c41102a50fa2735f2a8e68c22ef0f2cd0fd | [
"mock_res1 = '{\"number\": 1,\"pull_request\":{\"url\": \"https://api.github.com/repos/sjain3097/new/pulls/1\",\"user\":{\"login\":\"choukseyabhishek\"}, \"created_at\":\"2018-04-26 22:06:19Z\",\"changed_files\":3,\"comments_url\":\"https://api.github.com/repos/sjain3097/new/pulls/2/commits\" , \"commits\":3, \"he... | <|body_start_0|>
mock_res1 = '{"number": 1,"pull_request":{"url": "https://api.github.com/repos/sjain3097/new/pulls/1","user":{"login":"choukseyabhishek"}, "created_at":"2018-04-26 22:06:19Z","changed_files":3,"comments_url":"https://api.github.com/repos/sjain3097/new/pulls/2/commits" , "commits":3, "head":{"r... | Testcase for Repository | TestDataTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDataTest:
"""Testcase for Repository"""
def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_size):
"""test pushed_time method"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002445 | 4,431 | no_license | [
{
"docstring": "test pushed_time method",
"name": "test_fetcher",
"signature": "def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_size)"
},
{
"docstring": "test for pu... | 2 | stack_v2_sparse_classes_30k_train_039726 | Implement the Python class `TestDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_s... | Implement the Python class `TestDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_s... | 4b31f2c7d87c3ad15c7ab8b71a94abdada1faf63 | <|skeleton|>
class TestDataTest:
"""Testcase for Repository"""
def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_size):
"""test pushed_time method"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDataTest:
"""Testcase for Repository"""
def test_fetcher(self, mock_open_pr_count, mock_get_forks_count, mock_pushed_time, mock_watchers_count, mock_get_repo_probability, mock_test_total_contribution, mock_pull_request_size):
"""test pushed_time method"""
mock_res1 = '{"number": 1,"pu... | the_stack_v2_python_sparse | unit_test/test_data_test.py | iamthebj/GitPred | train | 0 |
d84cce916183b132f7125b9fd080e76479bd902d | [
"self.valid_set = set()\nself.invalid_set = set()\nif not isinstance(is_required, bool):\n raise InvalidFieldException('Allow_none must be type bool!')\nif accept_none is not None and (not isinstance(accept_none, bool)):\n raise InvalidFieldException('Accept_none must be type bool!')\nif is_required and accep... | <|body_start_0|>
self.valid_set = set()
self.invalid_set = set()
if not isinstance(is_required, bool):
raise InvalidFieldException('Allow_none must be type bool!')
if accept_none is not None and (not isinstance(accept_none, bool)):
raise InvalidFieldException('Acc... | Field | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Field:
def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs):
"""basic init function: check type of is_required :param is_required: allow feild is none or not :param args: None :param kwargs: None"""
<|body_0|>
def generate(self):
"""basic fu... | stack_v2_sparse_classes_75kplus_train_002446 | 27,120 | no_license | [
{
"docstring": "basic init function: check type of is_required :param is_required: allow feild is none or not :param args: None :param kwargs: None",
"name": "__init__",
"signature": "def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs)"
},
{
"docstring": "basic functio... | 2 | stack_v2_sparse_classes_30k_train_034149 | Implement the Python class `Field` described below.
Class description:
Implement the Field class.
Method signatures and docstrings:
- def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs): basic init function: check type of is_required :param is_required: allow feild is none or not :param arg... | Implement the Python class `Field` described below.
Class description:
Implement the Field class.
Method signatures and docstrings:
- def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs): basic init function: check type of is_required :param is_required: allow feild is none or not :param arg... | ee4871b1324cb5047a3284d1491184dfb0e21ca5 | <|skeleton|>
class Field:
def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs):
"""basic init function: check type of is_required :param is_required: allow feild is none or not :param args: None :param kwargs: None"""
<|body_0|>
def generate(self):
"""basic fu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Field:
def __init__(self, is_required: bool, accept_none: bool=None, *args, **kwargs):
"""basic init function: check type of is_required :param is_required: allow feild is none or not :param args: None :param kwargs: None"""
self.valid_set = set()
self.invalid_set = set()
if no... | the_stack_v2_python_sparse | Utils/Interface/Field.py | zghnwsq/EasySelenium | train | 0 | |
d1c519fda4a012e470a8c4636bf5cfe0e9952a1c | [
"if return_str:\n warnings.warn(\"Parameter 'return_str' has been deprecated and should no longer be used.\", category=DeprecationWarning, stacklevel=2)\nfor regexp, substitution in self.STARTING_QUOTES:\n text = regexp.sub(substitution, text)\nfor regexp, substitution in self.PUNCTUATION:\n text = regexp.... | <|body_start_0|>
if return_str:
warnings.warn("Parameter 'return_str' has been deprecated and should no longer be used.", category=DeprecationWarning, stacklevel=2)
for regexp, substitution in self.STARTING_QUOTES:
text = regexp.sub(substitution, text)
for regexp, substit... | The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The tokenizer is "destructive" such that the regexes applied will munge the input string to ... | NLTKWordTokenizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NLTKWordTokenizer:
"""The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The tokenizer is "destructive" such that the re... | stack_v2_sparse_classes_75kplus_train_002447 | 9,214 | permissive | [
{
"docstring": "Return a tokenized copy of `text`. >>> from nltk.tokenize import NLTKWordTokenizer >>> s = '''Good muffins cost $3.88 (roughly 3,36 euros)\\\\nin New York. Please buy me\\\\ntwo of them.\\\\nThanks.''' >>> NLTKWordTokenizer().tokenize(s) # doctest: +NORMALIZE_WHITESPACE ['Good', 'muffins', 'cost... | 2 | null | Implement the Python class `NLTKWordTokenizer` described below.
Class description:
The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The toke... | Implement the Python class `NLTKWordTokenizer` described below.
Class description:
The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The toke... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class NLTKWordTokenizer:
"""The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The tokenizer is "destructive" such that the re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NLTKWordTokenizer:
"""The NLTK tokenizer that has improved upon the TreebankWordTokenizer. This is the method that is invoked by ``word_tokenize()``. It assumes that the text has already been segmented into sentences, e.g. using ``sent_tokenize()``. The tokenizer is "destructive" such that the regexes applied... | the_stack_v2_python_sparse | nltk/tokenize/destructive.py | nltk/nltk | train | 11,860 |
c0890029fb42fdbb67aaa15c92e8d6b2fc059af7 | [
"with self.monitor('aggregate curves', autoflush=True):\n acc.eff_ruptures += pmap_by_grp.eff_ruptures\n for grp_id in pmap_by_grp:\n if pmap_by_grp[grp_id]:\n acc[grp_id] |= pmap_by_grp[grp_id]\n self.nsites.append(len(pmap_by_grp[grp_id]))\n for srcid, (srcweight, nsites, calc_ti... | <|body_start_0|>
with self.monitor('aggregate curves', autoflush=True):
acc.eff_ruptures += pmap_by_grp.eff_ruptures
for grp_id in pmap_by_grp:
if pmap_by_grp[grp_id]:
acc[grp_id] |= pmap_by_grp[grp_id]
self.nsites.append(len(pmap_by_gr... | Classical PSHA calculator | PSHACalculator | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSHACalculator:
"""Classical PSHA calculator"""
def agg_dicts(self, acc, pmap_by_grp):
"""Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary grp_id -> ProbabilityMap"""
<|body_0|>
def zer... | stack_v2_sparse_classes_75kplus_train_002448 | 15,779 | permissive | [
{
"docstring": "Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary grp_id -> ProbabilityMap",
"name": "agg_dicts",
"signature": "def agg_dicts(self, acc, pmap_by_grp)"
},
{
"docstring": "Initial accumulator, a di... | 5 | stack_v2_sparse_classes_30k_train_029512 | Implement the Python class `PSHACalculator` described below.
Class description:
Classical PSHA calculator
Method signatures and docstrings:
- def agg_dicts(self, acc, pmap_by_grp): Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary gr... | Implement the Python class `PSHACalculator` described below.
Class description:
Classical PSHA calculator
Method signatures and docstrings:
- def agg_dicts(self, acc, pmap_by_grp): Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary gr... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class PSHACalculator:
"""Classical PSHA calculator"""
def agg_dicts(self, acc, pmap_by_grp):
"""Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary grp_id -> ProbabilityMap"""
<|body_0|>
def zer... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PSHACalculator:
"""Classical PSHA calculator"""
def agg_dicts(self, acc, pmap_by_grp):
"""Aggregate dictionaries of hazard curves by updating the accumulator. :param acc: accumulator dictionary :param pmap_by_grp: dictionary grp_id -> ProbabilityMap"""
with self.monitor('aggregate curves'... | the_stack_v2_python_sparse | openquake/calculators/classical.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
a44b3b8fa63a9e02143b192204018d84a2c44bf1 | [
"self.classifier = classifier\nself.prior = prior\nself.true_observation = true_observation",
"parameters = next(iter(parameters_dict.values()))\nlog_ratio = self.classifier(torch.cat((parameters, self.true_observation)).reshape(1, -1))\nif isinstance(self.prior, distributions.Uniform):\n potential = -(log_rat... | <|body_start_0|>
self.classifier = classifier
self.prior = prior
self.true_observation = true_observation
<|end_body_0|>
<|body_start_1|>
parameters = next(iter(parameters_dict.values()))
log_ratio = self.classifier(torch.cat((parameters, self.true_observation)).reshape(1, -1))
... | Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood. | NeuralPotentialFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralPotentialFunction:
"""Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood."""
def __init__(self, classifier, prior, true_observation):
""":param neural_likelihood: Binary classifier which has ... | stack_v2_sparse_classes_75kplus_train_002449 | 21,120 | no_license | [
{
"docstring": ":param neural_likelihood: Binary classifier which has learned an approximation to the likelihood up to a constant. :param prior: Distribution object with 'log_prob' method. :param true_observation: torch.Tensor containing true observation x0.",
"name": "__init__",
"signature": "def __ini... | 2 | stack_v2_sparse_classes_30k_train_052681 | Implement the Python class `NeuralPotentialFunction` described below.
Class description:
Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood.
Method signatures and docstrings:
- def __init__(self, classifier, prior, true_observation... | Implement the Python class `NeuralPotentialFunction` described below.
Class description:
Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood.
Method signatures and docstrings:
- def __init__(self, classifier, prior, true_observation... | c3919c251084763e305f99df3923497a130371a2 | <|skeleton|>
class NeuralPotentialFunction:
"""Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood."""
def __init__(self, classifier, prior, true_observation):
""":param neural_likelihood: Binary classifier which has ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralPotentialFunction:
"""Implementation of a potential function for Pyro MCMC which uses a binary classifier to evaluate a quantity proportional to the likelihood."""
def __init__(self, classifier, prior, true_observation):
""":param neural_likelihood: Binary classifier which has learned an ap... | the_stack_v2_python_sparse | src/inference/sre.py | conormdurkan/lfi | train | 41 |
939f3ce3c3a38e64decd126a45bd928aa6b8ed04 | [
"session_data = self.get_current_user()\nif not session_data:\n return self.write({'errcode': '4101', 'errmsg': 'False'})\ntry:\n order_id = self.json_args['order_id']\n comment = self.json_args['comment']\n user_id = session_data['user_id']\nexcept Exception as e:\n return self.write({'errcode': '41... | <|body_start_0|>
session_data = self.get_current_user()
if not session_data:
return self.write({'errcode': '4101', 'errmsg': 'False'})
try:
order_id = self.json_args['order_id']
comment = self.json_args['comment']
user_id = session_data['user_id']
... | 取消订单及评价 | UpdateOrderHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateOrderHandler:
"""取消订单及评价"""
def post(self):
"""评价"""
<|body_0|>
def get(self):
"""取消订单"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
session_data = self.get_current_user()
if not session_data:
return self.write({'errc... | stack_v2_sparse_classes_75kplus_train_002450 | 6,765 | no_license | [
{
"docstring": "评价",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "取消订单",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033167 | Implement the Python class `UpdateOrderHandler` described below.
Class description:
取消订单及评价
Method signatures and docstrings:
- def post(self): 评价
- def get(self): 取消订单 | Implement the Python class `UpdateOrderHandler` described below.
Class description:
取消订单及评价
Method signatures and docstrings:
- def post(self): 评价
- def get(self): 取消订单
<|skeleton|>
class UpdateOrderHandler:
"""取消订单及评价"""
def post(self):
"""评价"""
<|body_0|>
def get(self):
"""取消订... | 49c660e6d7f70c7b82bd3ce9d3a4752dcacbf2ad | <|skeleton|>
class UpdateOrderHandler:
"""取消订单及评价"""
def post(self):
"""评价"""
<|body_0|>
def get(self):
"""取消订单"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateOrderHandler:
"""取消订单及评价"""
def post(self):
"""评价"""
session_data = self.get_current_user()
if not session_data:
return self.write({'errcode': '4101', 'errmsg': 'False'})
try:
order_id = self.json_args['order_id']
comment = self.js... | the_stack_v2_python_sparse | handlers/orderhandler.py | pyhcss/piaojia | train | 0 |
c4c34f18ec233e71b53cd86850acc7f2b54d5e41 | [
"super(TCPSender, self).__init__(address, port, False, logging.getLogger('gds_sender'))\nself.frame = True\nself.data = bytearray()\nself.deframes = []",
"with self.lock:\n self.frame = False\nself.write(b'Register FSW\\n')\nwith self.lock:\n self.frame = True",
"while True:\n while len(self.data) > 4 ... | <|body_start_0|>
super(TCPSender, self).__init__(address, port, False, logging.getLogger('gds_sender'))
self.frame = True
self.data = bytearray()
self.deframes = []
<|end_body_0|>
<|body_start_1|>
with self.lock:
self.frame = False
self.write(b'Register FSW\n... | Interface class defining necessary functions to talk to the GDS. | TCPSender | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPSender:
"""Interface class defining necessary functions to talk to the GDS."""
def __init__(self, address='127.0.0.1', port=50050):
"""Initialize this interface with the address and port needed to connect to the GDS. :param address: Address of the tcp server. Default 127.0.0.1 :pa... | stack_v2_sparse_classes_75kplus_train_002451 | 3,095 | permissive | [
{
"docstring": "Initialize this interface with the address and port needed to connect to the GDS. :param address: Address of the tcp server. Default 127.0.0.1 :param port: port of the tcp server. Default: 50000",
"name": "__init__",
"signature": "def __init__(self, address='127.0.0.1', port=50050)"
},... | 5 | null | Implement the Python class `TCPSender` described below.
Class description:
Interface class defining necessary functions to talk to the GDS.
Method signatures and docstrings:
- def __init__(self, address='127.0.0.1', port=50050): Initialize this interface with the address and port needed to connect to the GDS. :param ... | Implement the Python class `TCPSender` described below.
Class description:
Interface class defining necessary functions to talk to the GDS.
Method signatures and docstrings:
- def __init__(self, address='127.0.0.1', port=50050): Initialize this interface with the address and port needed to connect to the GDS. :param ... | d19cade2140231b4e0879b2f6ab4a62b25792dea | <|skeleton|>
class TCPSender:
"""Interface class defining necessary functions to talk to the GDS."""
def __init__(self, address='127.0.0.1', port=50050):
"""Initialize this interface with the address and port needed to connect to the GDS. :param address: Address of the tcp server. Default 127.0.0.1 :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TCPSender:
"""Interface class defining necessary functions to talk to the GDS."""
def __init__(self, address='127.0.0.1', port=50050):
"""Initialize this interface with the address and port needed to connect to the GDS. :param address: Address of the tcp server. Default 127.0.0.1 :param port: por... | the_stack_v2_python_sparse | Gds/src/fprime_gds/common/adapters/sender.py | nodcah/fprime | train | 0 |
62309d4b50706ee07aab779cee7b5f97d3f5fac7 | [
"super(DistanceToSolution, self).__init__(name=name)\nself.solution = solution\nself.norm = norm or None",
"t, y = new_state\ny_pred = self.solution(t)\nreturn jnp.linalg.norm(y - y_pred, ord=self.norm)"
] | <|body_start_0|>
super(DistanceToSolution, self).__init__(name=name)
self.solution = solution
self.norm = norm or None
<|end_body_0|>
<|body_start_1|>
t, y = new_state
y_pred = self.solution(t)
return jnp.linalg.norm(y - y_pred, ord=self.norm)
<|end_body_1|>
| Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected. | DistanceToSolution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistanceToSolution:
"""Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected."""
def __init__(self, solution: Callable, norm: Union[Text, int]=None, name: Text=None):
"""Solution distance metr... | stack_v2_sparse_classes_75kplus_train_002452 | 2,413 | permissive | [
{
"docstring": "Solution distance metric constructor. Args: solution: Callable, of signature t -> y(t) giving the ODE solution at time t. norm: Norm identifier for use in jnp.linalg.norm. name: Optional name identifier.",
"name": "__init__",
"signature": "def __init__(self, solution: Callable, norm: Uni... | 2 | null | Implement the Python class `DistanceToSolution` described below.
Class description:
Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected.
Method signatures and docstrings:
- def __init__(self, solution: Callable, norm: Union[... | Implement the Python class `DistanceToSolution` described below.
Class description:
Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected.
Method signatures and docstrings:
- def __init__(self, solution: Callable, norm: Union[... | 0bcb5d4834f6001b2a3e54bd5e000e86bbedf221 | <|skeleton|>
class DistanceToSolution:
"""Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected."""
def __init__(self, solution: Callable, norm: Union[Text, int]=None, name: Text=None):
"""Solution distance metr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DistanceToSolution:
"""Tracks distance of an ODE state vector to the state vector of a known solution. This is useful to test whether an integrator performs as expected."""
def __init__(self, solution: Callable, norm: Union[Text, int]=None, name: Text=None):
"""Solution distance metric constructo... | the_stack_v2_python_sparse | ode_explorer/metrics/metric.py | nicholasjng/ode-explorer | train | 5 |
be9e5709153f2ad6984388b3e761927d4611f4fc | [
"super().__init__()\nassert use_sigmoid is True, 'Only sigmoid varifocal loss supported now.'\nassert alpha >= 0.0\nself.use_sigmoid = use_sigmoid\nself.alpha = alpha\nself.gamma = gamma\nself.iou_weighted = iou_weighted\nself.reduction = reduction\nself.loss_weight = loss_weight",
"assert reduction_override in (... | <|body_start_0|>
super().__init__()
assert use_sigmoid is True, 'Only sigmoid varifocal loss supported now.'
assert alpha >= 0.0
self.use_sigmoid = use_sigmoid
self.alpha = alpha
self.gamma = gamma
self.iou_weighted = iou_weighted
self.reduction = reductio... | VarifocalLoss | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the predicti... | stack_v2_sparse_classes_75kplus_train_002453 | 5,749 | permissive | [
{
"docstring": "`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to True. alpha (float, optional): A balance factor for the negative part of Varifocal Loss, which is different from the alpha of Focal Loss. De... | 2 | stack_v2_sparse_classes_30k_train_046184 | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None: `Varifo... | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None: `Varifo... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the predicti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VarifocalLoss:
def __init__(self, use_sigmoid: bool=True, alpha: float=0.75, gamma: float=2.0, iou_weighted: bool=True, reduction: str='mean', loss_weight: float=1.0) -> None:
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/losses/varifocal_loss.py | alldatacenter/alldata | train | 774 | |
f147fbc04b7afbce6f08e4ed838e05c75f6061fe | [
"if len(edges) == 0:\n return\nself.inPhotoTarget = aggregator((edge.incoming.photos_target for edge in edges))\nself.inPhotoOther = aggregator((edge.incoming.photos_other for edge in edges))\nself.inMutuals = aggregator((edge.incoming.mut_friends for edge in edges))\nif require_incoming:\n self.inPostLikes =... | <|body_start_0|>
if len(edges) == 0:
return
self.inPhotoTarget = aggregator((edge.incoming.photos_target for edge in edges))
self.inPhotoOther = aggregator((edge.incoming.photos_other for edge in edges))
self.inMutuals = aggregator((edge.incoming.mut_friends for edge in edges... | Edge aggregation, scoring and ranking. | EdgeAggregate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregat... | stack_v2_sparse_classes_75kplus_train_002454 | 33,126 | no_license | [
{
"docstring": "Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregator: a function over properties of Edges (default: max)",
"name": "__init__",
"signature": "def __init__(self, edges, aggregator=max, require_incoming=True, ... | 2 | stack_v2_sparse_classes_30k_test_000756 | Implement the Python class `EdgeAggregate` described below.
Class description:
Edge aggregation, scoring and ranking.
Method signatures and docstrings:
- def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True): Apply the aggregator to the given Edges to initialize instance data. edges:... | Implement the Python class `EdgeAggregate` described below.
Class description:
Edge aggregation, scoring and ranking.
Method signatures and docstrings:
- def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True): Apply the aggregator to the given Edges to initialize instance data. edges:... | bebd10d910c87dabc0680692684a3e551e92dd2a | <|skeleton|>
class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EdgeAggregate:
"""Edge aggregation, scoring and ranking."""
def __init__(self, edges, aggregator=max, require_incoming=True, require_outgoing=True):
"""Apply the aggregator to the given Edges to initialize instance data. edges: sequence of Edges from a primary to all friends aggregator: a functio... | the_stack_v2_python_sparse | targetshare/models/datastructs.py | edgeflip/edgeflip | train | 1 |
58084122f432a51e940bc912c977e4a59393de90 | [
"if root is None:\n return []\nqueue = [root]\ndata = []\n\ndef dfs():\n if queue == []:\n return\n node = queue.pop(0)\n data.append(node.val)\n if node.left:\n queue.append(node.left)\n dfs()\n else:\n data.append(None)\n if node.right:\n queue.append(node.r... | <|body_start_0|>
if root is None:
return []
queue = [root]
data = []
def dfs():
if queue == []:
return
node = queue.pop(0)
data.append(node.val)
if node.left:
queue.append(node.left)
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002455 | 1,631 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002564 | 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:... | cdf785856941f7ea546aee56ebcda8801cbb04de | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return []
queue = [root]
data = []
def dfs():
if queue == []:
return
node = queue.pop(0)
... | the_stack_v2_python_sparse | ProgrammingQuestions/leetcode/297.py | strawsyz/straw | train | 2 | |
a25cfd7578aaee0e0c84a1200d7c5c14db1fd9b2 | [
"n = len(nums)\nif n * k == 0:\n return []\nif k == 1:\n return nums\nleft, right = ([0] * n, [0] * n)\nleft[0], right[n - 1] = (nums[0], nums[n - 1])\nfor lft_idx in range(1, n):\n if lft_idx % k == 0:\n left[lft_idx] = nums[lft_idx]\n else:\n left[lft_idx] = max(left[lft_idx - 1], nums[l... | <|body_start_0|>
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
left, right = ([0] * n, [0] * n)
left[0], right[n - 1] = (nums[0], nums[n - 1])
for lft_idx in range(1, n):
if lft_idx % k == 0:
left[lft_idx... | SlidingWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def get_all_max(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque / D... | stack_v2_sparse_classes_75kplus_train_002456 | 3,324 | no_license | [
{
"docstring": "Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:",
"name": "get_all_max_",
"signature": "def get_all_max_(self, nums: List[int], k: int) -> List[int]"
},
{
"docstring": "Approach: Deque / Doubly Linked List Time Complexity: O(N) - since ea... | 2 | stack_v2_sparse_classes_30k_train_022193 | Implement the Python class `SlidingWindow` described below.
Class description:
Implement the SlidingWindow class.
Method signatures and docstrings:
- def get_all_max_(self, nums: List[int], k: int) -> List[int]: Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def get_all_ma... | Implement the Python class `SlidingWindow` described below.
Class description:
Implement the SlidingWindow class.
Method signatures and docstrings:
- def get_all_max_(self, nums: List[int], k: int) -> List[int]: Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:
- def get_all_ma... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
<|body_0|>
def get_all_max(self, nums: List[int], k: int) -> List[int]:
"""Approach: Deque / D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlidingWindow:
def get_all_max_(self, nums: List[int], k: int) -> List[int]:
"""Approach: DP Time Complexity: O(N) Space Complexity: O(N) :param nums: :param k: :return:"""
n = len(nums)
if n * k == 0:
return []
if k == 1:
return nums
left, right... | the_stack_v2_python_sparse | amazon/sliding_window/sliding_window_maximum.py | Shiv2157k/leet_code | train | 1 | |
17a72335b0bb0fafd28aea427463b994b9be72be | [
"self.mq = []\nself.mc = 0\nself.sq = []\nself.sc = 0",
"if self.mc == 0:\n heappush(self.mq, -num)\n self.mc += 1\n return\nif self.sc == 0:\n self.sc += 1\n if num < -self.mq[0]:\n tmp = heappop(self.mq)\n heappush(self.sq, -tmp)\n heappush(self.mq, -num)\n else:\n ... | <|body_start_0|>
self.mq = []
self.mc = 0
self.sq = []
self.sc = 0
<|end_body_0|>
<|body_start_1|>
if self.mc == 0:
heappush(self.mq, -num)
self.mc += 1
return
if self.sc == 0:
self.sc += 1
if num < -self.mq[0]:... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_002457 | 2,285 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_028995 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 690adf05774a1c500d6c9160223dab7bcc38ccc1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.mq = []
self.mc = 0
self.sq = []
self.sc = 0
def addNum(self, num):
""":type num: int :rtype: void"""
if self.mc == 0:
heappush(self.mq, -num)
... | the_stack_v2_python_sparse | 295. Find Median from Data Stream.py | supersj/LeetCode | train | 2 | |
118ff04d45d8338e389dc12398e83ade2fa80861 | [
"super().__init__(env)\nself.get_robot_act = get_robot_act\nassert 0 <= beta <= 1\nself.beta = beta\nself.traj_accum = None\nself.save_dir = save_dir\nself._last_obs = None\nself._done_before = True\nself._is_reset = False",
"self.traj_accum = rollout.TrajectoryAccumulator()\nobs = self.env.reset()\nself._last_ob... | <|body_start_0|>
super().__init__(env)
self.get_robot_act = get_robot_act
assert 0 <= beta <= 1
self.beta = beta
self.traj_accum = None
self.save_dir = save_dir
self._last_obs = None
self._done_before = True
self._is_reset = False
<|end_body_0|>
<... | Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories. | InteractiveTrajectoryCollector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def ... | stack_v2_sparse_classes_75kplus_train_002458 | 15,864 | permissive | [
{
"docstring": "Trajectory collector constructor. Args: env: environment to sample trajectories from. get_robot_act: get a single robot action that can be substituted for human action. Takes a single observation as input & returns a single action. beta: fraction of the time to use action given to .step() instea... | 3 | null | Implement the Python class `InteractiveTrajectoryCollector` described below.
Class description:
Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automa... | Implement the Python class `InteractiveTrajectoryCollector` described below.
Class description:
Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automa... | 202b50e9d4373b4cc9bfe6a14e1208fd9ba63dc3 | <|skeleton|>
class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from of the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def __init__(self... | the_stack_v2_python_sparse | src/imitation/algorithms/dagger.py | doitdodo/imitation-1 | train | 0 |
918ea9b37cf9ddc6b8bba942907fb87ed0c765ca | [
"super(ProjectedBDG, self).__init__(name=name)\nself._num_sites = num_sites\nwith self._enter_variable_scope():\n self._pairing_matrix = tf.get_variable('pairing_matrix', shape=[1, num_sites, num_sites], dtype=tf.float32)",
"batch_size = inputs.shape[0]\nn_sites = self._num_sites\nmask = tf.einsum('ij,ik->ijk'... | <|body_start_0|>
super(ProjectedBDG, self).__init__(name=name)
self._num_sites = num_sites
with self._enter_variable_scope():
self._pairing_matrix = tf.get_variable('pairing_matrix', shape=[1, num_sites, num_sites], dtype=tf.float32)
<|end_body_0|>
<|body_start_1|>
batch_siz... | P-BDG module. | ProjectedBDG | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectedBDG:
"""P-BDG module."""
def __init__(self, num_sites: int, name: str='projected_bdg'):
"""Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module."""
<|body_0|>
def _build(self, inputs: tf.Tensor) -> tf.Tensor:
"""C... | stack_v2_sparse_classes_75kplus_train_002459 | 40,960 | permissive | [
{
"docstring": "Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module.",
"name": "__init__",
"signature": "def __init__(self, num_sites: int, name: str='projected_bdg')"
},
{
"docstring": "Connects the P-BDG module into the graph with input `inputs`. Args:... | 3 | stack_v2_sparse_classes_30k_train_052995 | Implement the Python class `ProjectedBDG` described below.
Class description:
P-BDG module.
Method signatures and docstrings:
- def __init__(self, num_sites: int, name: str='projected_bdg'): Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module.
- def _build(self, inputs: tf.Te... | Implement the Python class `ProjectedBDG` described below.
Class description:
P-BDG module.
Method signatures and docstrings:
- def __init__(self, num_sites: int, name: str='projected_bdg'): Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module.
- def _build(self, inputs: tf.Te... | 3a298ceab53bf6403c1a4037cb22431499891d79 | <|skeleton|>
class ProjectedBDG:
"""P-BDG module."""
def __init__(self, num_sites: int, name: str='projected_bdg'):
"""Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module."""
<|body_0|>
def _build(self, inputs: tf.Tensor) -> tf.Tensor:
"""C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectedBDG:
"""P-BDG module."""
def __init__(self, num_sites: int, name: str='projected_bdg'):
"""Constructs a projected BDG module. Args: num_sites: Number of sites. name: Name of the module."""
super(ProjectedBDG, self).__init__(name=name)
self._num_sites = num_sites
w... | the_stack_v2_python_sparse | cgs_vmc/wavefunctions.py | ClarkResearchGroup/cgs-vmc | train | 18 |
acf4c73c79b518e78bca131c5f02448595510438 | [
"self.vec = vec2d\nself.next_index = 0\nself.list_index = 0\nself.list_len = [len(one) for one in vec2d]",
"if self.next_index == self.list_len[self.list_index] - 1:\n num = self.vec[self.list_index][self.next_index]\n self.next_index = 0\n self.list_index += 1\nelse:\n num = self.vec[self.list_index]... | <|body_start_0|>
self.vec = vec2d
self.next_index = 0
self.list_index = 0
self.list_len = [len(one) for one in vec2d]
<|end_body_0|>
<|body_start_1|>
if self.next_index == self.list_len[self.list_index] - 1:
num = self.vec[self.list_index][self.next_index]
... | Vector2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_002460 | 1,245 | permissive | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_037146 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | cb2ed3524431aea2b204fe66797f9850bbe506a9 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec = vec2d
self.next_index = 0
self.list_index = 0
self.list_len = [len(one) for one in vec2d]
def next(self):
""":rtype: int"""
if se... | the_stack_v2_python_sparse | archive/python/Python/unsorted/251.flatten-2d-vector.py | linfengzhou/LeetCode | train | 0 | |
5a42022912e928b317a6e250a5544de75f5eeab8 | [
"res = []\nsList = list(s)\n\ndef backtrack(x):\n if x == len(sList) - 1:\n res.append(''.join(sList))\n return\n temp_set = set()\n for i in range(x, len(sList)):\n if sList[i] in temp_set:\n continue\n temp_set.add(sList[i])\n sList[i], sList[x] = (sList[x], ... | <|body_start_0|>
res = []
sList = list(s)
def backtrack(x):
if x == len(sList) - 1:
res.append(''.join(sList))
return
temp_set = set()
for i in range(x, len(sList)):
if sList[i] in temp_set:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ArrangementOfStrings(self, s):
"""字符串排列——》回溯递归 :param s: :return:"""
<|body_0|>
def ResverNum(self, nums: List[int], n: int) -> List[int]:
"""逆序数组中前n个数字 :param nums: :return:"""
<|body_1|>
def next_n(n):
"""find next n [POJ2453] :pa... | stack_v2_sparse_classes_75kplus_train_002461 | 3,562 | no_license | [
{
"docstring": "字符串排列——》回溯递归 :param s: :return:",
"name": "ArrangementOfStrings",
"signature": "def ArrangementOfStrings(self, s)"
},
{
"docstring": "逆序数组中前n个数字 :param nums: :return:",
"name": "ResverNum",
"signature": "def ResverNum(self, nums: List[int], n: int) -> List[int]"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_002510 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ArrangementOfStrings(self, s): 字符串排列——》回溯递归 :param s: :return:
- def ResverNum(self, nums: List[int], n: int) -> List[int]: 逆序数组中前n个数字 :param nums: :return:
- def next_n(n): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ArrangementOfStrings(self, s): 字符串排列——》回溯递归 :param s: :return:
- def ResverNum(self, nums: List[int], n: int) -> List[int]: 逆序数组中前n个数字 :param nums: :return:
- def next_n(n): ... | 32941ee052d0985a9569441d314378700ff4d225 | <|skeleton|>
class Solution:
def ArrangementOfStrings(self, s):
"""字符串排列——》回溯递归 :param s: :return:"""
<|body_0|>
def ResverNum(self, nums: List[int], n: int) -> List[int]:
"""逆序数组中前n个数字 :param nums: :return:"""
<|body_1|>
def next_n(n):
"""find next n [POJ2453] :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def ArrangementOfStrings(self, s):
"""字符串排列——》回溯递归 :param s: :return:"""
res = []
sList = list(s)
def backtrack(x):
if x == len(sList) - 1:
res.append(''.join(sList))
return
temp_set = set()
for i in... | the_stack_v2_python_sparse | cecilia-python/剑指offer/chapter-1/ArrangementOfStrings.py | Cecilia520/algorithmic-learning-leetcode | train | 7 | |
91327e86c170196166a744d15a98ae8706c5a90f | [
"translations = []\nif verify_assets is None:\n verify_assets = not settings.FEATURES.get('FALLBACK_TO_ENGLISH_TRANSCRIPTS')\nsub, other_langs = (transcripts['sub'], transcripts['transcripts'])\nif verify_assets:\n all_langs = dict(**other_langs)\n if sub:\n all_langs.update({'en': sub})\n for la... | <|body_start_0|>
translations = []
if verify_assets is None:
verify_assets = not settings.FEATURES.get('FALLBACK_TO_ENGLISH_TRANSCRIPTS')
sub, other_langs = (transcripts['sub'], transcripts['transcripts'])
if verify_assets:
all_langs = dict(**other_langs)
... | Mixin class for transcript functionality. This is necessary for VideoBlock. | VideoTranscriptsMixin | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoTranscriptsMixin:
"""Mixin class for transcript functionality. This is necessary for VideoBlock."""
def available_translations(self, transcripts, verify_assets=None, is_bumper=False):
"""Return a list of language codes for which we have transcripts. Arguments: verify_assets (boo... | stack_v2_sparse_classes_75kplus_train_002462 | 40,372 | permissive | [
{
"docstring": "Return a list of language codes for which we have transcripts. Arguments: verify_assets (boolean): If True, checks to ensure that the transcripts really exist in the contentstore. If False, we just look at the VideoBlock fields and do not query the contentstore. One reason we might do this is to... | 3 | null | Implement the Python class `VideoTranscriptsMixin` described below.
Class description:
Mixin class for transcript functionality. This is necessary for VideoBlock.
Method signatures and docstrings:
- def available_translations(self, transcripts, verify_assets=None, is_bumper=False): Return a list of language codes for... | Implement the Python class `VideoTranscriptsMixin` described below.
Class description:
Mixin class for transcript functionality. This is necessary for VideoBlock.
Method signatures and docstrings:
- def available_translations(self, transcripts, verify_assets=None, is_bumper=False): Return a list of language codes for... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class VideoTranscriptsMixin:
"""Mixin class for transcript functionality. This is necessary for VideoBlock."""
def available_translations(self, transcripts, verify_assets=None, is_bumper=False):
"""Return a list of language codes for which we have transcripts. Arguments: verify_assets (boo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoTranscriptsMixin:
"""Mixin class for transcript functionality. This is necessary for VideoBlock."""
def available_translations(self, transcripts, verify_assets=None, is_bumper=False):
"""Return a list of language codes for which we have transcripts. Arguments: verify_assets (boolean): If Tru... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/video_module/transcripts_utils.py | luque/better-ways-of-thinking-about-software | train | 3 |
1cded47a04023c2124ed85482e56f1a5cd25fdd3 | [
"assert type(seg) == tuple, repr(seg)\nassert len(seg) in (2, 3), repr(seg)\nself.sc, self.offs = seg[:2]\nassert type(self.sc) == int, repr(self.sc)\nif len(seg) == 3:\n assert type(self.offs) == int, repr(self.offs)\n assert self.sc > 0, repr(seg)\n t = seg[2]\n if type(t) == bytes:\n self.text... | <|body_start_0|>
assert type(seg) == tuple, repr(seg)
assert len(seg) in (2, 3), repr(seg)
self.sc, self.offs = seg[:2]
assert type(self.sc) == int, repr(self.sc)
if len(seg) == 3:
assert type(self.offs) == int, repr(self.offs)
assert self.sc > 0, repr(seg... | LayoutSegment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
<|body_0|>
def subseg(self, text, start, end):
"""Return a "sub-segment" list containing segment structures that make up a portion of this segment. A list is returned to ha... | stack_v2_sparse_classes_75kplus_train_002463 | 18,219 | permissive | [
{
"docstring": "Create object from line layout segment structure",
"name": "__init__",
"signature": "def __init__(self, seg)"
},
{
"docstring": "Return a \"sub-segment\" list containing segment structures that make up a portion of this segment. A list is returned to handle cases where wide chara... | 2 | stack_v2_sparse_classes_30k_val_002177 | Implement the Python class `LayoutSegment` described below.
Class description:
Implement the LayoutSegment class.
Method signatures and docstrings:
- def __init__(self, seg): Create object from line layout segment structure
- def subseg(self, text, start, end): Return a "sub-segment" list containing segment structure... | Implement the Python class `LayoutSegment` described below.
Class description:
Implement the LayoutSegment class.
Method signatures and docstrings:
- def __init__(self, seg): Create object from line layout segment structure
- def subseg(self, text, start, end): Return a "sub-segment" list containing segment structure... | 95b7a061eabd6f2b607fba79e007186030f02720 | <|skeleton|>
class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
<|body_0|>
def subseg(self, text, start, end):
"""Return a "sub-segment" list containing segment structures that make up a portion of this segment. A list is returned to ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayoutSegment:
def __init__(self, seg):
"""Create object from line layout segment structure"""
assert type(seg) == tuple, repr(seg)
assert len(seg) in (2, 3), repr(seg)
self.sc, self.offs = seg[:2]
assert type(self.sc) == int, repr(self.sc)
if len(seg) == 3:
... | the_stack_v2_python_sparse | Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/urwid/text_layout.py | icl-rocketry/Avionics | train | 9 | |
4ad4ec20e4c531c09d65e1cbda8523cf4ecdf366 | [
"super().__init__(scenario)\nself._ln_resp = self._calc_ln_resp()\nself._ln_std = self._calc_ln_std()",
"s = self._scenario\nc = self.COEFF\ndist = np.sqrt(s.dist_rup ** 2 + c.c_11 ** 2)\nlog10_resp = c.c_1 + c.c_2 * s.mag + c.c_3 * s.mag ** 2 + (c.c_4 + c.c_5 * s.mag) * np.minimum(np.log10(dist), np.log10(70.0))... | <|body_start_0|>
super().__init__(scenario)
self._ln_resp = self._calc_ln_resp()
self._ln_std = self._calc_ln_std()
<|end_body_0|>
<|body_start_1|>
s = self._scenario
c = self.COEFF
dist = np.sqrt(s.dist_rup ** 2 + c.c_11 ** 2)
log10_resp = c.c_1 + c.c_2 * s.mag ... | Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario | PezeshkZandiehTavakoli2011 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PezeshkZandiehTavakoli2011:
"""Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario"""
def __init__(self, scenario: mod... | stack_v2_sparse_classes_75kplus_train_002464 | 2,495 | permissive | [
{
"docstring": "Initialize the model.",
"name": "__init__",
"signature": "def __init__(self, scenario: model.Scenario)"
},
{
"docstring": "Calculate the natural logarithm of the response. Returns ------- ln_resp : class:`np.array`: natural log of the response",
"name": "_calc_ln_resp",
"... | 3 | stack_v2_sparse_classes_30k_train_037855 | Implement the Python class `PezeshkZandiehTavakoli2011` described below.
Class description:
Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario
... | Implement the Python class `PezeshkZandiehTavakoli2011` described below.
Class description:
Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario
... | ac07a9b9e23f0e43c957ce45164772e0d7641566 | <|skeleton|>
class PezeshkZandiehTavakoli2011:
"""Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario"""
def __init__(self, scenario: mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PezeshkZandiehTavakoli2011:
"""Pezeshk, Zandieh, and Tavakoli (2011, :cite:`pezeshk11`) model. Developed for the Eastern North America with a reference velocity of 2000 m/s. Parameters ---------- scenario : :class:`pygmm.model.Scenario` earthquake scenario"""
def __init__(self, scenario: model.Scenario):... | the_stack_v2_python_sparse | pygmm/pezeshk_zandieh_tavakoli_2011.py | arkottke/pygmm | train | 28 |
50748c34b8af1eaaa3bab09f377e93b6d418329a | [
"html_text = get_html_text(url)\nhtml = etree.HTML(html_text)\nurls = html.xpath('//*[@id=\"top_bg\"]/div/div[4]/div[7]/ul/li/a/@href')\nreturn urls",
"page_content = get_html_text(url)\nhtml = etree.HTML(page_content)\nindex = html.xpath('//div[@class=\"xx_con\"]/p[1]/text()')\naspect = html.xpath('//div[@class=... | <|body_start_0|>
html_text = get_html_text(url)
html = etree.HTML(html_text)
urls = html.xpath('//*[@id="top_bg"]/div/div[4]/div[7]/ul/li/a/@href')
return urls
<|end_body_0|>
<|body_start_1|>
page_content = get_html_text(url)
html = etree.HTML(page_content)
index... | CrawShenZhenReport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrawShenZhenReport:
def get_info_urls_of_reports(self, url):
"""根据url获取所有年份报告的url :param url: target url :return: page_urls list"""
<|body_0|>
def get_notification_infos(self, url):
"""在通知文件页面爬取通知的内容 :param url: info url :return: base_infos, content"""
<|body... | stack_v2_sparse_classes_75kplus_train_002465 | 6,461 | no_license | [
{
"docstring": "根据url获取所有年份报告的url :param url: target url :return: page_urls list",
"name": "get_info_urls_of_reports",
"signature": "def get_info_urls_of_reports(self, url)"
},
{
"docstring": "在通知文件页面爬取通知的内容 :param url: info url :return: base_infos, content",
"name": "get_notification_infos"... | 4 | stack_v2_sparse_classes_30k_train_036791 | Implement the Python class `CrawShenZhenReport` described below.
Class description:
Implement the CrawShenZhenReport class.
Method signatures and docstrings:
- def get_info_urls_of_reports(self, url): 根据url获取所有年份报告的url :param url: target url :return: page_urls list
- def get_notification_infos(self, url): 在通知文件页面爬取通知... | Implement the Python class `CrawShenZhenReport` described below.
Class description:
Implement the CrawShenZhenReport class.
Method signatures and docstrings:
- def get_info_urls_of_reports(self, url): 根据url获取所有年份报告的url :param url: target url :return: page_urls list
- def get_notification_infos(self, url): 在通知文件页面爬取通知... | 15daf1a80c781c1c929ba063d779c0928a24b117 | <|skeleton|>
class CrawShenZhenReport:
def get_info_urls_of_reports(self, url):
"""根据url获取所有年份报告的url :param url: target url :return: page_urls list"""
<|body_0|>
def get_notification_infos(self, url):
"""在通知文件页面爬取通知的内容 :param url: info url :return: base_infos, content"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrawShenZhenReport:
def get_info_urls_of_reports(self, url):
"""根据url获取所有年份报告的url :param url: target url :return: page_urls list"""
html_text = get_html_text(url)
html = etree.HTML(html_text)
urls = html.xpath('//*[@id="top_bg"]/div/div[4]/div[7]/ul/li/a/@href')
return ... | the_stack_v2_python_sparse | catkin_ws/src/robot_python/demo/craw_government_files-master/shenzhen/craw_shenzhen_gov_reports.py | xtyzhen/Multi_arm_robot | train | 0 | |
bf94a8544743695ebd4446d0f9e9857d2b6df760 | [
"super(Artanh, self).__init__()\nself.log = Log()\nself.sub = Sub()",
"x = clip_by_value(x, -1 + eps, 1 - eps)\nout = self.log(1 + x.astype(mstype.float32))\nout = 0.5 * self.sub(out, self.log(1 - x.astype(mstype.float32)))\nreturn out"
] | <|body_start_0|>
super(Artanh, self).__init__()
self.log = Log()
self.sub = Sub()
<|end_body_0|>
<|body_start_1|>
x = clip_by_value(x, -1 + eps, 1 - eps)
out = self.log(1 + x.astype(mstype.float32))
out = 0.5 * self.sub(out, self.log(1 - x.astype(mstype.float32)))
... | artanh | Artanh | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Artanh:
"""artanh"""
def __init__(self):
"""init"""
<|body_0|>
def construct(self, x):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Artanh, self).__init__()
self.log = Log()
self.sub = Sub()
<|end_body_0... | stack_v2_sparse_classes_75kplus_train_002466 | 1,240 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | null | Implement the Python class `Artanh` described below.
Class description:
artanh
Method signatures and docstrings:
- def __init__(self): init
- def construct(self, x): construct fun | Implement the Python class `Artanh` described below.
Class description:
artanh
Method signatures and docstrings:
- def __init__(self): init
- def construct(self, x): construct fun
<|skeleton|>
class Artanh:
"""artanh"""
def __init__(self):
"""init"""
<|body_0|>
def construct(self, x):
... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Artanh:
"""artanh"""
def __init__(self):
"""init"""
<|body_0|>
def construct(self, x):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Artanh:
"""artanh"""
def __init__(self):
"""init"""
super(Artanh, self).__init__()
self.log = Log()
self.sub = Sub()
def construct(self, x):
"""construct fun"""
x = clip_by_value(x, -1 + eps, 1 - eps)
out = self.log(1 + x.astype(mstype.float32)... | the_stack_v2_python_sparse | research/nlp/hypertext/src/math_utils.py | mindspore-ai/models | train | 301 |
1171dc0c7c35755e98e2dad0917ddfc227b633d0 | [
"hostname = event.get('hostname')\nutcoffset = event.get('utcoffset')\npid = event.get('pid')\nfreq = event.get('freq')\nsoftware = '{}-{}'.format(event.get('sw_ident'), event.get('sw_ver'))\nos = event.get('sw_sys')\ndetails = event.get('details', {})\nsignature = '{hostname}|{utcoffset}|{pid}|{freq}|{software}|{o... | <|body_start_0|>
hostname = event.get('hostname')
utcoffset = event.get('utcoffset')
pid = event.get('pid')
freq = event.get('freq')
software = '{}-{}'.format(event.get('sw_ident'), event.get('sw_ver'))
os = event.get('sw_sys')
details = event.get('details', {})
... | A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events. | Worker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worke... | stack_v2_sparse_classes_75kplus_train_002467 | 21,886 | permissive | [
{
"docstring": "Get or create a worker from a Celery worker event. This method extracts the fields of a worker from a Celery worker event and constructs a signature from them. If there is an active worker with the same signature then it is returned. The signature is the only way to uniquely identify a worker.",... | 2 | stack_v2_sparse_classes_30k_train_039795 | Implement the Python class `Worker` described below.
Class description:
A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events.
Method signatures and docstrings:
- def get_or_create(cls, event: dict, ... | Implement the Python class `Worker` described below.
Class description:
A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events.
Method signatures and docstrings:
- def get_or_create(cls, event: dict, ... | 47c6377ccbfe8576b35854053d726537e533e78c | <|skeleton|>
class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Worker:
"""A worker that runs jobs placed on one or more queues. This model stores information on a worker as captured by the `overseer` service from Celery's worker monitoring events."""
def get_or_create(cls, event: dict, create=False):
"""Get or create a worker from a Celery worker event. This... | the_stack_v2_python_sparse | director/jobs/models.py | gxf1986/hub | train | 0 |
ae27651030ffafda2ce526a54c26b95238f148eb | [
"self.nshoppers = nshoppers\nself.item_freq = ci / ci.sum()\nself.item_values = pv\nself.fcount = 0\nself.shoppers = []\nfor i in range(nshoppers):\n shopper = Shopper(self.item_freq, pv)\n self.shoppers.append(shopper)",
"self.fcount += 1\norder = np.argsort(p)\nrevenue = 0.0\nfor i in range(self.nshoppers... | <|body_start_0|>
self.nshoppers = nshoppers
self.item_freq = ci / ci.sum()
self.item_values = pv
self.fcount = 0
self.shoppers = []
for i in range(nshoppers):
shopper = Shopper(self.item_freq, pv)
self.shoppers.append(shopper)
<|end_body_0|>
<|bod... | Simulate a day's worth of customers | Objective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objective:
"""Simulate a day's worth of customers"""
def __init__(self, nshoppers, ci, pv):
"""Constructor"""
<|body_0|>
def Evaluate(self, p):
"""Evaluate an arrangement of products"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nshoppers... | stack_v2_sparse_classes_75kplus_train_002468 | 6,050 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, nshoppers, ci, pv)"
},
{
"docstring": "Evaluate an arrangement of products",
"name": "Evaluate",
"signature": "def Evaluate(self, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041670 | Implement the Python class `Objective` described below.
Class description:
Simulate a day's worth of customers
Method signatures and docstrings:
- def __init__(self, nshoppers, ci, pv): Constructor
- def Evaluate(self, p): Evaluate an arrangement of products | Implement the Python class `Objective` described below.
Class description:
Simulate a day's worth of customers
Method signatures and docstrings:
- def __init__(self, nshoppers, ci, pv): Constructor
- def Evaluate(self, p): Evaluate an arrangement of products
<|skeleton|>
class Objective:
"""Simulate a day's wort... | 5445b6f90ab49339ca0fdb71e98d44e6827c95a8 | <|skeleton|>
class Objective:
"""Simulate a day's worth of customers"""
def __init__(self, nshoppers, ci, pv):
"""Constructor"""
<|body_0|>
def Evaluate(self, p):
"""Evaluate an arrangement of products"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Objective:
"""Simulate a day's worth of customers"""
def __init__(self, nshoppers, ci, pv):
"""Constructor"""
self.nshoppers = nshoppers
self.item_freq = ci / ci.sum()
self.item_values = pv
self.fcount = 0
self.shoppers = []
for i in range(nshoppers... | the_stack_v2_python_sparse | store/store.py | dayoladejo/SwarmOptimization | train | 0 |
3340300629ab60347694e3c68aee243a7e36c304 | [
"super(Derender, self).__init__()\nresnet = resnet34(pretrained=True)\nresnet_layers = list(resnet.children())\nresnet_layers.pop()\nresnet_layers.pop(0)\nresnet_layers.insert(0, nn.Conv2d(cfg.MODEL.IN_CHANNELS, 64, kernel_size=3, stride=2, padding=1))\nresnet_layers[-1] = nn.AvgPool2d(kernel_size=cfg.MODEL.POOLING... | <|body_start_0|>
super(Derender, self).__init__()
resnet = resnet34(pretrained=True)
resnet_layers = list(resnet.children())
resnet_layers.pop()
resnet_layers.pop(0)
resnet_layers.insert(0, nn.Conv2d(cfg.MODEL.IN_CHANNELS, 64, kernel_size=3, stride=2, padding=1))
... | Neural Network used for obtaining object-centric representations from scenes | Derender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
<|body_0|>
def forward... | stack_v2_sparse_classes_75kplus_train_002469 | 2,428 | no_license | [
{
"docstring": "Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters",
"name": "__init__",
"signature": "def __init__(self, cfg, attributes)"
},
{
"docstring": "Derenderer's forward pass Args: inputs: Inputs to compute forward pass on c... | 2 | stack_v2_sparse_classes_30k_train_030467 | Implement the Python class `Derender` described below.
Class description:
Neural Network used for obtaining object-centric representations from scenes
Method signatures and docstrings:
- def __init__(self, cfg, attributes): Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with exp... | Implement the Python class `Derender` described below.
Class description:
Neural Network used for obtaining object-centric representations from scenes
Method signatures and docstrings:
- def __init__(self, cfg, attributes): Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with exp... | 424cbf65fd65e912430cb99d942e2fa69235aa61 | <|skeleton|>
class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
<|body_0|>
def forward... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
super(Derender, self).__init__()
... | the_stack_v2_python_sparse | models/derender.py | AdejuwonF/intphys-renderer | train | 0 |
a8090aea15462d1009ebe53c3f7ee376db9804e6 | [
"self.module = module\nself.PlotCaseRuns = PlotCaseRuns\npass",
"odir = os.path.join(case_path, 'json_files')\nofile = os.path.join(odir, 'figure_step.json')\nPrepare_Result = self.module(case_path)\nPrepare_Result.Interpret(step=step)\nUtilities.my_assert(os.path.isfile(pr_script), AssertionError, \"%s doesn't e... | <|body_start_0|>
self.module = module
self.PlotCaseRuns = PlotCaseRuns
pass
<|end_body_0|>
<|body_start_1|>
odir = os.path.join(case_path, 'json_files')
ofile = os.path.join(odir, 'figure_step.json')
Prepare_Result = self.module(case_path)
Prepare_Result.Interpre... | A class for preparing results | PLOTTER | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PLOTTER:
"""A class for preparing results"""
def __init__(self, module, PlotCaseRuns, **kwargs):
"""Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):... | stack_v2_sparse_classes_75kplus_train_002470 | 13,097 | no_license | [
{
"docstring": "Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):",
"name": "__init__",
"signature": "def __init__(self, module, PlotCaseRuns, **kwargs)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_004654 | Implement the Python class `PLOTTER` described below.
Class description:
A class for preparing results
Method signatures and docstrings:
- def __init__(self, module, PlotCaseRuns, **kwargs): Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of funct... | Implement the Python class `PLOTTER` described below.
Class description:
A class for preparing results
Method signatures and docstrings:
- def __init__(self, module, PlotCaseRuns, **kwargs): Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of funct... | d919cadce2b57811351c0615d94da5c6ebfff800 | <|skeleton|>
class PLOTTER:
"""A class for preparing results"""
def __init__(self, module, PlotCaseRuns, **kwargs):
"""Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PLOTTER:
"""A class for preparing results"""
def __init__(self, module, PlotCaseRuns, **kwargs):
"""Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):"""
s... | the_stack_v2_python_sparse | shilofue/PlotCase.py | lhy11009/aspectLib | train | 0 |
f4ffc1f4c7aadbb43bd9b74c5f8bc050b6235df8 | [
"if crn is None:\n raise ValueError('crn must be provided')\nif zone_id is None:\n raise ValueError('zone_id must be provided')\nauthenticator = get_authenticator_from_environment(service_name)\nservice = cls(crn, zone_id, authenticator)\nservice.configure_service(service_name)\nreturn service",
"if crn is ... | <|body_start_0|>
if crn is None:
raise ValueError('crn must be provided')
if zone_id is None:
raise ValueError('zone_id must be provided')
authenticator = get_authenticator_from_environment(service_name)
service = cls(crn, zone_id, authenticator)
service.c... | The WAF Rule Packages API V1 service. | WafRulePackagesApiV1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WafRulePackagesApiV1:
"""The WAF Rule Packages API V1 service."""
def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'WafRulePackagesApiV1':
"""Return a new client for the WAF Rule Packages API service using the specified parameters and external ... | stack_v2_sparse_classes_75kplus_train_002471 | 28,269 | permissive | [
{
"docstring": "Return a new client for the WAF Rule Packages API service using the specified parameters and external configuration. :param str crn: cloud resource name. :param str zone_id: zone id.",
"name": "new_instance",
"signature": "def new_instance(cls, crn: str, zone_id: str, service_name: str=D... | 5 | null | Implement the Python class `WafRulePackagesApiV1` described below.
Class description:
The WAF Rule Packages API V1 service.
Method signatures and docstrings:
- def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'WafRulePackagesApiV1': Return a new client for the WAF Rule Packages... | Implement the Python class `WafRulePackagesApiV1` described below.
Class description:
The WAF Rule Packages API V1 service.
Method signatures and docstrings:
- def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'WafRulePackagesApiV1': Return a new client for the WAF Rule Packages... | 7eed5185f1e93a57e43d0d7a1e83ee8c708179e0 | <|skeleton|>
class WafRulePackagesApiV1:
"""The WAF Rule Packages API V1 service."""
def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'WafRulePackagesApiV1':
"""Return a new client for the WAF Rule Packages API service using the specified parameters and external ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WafRulePackagesApiV1:
"""The WAF Rule Packages API V1 service."""
def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'WafRulePackagesApiV1':
"""Return a new client for the WAF Rule Packages API service using the specified parameters and external configuration... | the_stack_v2_python_sparse | ibm_cloud_networking_services/waf_rule_packages_api_v1.py | mauriceDevsM/networking-python-sdk | train | 0 |
f2f0d8aec8bc4280a90a001cc892eb21f5a7352a | [
"time = timezone.now() + datetime.timedelta(days=30)\nfuture_question = Question(pub_date=time)\nself.assertIs(future_question.was_recently_published(), False)",
"time = timezone.now() - datetime.timedelta(days=1, seconds=1)\nold_question = Question(pub_date=time)\nself.assertIs(old_question.was_recently_publishe... | <|body_start_0|>
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_recently_published(), False)
<|end_body_0|>
<|body_start_1|>
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_questio... | QuestionModelTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionModelTests:
def test_was_recently_published_with_future_question(self):
"""was_recently_published method should return false for question whose pub_date is in the future :return:"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""was_pu... | stack_v2_sparse_classes_75kplus_train_002472 | 4,335 | permissive | [
{
"docstring": "was_recently_published method should return false for question whose pub_date is in the future :return:",
"name": "test_was_recently_published_with_future_question",
"signature": "def test_was_recently_published_with_future_question(self)"
},
{
"docstring": "was_published_recentl... | 3 | stack_v2_sparse_classes_30k_train_004739 | Implement the Python class `QuestionModelTests` described below.
Class description:
Implement the QuestionModelTests class.
Method signatures and docstrings:
- def test_was_recently_published_with_future_question(self): was_recently_published method should return false for question whose pub_date is in the future :re... | Implement the Python class `QuestionModelTests` described below.
Class description:
Implement the QuestionModelTests class.
Method signatures and docstrings:
- def test_was_recently_published_with_future_question(self): was_recently_published method should return false for question whose pub_date is in the future :re... | 284ab9efae8361c139d330313abb831bfea9e5b9 | <|skeleton|>
class QuestionModelTests:
def test_was_recently_published_with_future_question(self):
"""was_recently_published method should return false for question whose pub_date is in the future :return:"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""was_pu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionModelTests:
def test_was_recently_published_with_future_question(self):
"""was_recently_published method should return false for question whose pub_date is in the future :return:"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
... | the_stack_v2_python_sparse | mysite/article/tests.py | wuhaoqiu/Spark-Machine-Learning-Platform-with-Social-Functionalities | train | 0 | |
e10a33b84aa890cac4fbcd2af2c67d7f35952d73 | [
"if not email:\n raise ValueError('The given email address must be set')\nif not username:\n raise ValueError('The given username must be set')\nemail = self.normalize_email(email)\nuser = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=time... | <|body_start_0|>
if not email:
raise ValueError('The given email address must be set')
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email, is_staff=is_staff, is_a... | Custom User Manager | AccountUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountUserManager:
"""Custom User Manager"""
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given username, email, and password"""
<|body_0|>
def normalize_email(cls, email):
"""Nor... | stack_v2_sparse_classes_75kplus_train_002473 | 2,974 | no_license | [
{
"docstring": "Creates and saves a User with the given username, email, and password",
"name": "_create_user",
"signature": "def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields)"
},
{
"docstring": "Normalize the address by lowercasing both the name and domai... | 2 | null | Implement the Python class `AccountUserManager` described below.
Class description:
Custom User Manager
Method signatures and docstrings:
- def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): Creates and saves a User with the given username, email, and password
- def normalize_e... | Implement the Python class `AccountUserManager` described below.
Class description:
Custom User Manager
Method signatures and docstrings:
- def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): Creates and saves a User with the given username, email, and password
- def normalize_e... | 2673181f3b7fd95be4441a2171f1318f17dfd85e | <|skeleton|>
class AccountUserManager:
"""Custom User Manager"""
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given username, email, and password"""
<|body_0|>
def normalize_email(cls, email):
"""Nor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountUserManager:
"""Custom User Manager"""
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given username, email, and password"""
if not email:
raise ValueError('The given email address must be ... | the_stack_v2_python_sparse | accounts/models.py | faisalae/RTarchViz | train | 0 |
03dcd89c0288a7aeed56c2b28160a5b40b401191 | [
"if self == LazBackend.Lazrs or self == LazBackend.LazrsParallel:\n try:\n import lazrs\n except ModuleNotFoundError:\n return False\n else:\n return True\nelif self == LazBackend.Laszip:\n try:\n import laszip\n except ModuleNotFoundError:\n return False\n else:... | <|body_start_0|>
if self == LazBackend.Lazrs or self == LazBackend.LazrsParallel:
try:
import lazrs
except ModuleNotFoundError:
return False
else:
return True
elif self == LazBackend.Laszip:
try:
... | Supported backends for reading and writing LAS/LAZ | LazBackend | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazBackend:
"""Supported backends for reading and writing LAS/LAZ"""
def is_available(self) -> bool:
"""Returns true if the backend is available"""
<|body_0|>
def detect_available() -> Tuple['LazBackend', ...]:
"""Returns a tuple containing the available backends... | stack_v2_sparse_classes_75kplus_train_002474 | 1,975 | permissive | [
{
"docstring": "Returns true if the backend is available",
"name": "is_available",
"signature": "def is_available(self) -> bool"
},
{
"docstring": "Returns a tuple containing the available backends in the current python environment",
"name": "detect_available",
"signature": "def detect_a... | 2 | null | Implement the Python class `LazBackend` described below.
Class description:
Supported backends for reading and writing LAS/LAZ
Method signatures and docstrings:
- def is_available(self) -> bool: Returns true if the backend is available
- def detect_available() -> Tuple['LazBackend', ...]: Returns a tuple containing t... | Implement the Python class `LazBackend` described below.
Class description:
Supported backends for reading and writing LAS/LAZ
Method signatures and docstrings:
- def is_available(self) -> bool: Returns true if the backend is available
- def detect_available() -> Tuple['LazBackend', ...]: Returns a tuple containing t... | 1a62d1fea108c12e68e28b2ae55620648866831e | <|skeleton|>
class LazBackend:
"""Supported backends for reading and writing LAS/LAZ"""
def is_available(self) -> bool:
"""Returns true if the backend is available"""
<|body_0|>
def detect_available() -> Tuple['LazBackend', ...]:
"""Returns a tuple containing the available backends... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LazBackend:
"""Supported backends for reading and writing LAS/LAZ"""
def is_available(self) -> bool:
"""Returns true if the backend is available"""
if self == LazBackend.Lazrs or self == LazBackend.LazrsParallel:
try:
import lazrs
except ModuleNotFo... | the_stack_v2_python_sparse | laspy/compression.py | hobu/laspy | train | 3 |
7ff70d0cd8252aaf45b8bc81e38a7b559ede77e1 | [
"set_seed(1)\nds.config.set_seed(1)\nrandom.seed(1)\nif device == 'CPU':\n context.set_context(mode=context.PYNATIVE_MODE, device_target=device)\nelse:\n print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device_id))\n device_num = get_device_num()\n context.set_cont... | <|body_start_0|>
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNATIVE_MODE, device_target=device)
else:
print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device... | utils for initialize and prepare dataloader | MSUtils | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_75kplus_train_002475 | 3,836 | permissive | [
{
"docstring": ":param device: support GPU/CPU/Ascend",
"name": "initialize",
"signature": "def initialize(device='CPU', device_id=0)"
},
{
"docstring": "prepare dataloader :param dataset: dataset :param column_names: column_names :param batch_size: batch_size :param num_workers: worker numbers ... | 2 | stack_v2_sparse_classes_30k_val_002679 | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNAT... | the_stack_v2_python_sparse | research/cv/rcnn/src/common/mindspore_utils.py | mindspore-ai/models | train | 301 |
43c3a71a0e8e966b38beb9ce29972037b971c5e6 | [
"self.name = 'list_sampling_strategy'\nself.param_name = param\nself.param_datatype = dt\nself.values = values\nself.visit_freq = dict()\nfor v in values:\n self.visit_freq[v] = 0",
"if len(self.values) == 0:\n return None\nreturn random.choice(self.values)"
] | <|body_start_0|>
self.name = 'list_sampling_strategy'
self.param_name = param
self.param_datatype = dt
self.values = values
self.visit_freq = dict()
for v in values:
self.visit_freq[v] = 0
<|end_body_0|>
<|body_start_1|>
if len(self.values) == 0:
... | ListSamplingStrategy | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-public-domain",
"Unlicense",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListSamplingStrategy:
def __init__(self, param, dt, values=[]):
"""When initializing a ListSamplingStrategy, one needs to give a list of possible values."""
<|body_0|>
def next_value(self, curt_val=None):
"""Return the next value according to the current value."""
... | stack_v2_sparse_classes_75kplus_train_002476 | 976 | permissive | [
{
"docstring": "When initializing a ListSamplingStrategy, one needs to give a list of possible values.",
"name": "__init__",
"signature": "def __init__(self, param, dt, values=[])"
},
{
"docstring": "Return the next value according to the current value.",
"name": "next_value",
"signature... | 2 | stack_v2_sparse_classes_30k_train_050660 | Implement the Python class `ListSamplingStrategy` described below.
Class description:
Implement the ListSamplingStrategy class.
Method signatures and docstrings:
- def __init__(self, param, dt, values=[]): When initializing a ListSamplingStrategy, one needs to give a list of possible values.
- def next_value(self, cu... | Implement the Python class `ListSamplingStrategy` described below.
Class description:
Implement the ListSamplingStrategy class.
Method signatures and docstrings:
- def __init__(self, param, dt, values=[]): When initializing a ListSamplingStrategy, one needs to give a list of possible values.
- def next_value(self, cu... | 4dd03a394694257dcd29a0f35cea83b656988830 | <|skeleton|>
class ListSamplingStrategy:
def __init__(self, param, dt, values=[]):
"""When initializing a ListSamplingStrategy, one needs to give a list of possible values."""
<|body_0|>
def next_value(self, curt_val=None):
"""Return the next value according to the current value."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListSamplingStrategy:
def __init__(self, param, dt, values=[]):
"""When initializing a ListSamplingStrategy, one needs to give a list of possible values."""
self.name = 'list_sampling_strategy'
self.param_name = param
self.param_datatype = dt
self.values = values
... | the_stack_v2_python_sparse | docker_hadoop/conexer/src/space_expl_framework/sampling_strategies/list_strategy.py | rahlk/ConEX | train | 0 | |
6f91d47659a9ec242d4cb42f02a6de6f1b296116 | [
"table_object = Tag.query.get_or_404(int_id)\nform = TagForm(obj=table_object)\ntemplate_return = flask.render_template('edit.html', form=form)\nreturn template_return",
"table_object = Tag.query.get_or_404(int_id)\nform = TagForm(obj=table_object)\nif form.validate_on_submit():\n form.populate_obj(table_objec... | <|body_start_0|>
table_object = Tag.query.get_or_404(int_id)
form = TagForm(obj=table_object)
template_return = flask.render_template('edit.html', form=form)
return template_return
<|end_body_0|>
<|body_start_1|>
table_object = Tag.query.get_or_404(int_id)
form = TagForm... | EditTagResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
table_object = Tag.query.get_or_404(int_id)
form = TagForm(obj=... | stack_v2_sparse_classes_75kplus_train_002477 | 3,873 | no_license | [
{
"docstring": "Args: int_id: Returns:",
"name": "get",
"signature": "def get(self, int_id)"
},
{
"docstring": "Args: int_id: Returns:",
"name": "post",
"signature": "def post(self, int_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041090 | Implement the Python class `EditTagResource` described below.
Class description:
Implement the EditTagResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns: | Implement the Python class `EditTagResource` described below.
Class description:
Implement the EditTagResource class.
Method signatures and docstrings:
- def get(self, int_id): Args: int_id: Returns:
- def post(self, int_id): Args: int_id: Returns:
<|skeleton|>
class EditTagResource:
def get(self, int_id):
... | 865403e3b1717226b25c9d64aeb4c35c7220e7e3 | <|skeleton|>
class EditTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
<|body_0|>
def post(self, int_id):
"""Args: int_id: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditTagResource:
def get(self, int_id):
"""Args: int_id: Returns:"""
table_object = Tag.query.get_or_404(int_id)
form = TagForm(obj=table_object)
template_return = flask.render_template('edit.html', form=form)
return template_return
def post(self, int_id):
... | the_stack_v2_python_sparse | things_organizer/web_app/tags/resources.py | yeyeto2788/Things-Organizer | train | 11 | |
5cb4e059a3424a14d01f72999f0f7507dcc68f07 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"appliance = Inventory.return_as_dictionary(self)\nappliance['brand'] = self.brand\nappliance['voltage'] = self.voltage\nreturn appliance"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
appliance = Inventory.return_as_dictionary(self)
appliance['brand'] = self.brand
appliance['voltage'... | ElectricAppliance class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliance class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""class construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return an electric appliance dictionary... | stack_v2_sparse_classes_75kplus_train_002478 | 858 | no_license | [
{
"docstring": "class construction",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": "function to return an electric appliance dictionary from super class",
"name": "return_as_dictionary",
"sig... | 2 | stack_v2_sparse_classes_30k_train_028602 | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliance class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): class construction
- def return_as_dictionary(self): function to return an electric... | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliance class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): class construction
- def return_as_dictionary(self): function to return an electric... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliance class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""class construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return an electric appliance dictionary... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElectricAppliances:
"""ElectricAppliance class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""class construction"""
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.vol... | the_stack_v2_python_sparse | students/ethan_nguyen/Lesson01/assignment/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
d3cb216718118a3186125dfc5526a63236d20fee | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.PolynomialProjection = PolynomialProjection\nself.GeographicProjection = GeographicProjection\nself.PlaneProjection = PlaneProjection\nself.CylindricalProjection = Cylindri... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.PolynomialProjection = PolynomialProjection
self.GeographicProjection = GeographicProjection
self.PlaneProje... | Geometric SAR information required for measurement/geolocation. | MeasurementType | [
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasurementType:
"""Geometric SAR information required for measurement/geolocation."""
def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, ARPPoly=None, **kwargs):
"""Parameters ---------- PolynomialProjection : P... | stack_v2_sparse_classes_75kplus_train_002479 | 4,466 | permissive | [
{
"docstring": "Parameters ---------- PolynomialProjection : PolynomialProjectionType GeographicProjection : GeographicProjectionType PlaneProjection : PlaneProjectionType CylindricalProjection : CylindricalProjectionType ARPPoly : XYZPolyType|numpy.ndarray|list|tuple kwargs",
"name": "__init__",
"signa... | 3 | null | Implement the Python class `MeasurementType` described below.
Class description:
Geometric SAR information required for measurement/geolocation.
Method signatures and docstrings:
- def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, ARPPoly=None, ... | Implement the Python class `MeasurementType` described below.
Class description:
Geometric SAR information required for measurement/geolocation.
Method signatures and docstrings:
- def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, ARPPoly=None, ... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class MeasurementType:
"""Geometric SAR information required for measurement/geolocation."""
def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, ARPPoly=None, **kwargs):
"""Parameters ---------- PolynomialProjection : P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeasurementType:
"""Geometric SAR information required for measurement/geolocation."""
def __init__(self, PolynomialProjection=None, GeographicProjection=None, PlaneProjection=None, CylindricalProjection=None, ARPPoly=None, **kwargs):
"""Parameters ---------- PolynomialProjection : PolynomialProj... | the_stack_v2_python_sparse | sarpy/io/product/sidd1_elements/Measurement.py | ngageoint/sarpy | train | 192 |
90fb7fb8690eb4c70da586d170f0cc0af923e450 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('xcao19', 'xcao19')\nBoston_vals = repo['xcao19.homeValues'].find({'City': 'Boston'}, {'_id': 0, 'RegionName': 1, '2019-01': 1})\nrepo.dropCollection('boston_homevalue')\nrepo.createCollection('boston_hom... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
Boston_vals = repo['xcao19.homeValues'].find({'City': 'Boston'}, {'_id': 0, 'RegionName': 1, '2019-01': 1})
repo.dropCollection... | boston_homevalue_neighkey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class boston_homevalue_neighkey:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describin... | stack_v2_sparse_classes_75kplus_train_002480 | 5,271 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `boston_homevalue_neighkey` described below.
Class description:
Implement the boston_homevalue_neighkey class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocum... | Implement the Python class `boston_homevalue_neighkey` described below.
Class description:
Implement the boston_homevalue_neighkey class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocum... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class boston_homevalue_neighkey:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class boston_homevalue_neighkey:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
... | the_stack_v2_python_sparse | xcao19/boston_homevalue_neighkey.py | maximega/course-2019-spr-proj | train | 2 | |
8737a8630b66163a17fb36ed2fbb2ca7f5b346df | [
"super(LimitedOffsetDataProvider, self).__init__(source, **kwargs)\nself.offset = max(offset, 0)\nself.limit = limit\nif self.limit is not None:\n self.limit = max(self.limit, 0)",
"if self.limit is not None and self.limit <= 0:\n return\nparent_gen = super(LimitedOffsetDataProvider, self).__iter__()\nfor d... | <|body_start_0|>
super(LimitedOffsetDataProvider, self).__init__(source, **kwargs)
self.offset = max(offset, 0)
self.limit = limit
if self.limit is not None:
self.limit = max(self.limit, 0)
<|end_body_0|>
<|body_start_1|>
if self.limit is not None and self.limit <= 0... | A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination). | LimitedOffsetDataProvider | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwar... | stack_v2_sparse_classes_75kplus_train_002481 | 12,222 | permissive | [
{
"docstring": ":param offset: the number of data to skip before providing. :param limit: the final number of data to provide.",
"name": "__init__",
"signature": "def __init__(self, source, offset=0, limit=None, **kwargs)"
},
{
"docstring": "Iterate over the source until `num_valid_data_read` is... | 2 | stack_v2_sparse_classes_30k_train_016061 | Implement the Python class `LimitedOffsetDataProvider` described below.
Class description:
A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination).
Method signatures and d... | Implement the Python class `LimitedOffsetDataProvider` described below.
Class description:
A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination).
Method signatures and d... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LimitedOffsetDataProvider:
"""A provider that uses the counters from FilteredDataProvider to limit the number of data and/or skip `offset` number of data before providing. Useful for grabbing sections from a source (e.g. pagination)."""
def __init__(self, source, offset=0, limit=None, **kwargs):
... | the_stack_v2_python_sparse | lib/galaxy/datatypes/dataproviders/base.py | bwlang/galaxy | train | 0 |
cec600d208aed558744dd0d09eaedd45b50c7fdc | [
"form.instance.created_by = self.request.user\nself.object = form.save()\nversion = Version(algorithm=self.object, description='Versión por defecto 1.0', number='1.0', repository_url='', publishing_state=Version.DEVELOPED_STATE)\nversion.save()\nreturn redirect(self.get_success_url())",
"context = super(Algorithm... | <|body_start_0|>
form.instance.created_by = self.request.user
self.object = form.save()
version = Version(algorithm=self.object, description='Versión por defecto 1.0', number='1.0', repository_url='', publishing_state=Version.DEVELOPED_STATE)
version.save()
return redirect(self.g... | Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html | AlgorithmCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgorithmCreateView:
"""Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html"""
def form_valid(self, form):
"""Create an initial version for the algorithm. This method is called when valid form data has been POSTed."""
<... | stack_v2_sparse_classes_75kplus_train_002482 | 23,693 | no_license | [
{
"docstring": "Create an initial version for the algorithm. This method is called when valid form data has been POSTed.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Add or change context initial data.",
"name": "get_context_data",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_014146 | Implement the Python class `AlgorithmCreateView` described below.
Class description:
Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html
Method signatures and docstrings:
- def form_valid(self, form): Create an initial version for the algorithm. This method is ... | Implement the Python class `AlgorithmCreateView` described below.
Class description:
Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html
Method signatures and docstrings:
- def form_valid(self, form): Create an initial version for the algorithm. This method is ... | e298a8089841f4dd02b1635e13e6dc2b984535bd | <|skeleton|>
class AlgorithmCreateView:
"""Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html"""
def form_valid(self, form):
"""Create an initial version for the algorithm. This method is called when valid form data has been POSTed."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlgorithmCreateView:
"""Create an algorithm and an initial version for the algorithm. Use the template algorithm/algorithm_form.html"""
def form_valid(self, form):
"""Create an initial version for the algorithm. This method is called when valid form data has been POSTed."""
form.instance.... | the_stack_v2_python_sparse | algorithm/views.py | OpenDatacubeIDEAM/cdcol-web | train | 3 |
bb94918559235fcefaa7fc8f2973c06100569b05 | [
"min_ = numpy.min(map)\nmax_ = numpy.max(map)\nif max_ > min_:\n map -= min_\n map /= max_ - min_\nreturn map",
"min_ = numpy.min(mapScalar)\nmax_ = numpy.max(mapScalar)\nresNorm = (mapScalar - min_) / (max_ - min_)\nreturn resNorm"
] | <|body_start_0|>
min_ = numpy.min(map)
max_ = numpy.max(map)
if max_ > min_:
map -= min_
map /= max_ - min_
return map
<|end_body_0|>
<|body_start_1|>
min_ = numpy.min(mapScalar)
max_ = numpy.max(mapScalar)
resNorm = (mapScalar - min_) / (... | UtilNormalize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilNormalize:
def normalize(map):
"""normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)"""
<|body_0|>
def normalizeCopy(mapScalar):
"""returns a newly created numpy array with normalized values actually is is... | stack_v2_sparse_classes_75kplus_train_002483 | 1,019 | no_license | [
{
"docstring": "normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)",
"name": "normalize",
"signature": "def normalize(map)"
},
{
"docstring": "returns a newly created numpy array with normalized values actually is is not normalizing but m... | 2 | stack_v2_sparse_classes_30k_train_035117 | Implement the Python class `UtilNormalize` described below.
Class description:
Implement the UtilNormalize class.
Method signatures and docstrings:
- def normalize(map): normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)
- def normalizeCopy(mapScalar): returns... | Implement the Python class `UtilNormalize` described below.
Class description:
Implement the UtilNormalize class.
Method signatures and docstrings:
- def normalize(map): normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)
- def normalizeCopy(mapScalar): returns... | a1788444e3f62c34af77e5e54d8ea133bddcb244 | <|skeleton|>
class UtilNormalize:
def normalize(map):
"""normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)"""
<|body_0|>
def normalizeCopy(mapScalar):
"""returns a newly created numpy array with normalized values actually is is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilNormalize:
def normalize(map):
"""normalizes the passed array actually is is not normalizing but min-max-scaling between 0 and 1 (TODO rename)"""
min_ = numpy.min(map)
max_ = numpy.max(map)
if max_ > min_:
map -= min_
map /= max_ - min_
retur... | the_stack_v2_python_sparse | UtilNormalize.py | marcbln/util-python | train | 0 | |
0b44e2a90da5efd8fdae4d38c0488cadbec007b0 | [
"channel = self.query('SOURce:SEL?')\nif channel:\n return int(channel)\nelse:\n raise InstrIOError",
"self.write('SOURce:SEL {}'.format(channel))\nresult = int(self.query('SOURce:SEL?'))\nif result and channel != result:\n msg = 'Instrument could not select channel {}'\n raise InstrIOError(msg.format... | <|body_start_0|>
channel = self.query('SOURce:SEL?')
if channel:
return int(channel)
else:
raise InstrIOError
<|end_body_0|>
<|body_start_1|>
self.write('SOURce:SEL {}'.format(channel))
result = int(self.query('SOURce:SEL?'))
if result and channel... | Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit used by the driver. The default unit is 'GHz'. Other valid units are : 'MHz', 'K... | AnapicoMulti | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnapicoMulti:
"""Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit used by the driver. The default unit is ... | stack_v2_sparse_classes_75kplus_train_002484 | 8,574 | permissive | [
{
"docstring": "Currently selected channel",
"name": "channel",
"signature": "def channel(self)"
},
{
"docstring": "Current channel setter method",
"name": "channel",
"signature": "def channel(self, channel)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042754 | Implement the Python class `AnapicoMulti` described below.
Class description:
Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit u... | Implement the Python class `AnapicoMulti` described below.
Class description:
Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit u... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class AnapicoMulti:
"""Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit used by the driver. The default unit is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnapicoMulti:
"""Generic driver for multi-channel Anapico Signal Generators, using the VISA library. Parameters ---------- see the `VisaInstrument` parameters Attributes ---------- channel: int Channel currently selected frequency_unit : str Frequency unit used by the driver. The default unit is 'GHz'. Other ... | the_stack_v2_python_sparse | exopy_hqc_legacy/instruments/drivers/visa/anapico.py | Exopy/exopy_hqc_legacy | train | 0 |
79aad45ef61218c8380c83007aadef65c25a546d | [
"self.viewport_name = viewport_name\nself.adhoc_media_pool_publisher = adhoc_media_pool_publisher\nself.media_type = media_type",
"adhoc_medias = self._extract_adhoc_media(data)\nlogger.info('Publishing AdhocMedias: %s' % adhoc_medias)\nself.adhoc_media_pool_publisher.publish(adhoc_medias)",
"medias = extract_f... | <|body_start_0|>
self.viewport_name = viewport_name
self.adhoc_media_pool_publisher = adhoc_media_pool_publisher
self.media_type = media_type
<|end_body_0|>
<|body_start_1|>
adhoc_medias = self._extract_adhoc_media(data)
logger.info('Publishing AdhocMedias: %s' % adhoc_medias)
... | Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mplayer_pool_publisher` | DirectorMediaBridge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_75kplus_train_002485 | 4,045 | permissive | [
{
"docstring": "MediaDirectorBridge should be configured per each viewport to properly translate director geometry to viewport geometry and provide separation and service granularity.",
"name": "__init__",
"signature": "def __init__(self, adhoc_media_pool_publisher, viewport_name, media_type='video')"
... | 5 | stack_v2_sparse_classes_30k_train_040106 | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | 90233b939bb4873c00a72e84ab3f8d1a776edee8 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mpl... | the_stack_v2_python_sparse | lg_media/src/lg_media/director_media_bridge.py | EndPointCorp/lg_ros_nodes | train | 18 |
135bb76f6db66984d253213eea79c2851ea1d5ac | [
"checked = obj.checked\nif self.cn_f('wxCHK_3STATE') in self.tmpl_dict['style']:\n checked = self.config['number2state'][checked]\n checked = self.cn_f(checked)\n self.tmpl_dict['value_3state'] = checked\nelse:\n self.has_setvalue1 = checked",
"if self.cn_f('wxCHK_3STATE') in self.tmpl_dict['style']:\... | <|body_start_0|>
checked = obj.checked
if self.cn_f('wxCHK_3STATE') in self.tmpl_dict['style']:
checked = self.config['number2state'][checked]
checked = self.cn_f(checked)
self.tmpl_dict['value_3state'] = checked
else:
self.has_setvalue1 = checked
... | Generic code to handle wxCheckbox code in all language code generators | CheckBoxMixin | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"WxWindows-exception-3.1",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckBoxMixin:
"""Generic code to handle wxCheckbox code in all language code generators"""
def _prepare_checkbox_content(self, obj):
"""Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj: xml_parse.CodeObject"""
<|body_0|>
def _get... | stack_v2_sparse_classes_75kplus_train_002486 | 1,037 | permissive | [
{
"docstring": "Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj: xml_parse.CodeObject",
"name": "_prepare_checkbox_content",
"signature": "def _prepare_checkbox_content(self, obj)"
},
{
"docstring": "Returns code to set the state of a 3-state checkbox to... | 2 | null | Implement the Python class `CheckBoxMixin` described below.
Class description:
Generic code to handle wxCheckbox code in all language code generators
Method signatures and docstrings:
- def _prepare_checkbox_content(self, obj): Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj:... | Implement the Python class `CheckBoxMixin` described below.
Class description:
Generic code to handle wxCheckbox code in all language code generators
Method signatures and docstrings:
- def _prepare_checkbox_content(self, obj): Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj:... | 828515e217c4733d38c57ed88d853e983a2008f2 | <|skeleton|>
class CheckBoxMixin:
"""Generic code to handle wxCheckbox code in all language code generators"""
def _prepare_checkbox_content(self, obj):
"""Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj: xml_parse.CodeObject"""
<|body_0|>
def _get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckBoxMixin:
"""Generic code to handle wxCheckbox code in all language code generators"""
def _prepare_checkbox_content(self, obj):
"""Prepare template variables for 3-state checkbox obj: Instance of xml_parse.CodeObject obj: xml_parse.CodeObject"""
checked = obj.checked
if self... | the_stack_v2_python_sparse | widgets/checkbox/checkbox_base.py | wxGlade/wxGlade | train | 275 |
c50cd214d49cf86dc79b6bf2ab5ca0ab12936bfd | [
"super().__init__()\nself._name = __name__\n'\\n Variavel com o nome do arquivo\\n '",
"test_path = ''\ntry:\n barra = '/'\n inicio = '/'\n if platform.system().upper() == 'WINDOWS':\n barra = '\\\\'\n inicio = ''\n path_aux = path_file.split(barra)\n for pp in range(len... | <|body_start_0|>
super().__init__()
self._name = __name__
'\n Variavel com o nome do arquivo\n '
<|end_body_0|>
<|body_start_1|>
test_path = ''
try:
barra = '/'
inicio = '/'
if platform.system().upper() == 'WINDOWS':
... | Isto é um comentário da classe MyClass | Copy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Copy:
"""Isto é um comentário da classe MyClass"""
def __init__(self):
"""Comentário do construtor"""
<|body_0|>
def criar_arquivos(path_file: str) -> bool:
"""Criar toda estrutura de arquivo para depois fazer a copia do arquivo. :param str path_file: Deve ser o ... | stack_v2_sparse_classes_75kplus_train_002487 | 4,767 | permissive | [
{
"docstring": "Comentário do construtor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Criar toda estrutura de arquivo para depois fazer a copia do arquivo. :param str path_file: Deve ser o caminho do arquivo, com o nome do arquivo junto. :return: Se tudo correu ok :... | 4 | stack_v2_sparse_classes_30k_train_046750 | Implement the Python class `Copy` described below.
Class description:
Isto é um comentário da classe MyClass
Method signatures and docstrings:
- def __init__(self): Comentário do construtor
- def criar_arquivos(path_file: str) -> bool: Criar toda estrutura de arquivo para depois fazer a copia do arquivo. :param str p... | Implement the Python class `Copy` described below.
Class description:
Isto é um comentário da classe MyClass
Method signatures and docstrings:
- def __init__(self): Comentário do construtor
- def criar_arquivos(path_file: str) -> bool: Criar toda estrutura de arquivo para depois fazer a copia do arquivo. :param str p... | dd4643d76ae98c017b0360e4e6af8f096f2a473e | <|skeleton|>
class Copy:
"""Isto é um comentário da classe MyClass"""
def __init__(self):
"""Comentário do construtor"""
<|body_0|>
def criar_arquivos(path_file: str) -> bool:
"""Criar toda estrutura de arquivo para depois fazer a copia do arquivo. :param str path_file: Deve ser o ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Copy:
"""Isto é um comentário da classe MyClass"""
def __init__(self):
"""Comentário do construtor"""
super().__init__()
self._name = __name__
'\n Variavel com o nome do arquivo\n '
def criar_arquivos(path_file: str) -> bool:
"""Criar toda estrut... | the_stack_v2_python_sparse | tardis/src/inout/Copy.py | randersonLemos/SIDRAT | train | 0 |
28d63dbe16b78bd3f1936921f44496b263b0ea2c | [
"if x is None or y is None:\n raise ValueError('Any observation variable cannot be None')\nif category_id is not None:\n category_id = int(category_id)\nreturn Observation(float(x), float(y), category_id)",
"if len(values) != 3:\n raise ValueError('Invalid observation structure')\nreturn ObservationFacto... | <|body_start_0|>
if x is None or y is None:
raise ValueError('Any observation variable cannot be None')
if category_id is not None:
category_id = int(category_id)
return Observation(float(x), float(y), category_id)
<|end_body_0|>
<|body_start_1|>
if len(values) !... | Factory for creation Observation instances | ObservationFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservationFactory:
"""Factory for creation Observation instances"""
def create_observation(x, y, category_id=None):
"""Creates new instance of Observation based on x, y"""
<|body_0|>
def create_observation_from_tuple(values):
"""Creates new instance of Observati... | stack_v2_sparse_classes_75kplus_train_002488 | 2,463 | no_license | [
{
"docstring": "Creates new instance of Observation based on x, y",
"name": "create_observation",
"signature": "def create_observation(x, y, category_id=None)"
},
{
"docstring": "Creates new instance of Observation based on a tuple",
"name": "create_observation_from_tuple",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_014228 | Implement the Python class `ObservationFactory` described below.
Class description:
Factory for creation Observation instances
Method signatures and docstrings:
- def create_observation(x, y, category_id=None): Creates new instance of Observation based on x, y
- def create_observation_from_tuple(values): Creates new ... | Implement the Python class `ObservationFactory` described below.
Class description:
Factory for creation Observation instances
Method signatures and docstrings:
- def create_observation(x, y, category_id=None): Creates new instance of Observation based on x, y
- def create_observation_from_tuple(values): Creates new ... | 6354e3640bcbb09544084d017dd0e0f0d2f398c0 | <|skeleton|>
class ObservationFactory:
"""Factory for creation Observation instances"""
def create_observation(x, y, category_id=None):
"""Creates new instance of Observation based on x, y"""
<|body_0|>
def create_observation_from_tuple(values):
"""Creates new instance of Observati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObservationFactory:
"""Factory for creation Observation instances"""
def create_observation(x, y, category_id=None):
"""Creates new instance of Observation based on x, y"""
if x is None or y is None:
raise ValueError('Any observation variable cannot be None')
if catego... | the_stack_v2_python_sparse | domain/shared/observation.py | jasphall/k_nearest_neighbours | train | 0 |
7cf11c3dcf1169783a763fa6be9ec4089889f63e | [
"try:\n documentobj = extract_value_from_input(input=input, field_id='document_id', model_type='Document', model=document_model)\nexcept ObjectDoesNotExist:\n raise GraphQLError(u'Ci sono stati problemi durante il recupero del documento.')\ntry:\n documentobj.document.delete()\nexcept Exception:\n raise... | <|body_start_0|>
try:
documentobj = extract_value_from_input(input=input, field_id='document_id', model_type='Document', model=document_model)
except ObjectDoesNotExist:
raise GraphQLError(u'Ci sono stati problemi durante il recupero del documento.')
try:
docu... | DocumentMutationService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentMutationService:
def deleteDocument(self, input):
"""cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati dict: che indica il numero di cancellazioni per quel tipo di oggetto esempio: (1, {'document.Entry': 1})"""
... | stack_v2_sparse_classes_75kplus_train_002489 | 3,329 | no_license | [
{
"docstring": "cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati dict: che indica il numero di cancellazioni per quel tipo di oggetto esempio: (1, {'document.Entry': 1})",
"name": "deleteDocument",
"signature": "def deleteDocument(self, ... | 2 | stack_v2_sparse_classes_30k_train_031354 | Implement the Python class `DocumentMutationService` described below.
Class description:
Implement the DocumentMutationService class.
Method signatures and docstrings:
- def deleteDocument(self, input): cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati... | Implement the Python class `DocumentMutationService` described below.
Class description:
Implement the DocumentMutationService class.
Method signatures and docstrings:
- def deleteDocument(self, input): cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati... | 7929b244a40a2faf834f55f1803d131cc6324a49 | <|skeleton|>
class DocumentMutationService:
def deleteDocument(self, input):
"""cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati dict: che indica il numero di cancellazioni per quel tipo di oggetto esempio: (1, {'document.Entry': 1})"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentMutationService:
def deleteDocument(self, input):
"""cancellazione di un file input: input: dict output: ritorna una tupla composta da: int: numero di oggetti eliminati dict: che indica il numero di cancellazioni per quel tipo di oggetto esempio: (1, {'document.Entry': 1})"""
try:
... | the_stack_v2_python_sparse | legionella/graphqlapp/document/mutationservice.py | RedTurtle/legionella-backend | train | 0 | |
34a54df374c8271a13f8c709f182788b9b44fc01 | [
"value = '<div>'\nclase = 'actions'\nperm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)\nperm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_item)\nurl = './'\nif UrlParser.parse_nombre(request.url, 'post_buscar'):\n url = '../'\nif perm_mod.is_met(request.environ):\n value +... | <|body_start_0|>
value = '<div>'
clase = 'actions'
perm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)
perm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_item)
url = './'
if UrlParser.parse_nombre(request.url, 'post_buscar'):
... | RolesTipoTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw):
"""Se muestra la lista de roles para este tipo de ítem."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_002490 | 12,240 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de roles para este tipo de ítem.",
"name": "_do_get_provider_count_and_objs",
"signature": "def _do_get_provider_count_and_obj... | 2 | stack_v2_sparse_classes_30k_train_048818 | Implement the Python class `RolesTipoTableFiller` described below.
Class description:
Implement the RolesTipoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw): Se muestra la li... | Implement the Python class `RolesTipoTableFiller` described below.
Class description:
Implement the RolesTipoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw): Se muestra la li... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw):
"""Se muestra la lista de roles para este tipo de ítem."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
value = '<div>'
clase = 'actions'
perm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)
perm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_ite... | the_stack_v2_python_sparse | lpm/controllers/roles_tipo_item.py | jorgeramirez/LPM | train | 1 | |
12170732660736be430b4be81be0245f6d7cb34d | [
"count = 0\nwhile n:\n count += n & 1\n n >>= 1\nreturn count",
"count = 0\nwhile n:\n res = n % 2\n if res == 1:\n count += 1\n n //= 2\nreturn count"
] | <|body_start_0|>
count = 0
while n:
count += n & 1
n >>= 1
return count
<|end_body_0|>
<|body_start_1|>
count = 0
while n:
res = n % 2
if res == 1:
count += 1
n //= 2
return count
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
while n:
count += n & 1
... | stack_v2_sparse_classes_75kplus_train_002491 | 806 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight1",
"signature": "def hammingWeight1(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight1(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight1(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | f3fbc356a460831c41b0b818249d178252939fc1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
count = 0
while n:
count += n & 1
n >>= 1
return count
def hammingWeight1(self, n):
""":type n: int :rtype: int"""
count = 0
while n:
res = n % ... | the_stack_v2_python_sparse | Week 07/id_091/Leetcode_191_091.py | Ryanyanglibin/algorithm004-01 | train | 1 | |
2993c58fb7b33bf4320ed9f245d41597339e7e9b | [
"if user_config_directory is CredentialsStore._DEFAULT_CONFIG_DIRECTORY:\n user_config_directory = util.get_user_config_directory()\n if user_config_directory is None:\n logger.warning('Credentials caching disabled - no private config directory found')\nif user_config_directory is None:\n self._cred... | <|body_start_0|>
if user_config_directory is CredentialsStore._DEFAULT_CONFIG_DIRECTORY:
user_config_directory = util.get_user_config_directory()
if user_config_directory is None:
logger.warning('Credentials caching disabled - no private config directory found')
i... | Private file store for a `google.oauth2.credentials.Credentials`. | CredentialsStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CredentialsStore:
"""Private file store for a `google.oauth2.credentials.Credentials`."""
def __init__(self, user_config_directory=_DEFAULT_CONFIG_DIRECTORY):
"""Creates a CredentialsStore. Args: user_config_directory: Optional absolute path to the root directory for storing user con... | stack_v2_sparse_classes_75kplus_train_002492 | 16,711 | permissive | [
{
"docstring": "Creates a CredentialsStore. Args: user_config_directory: Optional absolute path to the root directory for storing user configs, under which to store the credentials file. If not set, defaults to a platform-specific location. If set to None, the store is disabled (reads return None; write and cle... | 4 | stack_v2_sparse_classes_30k_train_014369 | Implement the Python class `CredentialsStore` described below.
Class description:
Private file store for a `google.oauth2.credentials.Credentials`.
Method signatures and docstrings:
- def __init__(self, user_config_directory=_DEFAULT_CONFIG_DIRECTORY): Creates a CredentialsStore. Args: user_config_directory: Optional... | Implement the Python class `CredentialsStore` described below.
Class description:
Private file store for a `google.oauth2.credentials.Credentials`.
Method signatures and docstrings:
- def __init__(self, user_config_directory=_DEFAULT_CONFIG_DIRECTORY): Creates a CredentialsStore. Args: user_config_directory: Optional... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class CredentialsStore:
"""Private file store for a `google.oauth2.credentials.Credentials`."""
def __init__(self, user_config_directory=_DEFAULT_CONFIG_DIRECTORY):
"""Creates a CredentialsStore. Args: user_config_directory: Optional absolute path to the root directory for storing user con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CredentialsStore:
"""Private file store for a `google.oauth2.credentials.Credentials`."""
def __init__(self, user_config_directory=_DEFAULT_CONFIG_DIRECTORY):
"""Creates a CredentialsStore. Args: user_config_directory: Optional absolute path to the root directory for storing user configs, under w... | the_stack_v2_python_sparse | tensorboard/uploader/auth.py | tensorflow/tensorboard | train | 6,766 |
8d260f0ca6244ab518d76e5e4bf8e9b282b3434b | [
"n = len(position)\nif not n:\n return 0\ntime = [(target - position[i]) / speed[i] for i in range(n)]\na = sorted(list(zip(position, time)), reverse=True)\ncount = 1\ncur = a[0][1]\nfor i in range(1, n):\n if a[i][1] > cur:\n count += 1\n cur = a[i][1]\nreturn count",
"time = [(target - p) / ... | <|body_start_0|>
n = len(position)
if not n:
return 0
time = [(target - position[i]) / speed[i] for i in range(n)]
a = sorted(list(zip(position, time)), reverse=True)
count = 1
cur = a[0][1]
for i in range(1, n):
if a[i][1] > cur:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def carFleet(self, target, position, speed):
""":type target: int :type position: List[int] :type speed: List[int] :rtype: int"""
<|body_0|>
def carFleet1(self, target, position, speed):
""":type target: int :type position: List[int] :type speed: List[int] ... | stack_v2_sparse_classes_75kplus_train_002493 | 1,315 | no_license | [
{
"docstring": ":type target: int :type position: List[int] :type speed: List[int] :rtype: int",
"name": "carFleet",
"signature": "def carFleet(self, target, position, speed)"
},
{
"docstring": ":type target: int :type position: List[int] :type speed: List[int] :rtype: int",
"name": "carFlee... | 2 | stack_v2_sparse_classes_30k_train_030172 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carFleet(self, target, position, speed): :type target: int :type position: List[int] :type speed: List[int] :rtype: int
- def carFleet1(self, target, position, speed): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def carFleet(self, target, position, speed): :type target: int :type position: List[int] :type speed: List[int] :rtype: int
- def carFleet1(self, target, position, speed): :type ... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def carFleet(self, target, position, speed):
""":type target: int :type position: List[int] :type speed: List[int] :rtype: int"""
<|body_0|>
def carFleet1(self, target, position, speed):
""":type target: int :type position: List[int] :type speed: List[int] ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def carFleet(self, target, position, speed):
""":type target: int :type position: List[int] :type speed: List[int] :rtype: int"""
n = len(position)
if not n:
return 0
time = [(target - position[i]) / speed[i] for i in range(n)]
a = sorted(list(zip(... | the_stack_v2_python_sparse | Array/q853_car_fleet.py | sevenhe716/LeetCode | train | 0 | |
46aec80a6e221972ea9647708cf556e76502de7a | [
"prev, current = (None, head)\nwhile current:\n temp = current.next\n current.next = prev\n prev = current\n current = temp\nreturn prev",
"def reverse(prev, current):\n if not current:\n return prev\n temp = current.next\n current.next = prev\n return reverse(current, temp)\nreturn... | <|body_start_0|>
prev, current = (None, head)
while current:
temp = current.next
current.next = prev
prev = current
current = temp
return prev
<|end_body_0|>
<|body_start_1|>
def reverse(prev, current):
if not current:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Iterative approach Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def reverseListRecursive(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Recursive approach Tim... | stack_v2_sparse_classes_75kplus_train_002494 | 1,202 | permissive | [
{
"docstring": "Iterative approach Time complexity: O(n) Space complexity: O(1)",
"name": "reverseList",
"signature": "def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]"
},
{
"docstring": "Recursive approach Time complexity: O(n) Space complexity: O(n)",
"name": "reverseL... | 2 | stack_v2_sparse_classes_30k_train_007156 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: Iterative approach Time complexity: O(n) Space complexity: O(1)
- def reverseListRecursive(self, head: Opti... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: Iterative approach Time complexity: O(n) Space complexity: O(1)
- def reverseListRecursive(self, head: Opti... | 32b0878f63e5edd19a1fbe13bfa4c518a4261e23 | <|skeleton|>
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Iterative approach Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def reverseListRecursive(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Recursive approach Tim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Iterative approach Time complexity: O(n) Space complexity: O(1)"""
prev, current = (None, head)
while current:
temp = current.next
current.next = prev
prev = current
... | the_stack_v2_python_sparse | leetcode/Linked Lists/206. Reverse Linked List.py | danielfsousa/algorithms-solutions | train | 2 | |
fa8580dfcfd6019a1faa29bb1100a9a279c12aa6 | [
"if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:\n raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')\nif not isinstance(content_image, np.ndarray) or content_image.ndim != 3 or content_image.shape[-1] != 3:\n raise TypeError('content... | <|body_start_0|>
if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:
raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')
if not isinstance(content_image, np.ndarray) or content_image.ndim != 3 or content_image.shape[-1] !... | class | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
<|body_0|>
def scale_image(image):
"""method"""
<|body_1|>
def load_model(self):
"""method"""
<|body_2|>
def gram_matrix(in... | stack_v2_sparse_classes_75kplus_train_002495 | 3,025 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"
},
{
"docstring": "method",
"name": "scale_image",
"signature": "def scale_image(image)"
},
{
"docstring": "method",
"name": "load_model",
... | 4 | stack_v2_sparse_classes_30k_train_017136 | Implement the Python class `NST` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor
- def scale_image(image): method
- def load_model(self): method
- def gram_matrix(input_layer): method | Implement the Python class `NST` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor
- def scale_image(image): method
- def load_model(self): method
- def gram_matrix(input_layer): method
<|skeleton|>
class N... | b5e8f1253309567ca7be71b9575a150de1be3820 | <|skeleton|>
class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
<|body_0|>
def scale_image(image):
"""method"""
<|body_1|>
def load_model(self):
"""method"""
<|body_2|>
def gram_matrix(in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NST:
"""class"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor"""
if not isinstance(style_image, np.ndarray) or style_image.ndim != 3 or style_image.shape[-1] != 3:
raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/2-neural_style.py | jadsm98/holbertonschool-machine_learning | train | 0 |
8fdda54c8cf74f1a9a6447b8a6edf95299b93687 | [
"now = now or OSAUtil.get_now()\nstage_max = None\nself.stageschedule.sort(key=lambda x: x['time'])\nfor data in self.stageschedule:\n if data['time'] <= now:\n continue\n stage_max = data['stage'] - 1\n break\nreturn stage_max",
"self.prize_flag = 0\nself.beginer_prize_flag = 0\nself.tip_prize_fl... | <|body_start_0|>
now = now or OSAUtil.get_now()
stage_max = None
self.stageschedule.sort(key=lambda x: x['time'])
for data in self.stageschedule:
if data['time'] <= now:
continue
stage_max = data['stage'] - 1
break
return stage_... | 開催中または開催予定のスカウトイベント. | CurrentScoutEventConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrentScoutEventConfig:
"""開催中または開催予定のスカウトイベント."""
def get_stage_max(self, now=None):
"""現在の最大ステージ数. 無制限の場合はNone."""
<|body_0|>
def reset_prize_flags(self):
"""報酬配布フラグをリセット."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
now = now or OSAUtil.g... | stack_v2_sparse_classes_75kplus_train_002496 | 22,966 | no_license | [
{
"docstring": "現在の最大ステージ数. 無制限の場合はNone.",
"name": "get_stage_max",
"signature": "def get_stage_max(self, now=None)"
},
{
"docstring": "報酬配布フラグをリセット.",
"name": "reset_prize_flags",
"signature": "def reset_prize_flags(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002671 | Implement the Python class `CurrentScoutEventConfig` described below.
Class description:
開催中または開催予定のスカウトイベント.
Method signatures and docstrings:
- def get_stage_max(self, now=None): 現在の最大ステージ数. 無制限の場合はNone.
- def reset_prize_flags(self): 報酬配布フラグをリセット. | Implement the Python class `CurrentScoutEventConfig` described below.
Class description:
開催中または開催予定のスカウトイベント.
Method signatures and docstrings:
- def get_stage_max(self, now=None): 現在の最大ステージ数. 無制限の場合はNone.
- def reset_prize_flags(self): 報酬配布フラグをリセット.
<|skeleton|>
class CurrentScoutEventConfig:
"""開催中または開催予定のスカウト... | 492bf477ac00c380f2b2758c86b46aa7e58bbad9 | <|skeleton|>
class CurrentScoutEventConfig:
"""開催中または開催予定のスカウトイベント."""
def get_stage_max(self, now=None):
"""現在の最大ステージ数. 無制限の場合はNone."""
<|body_0|>
def reset_prize_flags(self):
"""報酬配布フラグをリセット."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurrentScoutEventConfig:
"""開催中または開催予定のスカウトイベント."""
def get_stage_max(self, now=None):
"""現在の最大ステージ数. 無制限の場合はNone."""
now = now or OSAUtil.get_now()
stage_max = None
self.stageschedule.sort(key=lambda x: x['time'])
for data in self.stageschedule:
if dat... | the_stack_v2_python_sparse | src/dprj/platinumegg/app/cabaret/models/ScoutEvent.py | hitandaway100/caba | train | 0 |
0c07078acce2a17c9a4fd06c4521fef7dbad41a2 | [
"self.logger = logging.getLogger('SMAC2')\nself.traj_file_regex = 'smac3-output*/**/traj_old.csv'\nself._bin = os.path.abspath('%s/configurators/tool%s/scripts/smac' % (aclib_root, suffix_dir))",
"cmd = '/home/wagnerf/pyvenv/bin/python3 \"%s\" --parallel_scenario UCB+EACH --scenario_file %s --seed %d 1> log-%d.tx... | <|body_start_0|>
self.logger = logging.getLogger('SMAC2')
self.traj_file_regex = 'smac3-output*/**/traj_old.csv'
self._bin = os.path.abspath('%s/configurators/tool%s/scripts/smac' % (aclib_root, suffix_dir))
<|end_body_0|>
<|body_start_1|>
cmd = '/home/wagnerf/pyvenv/bin/python3 "%s" --... | TOOL_UCB_EACH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TOOL_UCB_EACH:
def __init__(self, aclib_root: str, suffix_dir: str=''):
"""Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure directory"""
<|body_0|>
def get_call(self, scenario_fn: str, seed: int=1, ac_args: list=... | stack_v2_sparse_classes_75kplus_train_002497 | 1,750 | no_license | [
{
"docstring": "Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure directory",
"name": "__init__",
"signature": "def __init__(self, aclib_root: str, suffix_dir: str='')"
},
{
"docstring": "returns call to AC procedure for a given scena... | 2 | null | Implement the Python class `TOOL_UCB_EACH` described below.
Class description:
Implement the TOOL_UCB_EACH class.
Method signatures and docstrings:
- def __init__(self, aclib_root: str, suffix_dir: str=''): Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure... | Implement the Python class `TOOL_UCB_EACH` described below.
Class description:
Implement the TOOL_UCB_EACH class.
Method signatures and docstrings:
- def __init__(self, aclib_root: str, suffix_dir: str=''): Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure... | f2e1904d8f22ff53b622e786c8f4b5bc3dbf6b66 | <|skeleton|>
class TOOL_UCB_EACH:
def __init__(self, aclib_root: str, suffix_dir: str=''):
"""Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure directory"""
<|body_0|>
def get_call(self, scenario_fn: str, seed: int=1, ac_args: list=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TOOL_UCB_EACH:
def __init__(self, aclib_root: str, suffix_dir: str=''):
"""Constructor Arguments --------- aclib_root: str root directory to AClib suffix_dir : str suffix of AC procedure directory"""
self.logger = logging.getLogger('SMAC2')
self.traj_file_regex = 'smac3-output*/**/traj... | the_stack_v2_python_sparse | final/aclib2/aclib/configurators/tool_ucb_each.py | hussieneloy/ML4AAD | train | 0 | |
30e3ca8b72cc31243d061348299db2db33ef26de | [
"self._quantile_value = quantile_value\nself._comparator_fn = comparator_fn\nself._error_loss_fn = functools.partial(loss_utils.pinball_loss, quantile=quantile)\nsuper(QuantileConstraint, self).__init__(time_step_spec, action_spec, constraint_network, error_loss_fn=self._error_loss_fn, name=name)",
"predicted_qua... | <|body_start_0|>
self._quantile_value = quantile_value
self._comparator_fn = comparator_fn
self._error_loss_fn = functools.partial(loss_utils.pinball_loss, quantile=quantile)
super(QuantileConstraint, self).__init__(time_step_spec, action_spec, constraint_network, error_loss_fn=self._err... | Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ``` | QuantileConstraint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantileConstraint:
"""Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ```"""
def __init__(self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_... | stack_v2_sparse_classes_75kplus_train_002498 | 22,532 | permissive | [
{
"docstring": "Creates a trainable quantile constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates of act... | 2 | stack_v2_sparse_classes_30k_train_018031 | Implement the Python class `QuantileConstraint` described below.
Class description:
Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ```
Method signatures and docstrings:
- def __init__(self, time_step_spe... | Implement the Python class `QuantileConstraint` described below.
Class description:
Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ```
Method signatures and docstrings:
- def __init__(self, time_step_spe... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class QuantileConstraint:
"""Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ```"""
def __init__(self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuantileConstraint:
"""Class for representing a trainable quantile constraint. This constraint class implements a quantile constraint such as ``` Q_tau(x) >= v ``` or ``` Q_tau(x) <= v ```"""
def __init__(self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: type... | the_stack_v2_python_sparse | tf_agents/bandits/policies/constraints.py | tensorflow/agents | train | 2,755 |
c6057703d8aebb9008181f9bf6431850a9bb0d41 | [
"ObjectManager.__init__(self)\nself.getters.update({'session_user_role_requirements': 'get_many_to_one', 'name': 'get_general'})\nself.setters.update({'session_user_role_requirements': 'set_many', 'name': 'set_general'})\nself.my_django_model = facade.models.SessionUserRole",
"if optional_parameters is None:\n ... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'session_user_role_requirements': 'get_many_to_one', 'name': 'get_general'})
self.setters.update({'session_user_role_requirements': 'set_many', 'name': 'set_general'})
self.my_django_model = facade.models.SessionUserRole
... | Manage SessionUserRoles in the Power Reg system | SessionUserRoleManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionUserRoleManager:
"""Manage SessionUserRoles in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, optional_parameters=None):
"""Create a new SessionUserRole Optional parameters include: url URL for a... | stack_v2_sparse_classes_75kplus_train_002499 | 1,576 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new SessionUserRole Optional parameters include: url URL for a website @param name Name for this session user role @param optional_parameters Dictionary of optional parameter names and... | 2 | stack_v2_sparse_classes_30k_train_050841 | Implement the Python class `SessionUserRoleManager` described below.
Class description:
Manage SessionUserRoles in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, optional_parameters=None): Create a new SessionUserRole Optional parameters i... | Implement the Python class `SessionUserRoleManager` described below.
Class description:
Manage SessionUserRoles in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, optional_parameters=None): Create a new SessionUserRole Optional parameters i... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class SessionUserRoleManager:
"""Manage SessionUserRoles in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, optional_parameters=None):
"""Create a new SessionUserRole Optional parameters include: url URL for a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionUserRoleManager:
"""Manage SessionUserRoles in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'session_user_role_requirements': 'get_many_to_one', 'name': 'get_general'})
self.setters.update({'session_... | the_stack_v2_python_sparse | pr_services/event_system/session_user_role_manager.py | ninemoreminutes/openassign-server | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.