blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fd9ff85a7ddf74777f5a24a389d1e18036ada39d | [
"super().__init__()\nself.normalized_shape = normalized_shape\nself.partial = True if 0 < partial < 1 else False\nself.p = partial\nself.eps = eps\nself.scale = torch.nn.Parameter(torch.ones(normalized_shape))",
"if self.partial:\n partial_size = int(self.normalized_shape * self.p)\n partial_x, _ = torch.sp... | <|body_start_0|>
super().__init__()
self.normalized_shape = normalized_shape
self.partial = True if 0 < partial < 1 else False
self.p = partial
self.eps = eps
self.scale = torch.nn.Parameter(torch.ones(normalized_shape))
<|end_body_0|>
<|body_start_1|>
if self.pa... | RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats. | RMSNorm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMSNorm:
"""RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats."""
def __init__(self, normalized_shape:... | stack_v2_sparse_classes_36k_train_017000 | 4,449 | permissive | [
{
"docstring": "Construct a RMSNorm object.",
"name": "__init__",
"signature": "def __init__(self, normalized_shape: int, eps: float=1e-05, partial: float=0.0) -> None"
},
{
"docstring": "Compute RMS normalization. Args: x: Input sequences. (B, T, D_hidden) Returns: x: Output sequences. (B, T, D... | 2 | null | Implement the Python class `RMSNorm` described below.
Class description:
RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats.
Meth... | Implement the Python class `RMSNorm` described below.
Class description:
RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats.
Meth... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class RMSNorm:
"""RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats."""
def __init__(self, normalized_shape:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RMSNorm:
"""RMSNorm module definition. Reference: https://arxiv.org/pdf/1910.07467.pdf Args: normalized_shape: Expected size. eps: Value added to the denominator for numerical stability. partial: Value defining the part of the input used for RMS stats."""
def __init__(self, normalized_shape: int, eps: fl... | the_stack_v2_python_sparse | espnet2/asr_transducer/normalization.py | espnet/espnet | train | 7,242 |
4982f4aff17a94f65f753fb1ec1b6a2656bd97ea | [
"message = (tag, ':', text_string)\nif global_step is not None:\n message = ('Global step', global_step, ',') + message\nprint(*message)\nreturn super().add_text(tag, text_string, global_step, walltime)",
"message = (tag, ':', scalar_value)\nif global_step:\n message = ('Global step', global_step, ',') + me... | <|body_start_0|>
message = (tag, ':', text_string)
if global_step is not None:
message = ('Global step', global_step, ',') + message
print(*message)
return super().add_text(tag, text_string, global_step, walltime)
<|end_body_0|>
<|body_start_1|>
message = (tag, ':', ... | SummaryWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
<|body_0|>
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Prints to consol... | stack_v2_sparse_classes_36k_train_017001 | 5,926 | no_license | [
{
"docstring": "Prints to console before running tensorboardX.SummaryWriter.add_text()",
"name": "add_text",
"signature": "def add_text(self, tag, text_string, global_step=None, walltime=None)"
},
{
"docstring": "Prints to console before running tensorboardX.SummaryWriter.add_scalar()",
"nam... | 2 | stack_v2_sparse_classes_30k_train_019359 | Implement the Python class `SummaryWriter` described below.
Class description:
Implement the SummaryWriter class.
Method signatures and docstrings:
- def add_text(self, tag, text_string, global_step=None, walltime=None): Prints to console before running tensorboardX.SummaryWriter.add_text()
- def add_scalar(self, tag... | Implement the Python class `SummaryWriter` described below.
Class description:
Implement the SummaryWriter class.
Method signatures and docstrings:
- def add_text(self, tag, text_string, global_step=None, walltime=None): Prints to console before running tensorboardX.SummaryWriter.add_text()
- def add_scalar(self, tag... | e0f6183e6b669c078793b326839665f69b3f324e | <|skeleton|>
class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
<|body_0|>
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Prints to consol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SummaryWriter:
def add_text(self, tag, text_string, global_step=None, walltime=None):
"""Prints to console before running tensorboardX.SummaryWriter.add_text()"""
message = (tag, ':', text_string)
if global_step is not None:
message = ('Global step', global_step, ',') + mes... | the_stack_v2_python_sparse | experiments/base.py | ctrl-q/pass-the-torch | train | 0 | |
ab2505776a3967f7e4f497ce64dfd80e1ce3d398 | [
"cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'\ntry:\n tx.run(cql, node_value=node_value)\nexcept Exception as e:\n print(str(e))",
"if node_value_1 is None and node_type_1 is None:\n cql = 'MATCH ()-[u:' + relationship + ']-(w:' + node_type_2 + '{name:$node_value_2}) DELETE u;'\... | <|body_start_0|>
cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'
try:
tx.run(cql, node_value=node_value)
except Exception as e:
print(str(e))
<|end_body_0|>
<|body_start_1|>
if node_value_1 is None and node_type_1 is None:
cql =... | This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplate code and allows for a clear separation ... | DeleteTransactionFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_36k_train_017002 | 12,659 | no_license | [
{
"docstring": "Delete node and all respective relationships :param tx: :param node_value: :param node_type: :return:",
"name": "delete_node",
"signature": "def delete_node(tx, node_value, node_type)"
},
{
"docstring": "Delete Utterance Relationship, based on input nodes :param tx: :param name1:... | 2 | stack_v2_sparse_classes_30k_train_016839 | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplat... | the_stack_v2_python_sparse | deliverable/SourceCode/streaming/src/graph/transaction_functions.py | eldrad294/ICS5114_Practical_Assignment | train | 0 |
208bdb5a0ad57f8b993f0d4f733a9c3cc4a8e396 | [
"self.pKa = pKa\nself.chem_type = chem_type\npass",
"Fr_n = 0.0\nFr_i = 0.0\nif self.chem_type == 'organic acid':\n Fr_n = 1.0 / (1.0 + 10.0 ** (pH - self.pKa))\n Fr_i = 1.0 - Fr_n\nelif self.chem_type == 'organic base':\n Fr_n = 1.0 / (1.0 + 10.0 ** (self.pKa - pH))\n Fr_i = 1.0 - Fr_n\nreturn (Fr_n,... | <|body_start_0|>
self.pKa = pKa
self.chem_type = chem_type
pass
<|end_body_0|>
<|body_start_1|>
Fr_n = 0.0
Fr_i = 0.0
if self.chem_type == 'organic acid':
Fr_n = 1.0 / (1.0 + 10.0 ** (pH - self.pKa))
Fr_i = 1.0 - Fr_n
elif self.chem_type =... | SpeciesFraction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeciesFraction:
def __init__(self, pKa, chem_type):
""":param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for metals, species fraction need to be generated from WHAM or MINTEQ software"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_017003 | 2,094 | no_license | [
{
"docstring": ":param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for metals, species fraction need to be generated from WHAM or MINTEQ software",
"name": "__init__",
"signature": "def __init__(self, pKa, chem_type)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_021141 | Implement the Python class `SpeciesFraction` described below.
Class description:
Implement the SpeciesFraction class.
Method signatures and docstrings:
- def __init__(self, pKa, chem_type): :param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for ... | Implement the Python class `SpeciesFraction` described below.
Class description:
Implement the SpeciesFraction class.
Method signatures and docstrings:
- def __init__(self, pKa, chem_type): :param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for ... | 94a6154b91d602f6566c57cf30af93e56802a78a | <|skeleton|>
class SpeciesFraction:
def __init__(self, pKa, chem_type):
""":param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for metals, species fraction need to be generated from WHAM or MINTEQ software"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeciesFraction:
def __init__(self, pKa, chem_type):
""":param pKa: the negative lag of the acid dissociation constant species fraction equations are used for organic acid or base for metals, species fraction need to be generated from WHAM or MINTEQ software"""
self.pKa = pKa
self.chem... | the_stack_v2_python_sparse | ChemFate_py3/species_fraction_ion.py | klaris-ak/ChemFate | train | 5 | |
6be363362f51f0d889ac06917a9e911ed094a888 | [
"if isinstance(obj, str):\n raise NotImplementedError\nself.converter = obj\nself.N = N\nself.results = None\nself.include_dummy = False\nif to_exclude is None:\n self.to_exclude = []\nelse:\n self.to_exclude = to_exclude\nif to_include is None:\n self.to_include = []\nelse:\n self.to_include = to_in... | <|body_start_0|>
if isinstance(obj, str):
raise NotImplementedError
self.converter = obj
self.N = N
self.results = None
self.include_dummy = False
if to_exclude is None:
self.to_exclude = []
else:
self.to_exclude = to_exclude
... | Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot() | Benchmark | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instanc... | stack_v2_sparse_classes_36k_train_017004 | 6,414 | permissive | [
{
"docstring": ".. rubric:: constructor :param obj: can be an instance of a converter class or a class name :param int N: number of replicates :param list to_exclude: methods to exclude from the benchmark :param list to_include: methods to include ONLY Use one of to_exclude or to_include. If both are provided, ... | 3 | stack_v2_sparse_classes_30k_test_000789 | Implement the Python class `Benchmark` described below.
Class description:
Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()
Method signatures and docstrings:
- def __init__(self, obj, N=5, to_exclude=None, to_include=Non... | Implement the Python class `Benchmark` described below.
Class description:
Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()
Method signatures and docstrings:
- def __init__(self, obj, N=5, to_exclude=None, to_include=Non... | 60a746290e763fd1041732dab0bda123841e5b26 | <|skeleton|>
class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instanc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Benchmark:
"""Convenient class to benchmark several methods for a given converter :: c = Bam2Bed(infile, outfile) b = Benchmark(c, N=5) b.run_methods() b.plot()"""
def __init__(self, obj, N=5, to_exclude=None, to_include=None):
""".. rubric:: constructor :param obj: can be an instance of a conver... | the_stack_v2_python_sparse | bioconvert/core/benchmark.py | ddesvillechabrol/bioconvert | train | 1 |
32f31b2c567502688938e0f41527ac10ebd8c6a3 | [
"seconds = convert_unit(-pseudo_pos.delay - self.user_offset.get(), self.delay.egu, 'seconds')\nmeters = seconds * speed_of_light / self.n_bounces\nmotor_value = convert_unit(meters, 'meters', self.motor.egu)\nreturn self.RealPosition(motor=motor_value)",
"meters = convert_unit(real_pos.motor, self.motor.egu, 'me... | <|body_start_0|>
seconds = convert_unit(-pseudo_pos.delay - self.user_offset.get(), self.delay.egu, 'seconds')
meters = seconds * speed_of_light / self.n_bounces
motor_value = convert_unit(meters, 'meters', self.motor.egu)
return self.RealPosition(motor=motor_value)
<|end_body_0|>
<|bod... | An inverted version of :class:`TimeToolDelay`. | _ReversedTimeToolDelay | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ReversedTimeToolDelay:
"""An inverted version of :class:`TimeToolDelay`."""
def forward(self, pseudo_pos):
"""Convert delay unit to motor unit."""
<|body_0|>
def inverse(self, real_pos):
"""Convert motor unit to delay unit."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_017005 | 16,653 | permissive | [
{
"docstring": "Convert delay unit to motor unit.",
"name": "forward",
"signature": "def forward(self, pseudo_pos)"
},
{
"docstring": "Convert motor unit to delay unit.",
"name": "inverse",
"signature": "def inverse(self, real_pos)"
}
] | 2 | null | Implement the Python class `_ReversedTimeToolDelay` described below.
Class description:
An inverted version of :class:`TimeToolDelay`.
Method signatures and docstrings:
- def forward(self, pseudo_pos): Convert delay unit to motor unit.
- def inverse(self, real_pos): Convert motor unit to delay unit. | Implement the Python class `_ReversedTimeToolDelay` described below.
Class description:
An inverted version of :class:`TimeToolDelay`.
Method signatures and docstrings:
- def forward(self, pseudo_pos): Convert delay unit to motor unit.
- def inverse(self, real_pos): Convert motor unit to delay unit.
<|skeleton|>
cla... | 9d928b1466dd3714d38c703d7d07953a9f1b58f1 | <|skeleton|>
class _ReversedTimeToolDelay:
"""An inverted version of :class:`TimeToolDelay`."""
def forward(self, pseudo_pos):
"""Convert delay unit to motor unit."""
<|body_0|>
def inverse(self, real_pos):
"""Convert motor unit to delay unit."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ReversedTimeToolDelay:
"""An inverted version of :class:`TimeToolDelay`."""
def forward(self, pseudo_pos):
"""Convert delay unit to motor unit."""
seconds = convert_unit(-pseudo_pos.delay - self.user_offset.get(), self.delay.egu, 'seconds')
meters = seconds * speed_of_light / sel... | the_stack_v2_python_sparse | pcdsdevices/lxe.py | slactjohnson/pcdsdevices | train | 0 |
e91d9cb1c951ee22dd863dcb1a6c9ec726b20a0f | [
"search_term = request.args.get('q') or None\nlimit = request.args.get('limit') or Config.MAX_PAGE_SIZE\npage_limit = 100 if int(limit) > 100 else int(limit)\npage = request.args.get('page') or 1\nif page_limit < 1 or page < 1:\n return abort(400, 'Page or Limit cannot be negative values')\npostal_data = Postal.... | <|body_start_0|>
search_term = request.args.get('q') or None
limit = request.args.get('limit') or Config.MAX_PAGE_SIZE
page_limit = 100 if int(limit) > 100 else int(limit)
page = request.args.get('page') or 1
if page_limit < 1 or page < 1:
return abort(400, 'Page or L... | PostalEndPoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostalEndPoint:
def get(self):
"""Retrieve postal records"""
<|body_0|>
def post(self):
"""Create a postal resource"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
search_term = request.args.get('q') or None
limit = request.args.get('limit')... | stack_v2_sparse_classes_36k_train_017006 | 10,081 | permissive | [
{
"docstring": "Retrieve postal records",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a postal resource",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015676 | Implement the Python class `PostalEndPoint` described below.
Class description:
Implement the PostalEndPoint class.
Method signatures and docstrings:
- def get(self): Retrieve postal records
- def post(self): Create a postal resource | Implement the Python class `PostalEndPoint` described below.
Class description:
Implement the PostalEndPoint class.
Method signatures and docstrings:
- def get(self): Retrieve postal records
- def post(self): Create a postal resource
<|skeleton|>
class PostalEndPoint:
def get(self):
"""Retrieve postal r... | 652c156b622e679fa2e68d2fb4b0f87180b3ca11 | <|skeleton|>
class PostalEndPoint:
def get(self):
"""Retrieve postal records"""
<|body_0|>
def post(self):
"""Create a postal resource"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostalEndPoint:
def get(self):
"""Retrieve postal records"""
search_term = request.args.get('q') or None
limit = request.args.get('limit') or Config.MAX_PAGE_SIZE
page_limit = 100 if int(limit) > 100 else int(limit)
page = request.args.get('page') or 1
if page_l... | the_stack_v2_python_sparse | app/api/v1/postal.py | Enkya/ims_beta | train | 0 | |
7eae07e3f21efe42555adc9f7c3cc9b06fc4e13c | [
"assert 0 < eta, 'Efficiency of boiler should be greater 0.' + ' Check your input for eta.'\nassert eta <= 1, 'Efficiency of boiler should smaller or equal to 1.' + ' Check your input for eta.'\nsuper(BoilerExtended, self).__init__(environment=environment, qNominal=q_nominal, tMax=t_max, lowerActivationLimit=lower_... | <|body_start_0|>
assert 0 < eta, 'Efficiency of boiler should be greater 0.' + ' Check your input for eta.'
assert eta <= 1, 'Efficiency of boiler should smaller or equal to 1.' + ' Check your input for eta.'
super(BoilerExtended, self).__init__(environment=environment, qNominal=q_nominal, tMax=... | BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power | BoilerExtended | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoilerExtended:
"""BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power"""
def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2):
"""Parameters ---------- env... | stack_v2_sparse_classes_36k_train_017007 | 6,053 | permissive | [
{
"docstring": "Parameters ---------- environment : Extended environment object Common to all other objects. Includes time and weather instances q_nominal : float nominal heat output in W eta : float efficiency (without unit) t_max : Integer, optional maximum provided temperature in °C (default : 85 °C) lower_a... | 5 | stack_v2_sparse_classes_30k_val_000529 | Implement the Python class `BoilerExtended` described below.
Class description:
BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power
Method signatures and docstrings:
- def __init__(self, environment, q_nominal, eta, t_max=8... | Implement the Python class `BoilerExtended` described below.
Class description:
BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power
Method signatures and docstrings:
- def __init__(self, environment, q_nominal, eta, t_max=8... | 99fd0dab7f9a9030fd84ba4715753364662927ec | <|skeleton|>
class BoilerExtended:
"""BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power"""
def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2):
"""Parameters ---------- env... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoilerExtended:
"""BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power"""
def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2):
"""Parameters ---------- environment : Ex... | the_stack_v2_python_sparse | pycity_calc/energysystems/boiler.py | RWTH-EBC/pyCity_calc | train | 4 |
13ce7d3434101e5872b225867f3f353c995e9687 | [
"mata = np.zeros((3, 3))\nif self.ProbaRew == [1, 1, 1]:\n sequ = self.seqChoix\nelse:\n sequ = self.seqChoix + 3\n sequ[sequ == self.ProbaRew.index(0.25) + 3] = 0\n sequ[sequ == self.ProbaRew.index(0.5) + 3] = 1\n sequ[sequ == self.ProbaRew.index(1) + 3] = 2\nll = len(sequ)\ns1 = sequ[0:ll - 1]\ns2 ... | <|body_start_0|>
mata = np.zeros((3, 3))
if self.ProbaRew == [1, 1, 1]:
sequ = self.seqChoix
else:
sequ = self.seqChoix + 3
sequ[sequ == self.ProbaRew.index(0.25) + 3] = 0
sequ[sequ == self.ProbaRew.index(0.5) + 3] = 1
sequ[sequ == self... | AnalyseProbabiliste | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyseProbabiliste:
def matrixchoix(self):
"""% matrice de transition normalisé"""
<|body_0|>
def betaphi(self):
"""Estimation de beta et phi"""
<|body_1|>
def beta(self):
"""Estimation de beta"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_017008 | 3,416 | no_license | [
{
"docstring": "% matrice de transition normalisé",
"name": "matrixchoix",
"signature": "def matrixchoix(self)"
},
{
"docstring": "Estimation de beta et phi",
"name": "betaphi",
"signature": "def betaphi(self)"
},
{
"docstring": "Estimation de beta",
"name": "beta",
"sign... | 3 | stack_v2_sparse_classes_30k_test_000362 | Implement the Python class `AnalyseProbabiliste` described below.
Class description:
Implement the AnalyseProbabiliste class.
Method signatures and docstrings:
- def matrixchoix(self): % matrice de transition normalisé
- def betaphi(self): Estimation de beta et phi
- def beta(self): Estimation de beta | Implement the Python class `AnalyseProbabiliste` described below.
Class description:
Implement the AnalyseProbabiliste class.
Method signatures and docstrings:
- def matrixchoix(self): % matrice de transition normalisé
- def betaphi(self): Estimation de beta et phi
- def beta(self): Estimation de beta
<|skeleton|>
c... | 82f9c78828a1e1fb6c3d60d91777638720129e1a | <|skeleton|>
class AnalyseProbabiliste:
def matrixchoix(self):
"""% matrice de transition normalisé"""
<|body_0|>
def betaphi(self):
"""Estimation de beta et phi"""
<|body_1|>
def beta(self):
"""Estimation de beta"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyseProbabiliste:
def matrixchoix(self):
"""% matrice de transition normalisé"""
mata = np.zeros((3, 3))
if self.ProbaRew == [1, 1, 1]:
sequ = self.seqChoix
else:
sequ = self.seqChoix + 3
sequ[sequ == self.ProbaRew.index(0.25) + 3] = 0
... | the_stack_v2_python_sparse | py_NPClab_Package/AnalyseComportment/Traitement3points.py | NPC-lab-python/py_NPC-Lab_Packages | train | 0 | |
700c185d9f867c5bf7db8c45c4dc913a7ab04271 | [
"start_point = {projected_space_dim_2_dim[index]: value for index, value in enumerate(edge_in_two_dimension.left_point().values())}\nstart_point.update(additional_dim_2_value)\nstart_point_values = [start_point[key] for key in sorted(start_point)]\nend_point = {projected_space_dim_2_dim[index]: value for index, val... | <|body_start_0|>
start_point = {projected_space_dim_2_dim[index]: value for index, value in enumerate(edge_in_two_dimension.left_point().values())}
start_point.update(additional_dim_2_value)
start_point_values = [start_point[key] for key in sorted(start_point)]
end_point = {projected_spa... | Implements the utilities to convert types to each other | TypeConversionUtilities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeConversionUtilities:
"""Implements the utilities to convert types to each other"""
def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim):
"""Returns an edge in the original search space from the edge in the projected search sp... | stack_v2_sparse_classes_36k_train_017009 | 41,178 | permissive | [
{
"docstring": "Returns an edge in the original search space from the edge in the projected search space",
"name": "edge_in_two_dimension_to_edge",
"signature": "def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim)"
},
{
"docstring": "Conver... | 3 | stack_v2_sparse_classes_30k_train_001329 | Implement the Python class `TypeConversionUtilities` described below.
Class description:
Implements the utilities to convert types to each other
Method signatures and docstrings:
- def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim): Returns an edge in the origi... | Implement the Python class `TypeConversionUtilities` described below.
Class description:
Implements the utilities to convert types to each other
Method signatures and docstrings:
- def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim): Returns an edge in the origi... | 465ea7aaa62157411f9f181b994f4d7e6b8a2e33 | <|skeleton|>
class TypeConversionUtilities:
"""Implements the utilities to convert types to each other"""
def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim):
"""Returns an edge in the original search space from the edge in the projected search sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeConversionUtilities:
"""Implements the utilities to convert types to each other"""
def edge_in_two_dimension_to_edge(additional_dim_2_value, edge_in_two_dimension, projected_space_dim_2_dim):
"""Returns an edge in the original search space from the edge in the projected search space"""
... | the_stack_v2_python_sparse | src/momilp/utilities.py | gokhanceyhan/momilp | train | 2 |
7fd543ee8b70b1669c41e61ac0e24e5595bb0b9c | [
"self.w = w\nself.n = len(w)\nself.s = sum(self.w)\nfor i in range(1, self.n):\n w[i] += w[i - 1]",
"seed = random.randint(1, self.s)\nl, r = (0, self.n - 1)\nwhile l < r:\n mid = (l + r) // 2\n if seed <= self.w[mid]:\n r = mid\n else:\n l = mid + 1\nreturn l"
] | <|body_start_0|>
self.w = w
self.n = len(w)
self.s = sum(self.w)
for i in range(1, self.n):
w[i] += w[i - 1]
<|end_body_0|>
<|body_start_1|>
seed = random.randint(1, self.s)
l, r = (0, self.n - 1)
while l < r:
mid = (l + r) // 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.w = w
self.n = len(w)
self.s = sum(self.w)
for i in range(1, self.n... | stack_v2_sparse_classes_36k_train_017010 | 570 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008909 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | eb3fc22450b362703c3322d9e975d191eb324ffc | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.w = w
self.n = len(w)
self.s = sum(self.w)
for i in range(1, self.n):
w[i] += w[i - 1]
def pickIndex(self):
""":rtype: int"""
seed = random.randint(1, self.s)
l, r = ... | the_stack_v2_python_sparse | 2-27/528-Random-Pick-with-Weight.py | whalejasmine/leetcode_python_summary | train | 0 | |
866c5f07f843369d8f12c6aa476e70b828fc45e7 | [
"self.include_labels = True\nif del_existing:\n if os.path.exists(output_path):\n os.remove(output_path)\nelif os.path.exists(output_path):\n raise ValueError('Output path already exists', output_path)\nself.db = h5py.File(output_path, 'w', libver='latest')\nself.feat_dataset = self.db.create_dataset(f... | <|body_start_0|>
self.include_labels = True
if del_existing:
if os.path.exists(output_path):
os.remove(output_path)
elif os.path.exists(output_path):
raise ValueError('Output path already exists', output_path)
self.db = h5py.File(output_path, 'w', ... | HDF5Writer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of imag... | stack_v2_sparse_classes_36k_train_017011 | 3,622 | no_license | [
{
"docstring": "Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of images, height, width, # of channels) :param output_path: full path to the HDF5 file :param feat_key: name of the features data set :param label_key: name of the labels data set :param ... | 5 | stack_v2_sparse_classes_30k_train_016679 | Implement the Python class `HDF5Writer` described below.
Class description:
Implement the HDF5Writer class.
Method signatures and docstrings:
- def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8): Create the new H... | Implement the Python class `HDF5Writer` described below.
Class description:
Implement the HDF5Writer class.
Method signatures and docstrings:
- def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8): Create the new H... | e9f2010715fa06f50095d05684617c86e18ca661 | <|skeleton|>
class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of imag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of images, height, wi... | the_stack_v2_python_sparse | dltoolkit/iomisc/hdf5writer.py | GeoffBreemer/DLToolkit | train | 2 | |
fc841da4131ef82e9b0b1af08c1b7b9bb89ac715 | [
"self.logger = logger\nself.is_trained = False\nself.supported_formats = ['pkl', 'onnx', 'pmml']\nself.name = 'FBSVM'\nself.centroids = None\nself.weights = None\nself.sigma = None",
"NP = X_b.shape[0]\nNC = self.centroids.shape[0]\nXC2 = -2 * np.dot(X_b, self.centroids.T)\nXC2 += np.sum(np.multiply(X_b, X_b), ax... | <|body_start_0|>
self.logger = logger
self.is_trained = False
self.supported_formats = ['pkl', 'onnx', 'pmml']
self.name = 'FBSVM'
self.centroids = None
self.weights = None
self.sigma = None
<|end_body_0|>
<|body_start_1|>
NP = X_b.shape[0]
NC = s... | This class contains the Federated Budget SVM model. | FBSVM_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FBSVM_model:
"""This class contains the Federated Budget SVM model."""
def __init__(self, logger):
"""Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
<|body_0|>
def predict(self, X_b):
""... | stack_v2_sparse_classes_36k_train_017012 | 17,863 | permissive | [
{
"docstring": "Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.",
"name": "__init__",
"signature": "def __init__(self, logger)"
},
{
"docstring": "Uses the model to predict new outputs given for an unlabeled dataset. Parame... | 2 | stack_v2_sparse_classes_30k_test_000631 | Implement the Python class `FBSVM_model` described below.
Class description:
This class contains the Federated Budget SVM model.
Method signatures and docstrings:
- def __init__(self, logger): Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.
- de... | Implement the Python class `FBSVM_model` described below.
Class description:
This class contains the Federated Budget SVM model.
Method signatures and docstrings:
- def __init__(self, logger): Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.
- de... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class FBSVM_model:
"""This class contains the Federated Budget SVM model."""
def __init__(self, logger):
"""Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
<|body_0|>
def predict(self, X_b):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FBSVM_model:
"""This class contains the Federated Budget SVM model."""
def __init__(self, logger):
"""Create a :class:`FBSVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
self.logger = logger
self.is_trained = False
se... | the_stack_v2_python_sparse | MMLL/models/POM1/FBSVM/FBSVM.py | Musketeer-H2020/MMLL-Robust | train | 0 |
6c8d9a50fde0455f8c3b2dcacce2089db3fcd7f6 | [
"authors = ','.join([x['name'] for x in doc.artists])\nauthor = re.sub('[\\\\\\\\/:*?\"<>|]', '', authors.strip())\nmv_name = re.sub('[\\\\\\\\/:*?\"<>|]', '', doc['name'])\nname = '%s - %s.mp4' % (author, mv_name)\nreturn name",
"authors = ','.join([x['name'] for x in doc.artists])\nauthor = re.sub('[\\\\\\\\/:*... | <|body_start_0|>
authors = ','.join([x['name'] for x in doc.artists])
author = re.sub('[\\\\/:*?"<>|]', '', authors.strip())
mv_name = re.sub('[\\\\/:*?"<>|]', '', doc['name'])
name = '%s - %s.mp4' % (author, mv_name)
return name
<|end_body_0|>
<|body_start_1|>
authors =... | MV | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MV:
def download_filename(self, doc):
"""implement pls get a name to save file need be complete by child :param doc: :return:"""
<|body_0|>
def download_filename_full(self, doc):
"""implement pls get a path to save file, by relative path need be complete by child :pa... | stack_v2_sparse_classes_36k_train_017013 | 2,280 | permissive | [
{
"docstring": "implement pls get a name to save file need be complete by child :param doc: :return:",
"name": "download_filename",
"signature": "def download_filename(self, doc)"
},
{
"docstring": "implement pls get a path to save file, by relative path need be complete by child :param doc: :re... | 4 | stack_v2_sparse_classes_30k_train_007884 | Implement the Python class `MV` described below.
Class description:
Implement the MV class.
Method signatures and docstrings:
- def download_filename(self, doc): implement pls get a name to save file need be complete by child :param doc: :return:
- def download_filename_full(self, doc): implement pls get a path to sa... | Implement the Python class `MV` described below.
Class description:
Implement the MV class.
Method signatures and docstrings:
- def download_filename(self, doc): implement pls get a name to save file need be complete by child :param doc: :return:
- def download_filename_full(self, doc): implement pls get a path to sa... | 68e588c0612d0ab2af3a820ff88ca24d698ceeb7 | <|skeleton|>
class MV:
def download_filename(self, doc):
"""implement pls get a name to save file need be complete by child :param doc: :return:"""
<|body_0|>
def download_filename_full(self, doc):
"""implement pls get a path to save file, by relative path need be complete by child :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MV:
def download_filename(self, doc):
"""implement pls get a name to save file need be complete by child :param doc: :return:"""
authors = ','.join([x['name'] for x in doc.artists])
author = re.sub('[\\\\/:*?"<>|]', '', authors.strip())
mv_name = re.sub('[\\\\/:*?"<>|]', '', do... | the_stack_v2_python_sparse | NXSpider/spider/mv.py | Z-Shuming/NXSpider | train | 0 | |
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_36k_train_017014 | 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 | null | 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_36k | data/stack_v2_sparse_classes_30k | 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 | |
abf0dbb97e52fe803cc6fa486118c4b4bbc653d4 | [
"self._scope = ('%s/' % name if name else '') + 'HashTableIndexer'\nwith tf.name_scope(self._scope):\n self._key_to_index = tf.lookup.experimental.DenseHashTable(key_dtype=key_dtype, value_dtype=tf.int32, default_value=-1, empty_key=empty_key, deleted_key=deleted_key)\n self._max_index = max_index",
"with t... | <|body_start_0|>
self._scope = ('%s/' % name if name else '') + 'HashTableIndexer'
with tf.name_scope(self._scope):
self._key_to_index = tf.lookup.experimental.DenseHashTable(key_dtype=key_dtype, value_dtype=tf.int32, default_value=-1, empty_key=empty_key, deleted_key=deleted_key)
... | Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequentially: The first key would receive the index 0, the second 1, etc. | HashTableIndexer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTableIndexer:
"""Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequentially: The first key would receive the i... | stack_v2_sparse_classes_36k_train_017015 | 8,366 | permissive | [
{
"docstring": "Creates an instance. Args: max_index: An integer, all keys will be mapped to indices will be in the interval [0, max_index). Trying to insert more keys will raise an exception. key_dtype: Type of the key. empty_key: A key that denotes \"no key\". deleted_key: A key that denotes a deleted key. na... | 2 | stack_v2_sparse_classes_30k_train_021585 | Implement the Python class `HashTableIndexer` described below.
Class description:
Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequenti... | Implement the Python class `HashTableIndexer` described below.
Class description:
Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequenti... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class HashTableIndexer:
"""Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequentially: The first key would receive the i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HashTableIndexer:
"""Using a hash table, maps sparse keys to dense integer indices. The main method is get_or_create_index(self, key), which allocates (or fetches if exists) an integer index, in [0, max_index), to each `key`. The indices are created sequentially: The first key would receive the index 0, the s... | the_stack_v2_python_sparse | depth_and_motion_learning/intrinsics_utils.py | Jimmy-INL/google-research | train | 1 |
e950f3f74a00718ebb0e1fe0d7a6f3a6aeb9a303 | [
"self.a = a\nself.lambda0 = lambda0\nself.e = e\nself.I = I\nself.lon_of_peri = lon_of_peri\nself.node = node\nself.T = T\nself.color = color\nself.size = size\nself.n = 2 * np.pi / self.T",
"E = self.solveForE(t)\nx, y, z = orbitalElements2Cartesian(self.a, self.e, self.I, self.lon_of_peri - self.node, self.node... | <|body_start_0|>
self.a = a
self.lambda0 = lambda0
self.e = e
self.I = I
self.lon_of_peri = lon_of_peri
self.node = node
self.T = T
self.color = color
self.size = size
self.n = 2 * np.pi / self.T
<|end_body_0|>
<|body_start_1|>
E =... | Defines a planet in the Solar System. | Planet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Planet:
"""Defines a planet in the Solar System."""
def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20):
"""Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degrees) e: [float] eccentricity I: [float]: inclination (deg... | stack_v2_sparse_classes_36k_train_017016 | 13,183 | permissive | [
{
"docstring": "Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degrees) e: [float] eccentricity I: [float]: inclination (degrees) lon_of_peri: [float] longitude of perihelion (degrees) node: [float] longitude of ascending node (degrees) T: [float]: orbital period (years) Ke... | 4 | stack_v2_sparse_classes_30k_train_021573 | Implement the Python class `Planet` described below.
Class description:
Defines a planet in the Solar System.
Method signatures and docstrings:
- def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20): Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degr... | Implement the Python class `Planet` described below.
Class description:
Defines a planet in the Solar System.
Method signatures and docstrings:
- def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20): Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degr... | fe511f264c4354a84b4a1c60f257883473e3855d | <|skeleton|>
class Planet:
"""Defines a planet in the Solar System."""
def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20):
"""Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degrees) e: [float] eccentricity I: [float]: inclination (deg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Planet:
"""Defines a planet in the Solar System."""
def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20):
"""Arguments: a: [float] semi-major axis (AU) lambda0: [float] mean longitude at epoch (degrees) e: [float] eccentricity I: [float]: inclination (degrees) lon_of_... | the_stack_v2_python_sparse | wmpl/Utils/PlotOrbits.py | wmpg/WesternMeteorPyLib | train | 29 |
4d302e147b019574635ba482bca66722d7046862 | [
"self._x0 = x0\nself._y0 = y0\nself._x1 = x1\nself._y1 = y1\nself._rsquared = r * r",
"if collision:\n return (-1.0, False)\nax = x - self._x0\nay = y - self._y0\nbx = self._x1 - self._x0\nby = self._y1 - self._y0\nda = ax * ax + ay * ay\ndot = ax * bx + ay * by\nif dot <= 0.0:\n return (0.0, False)\ndb = b... | <|body_start_0|>
self._x0 = x0
self._y0 = y0
self._x1 = x1
self._y1 = y1
self._rsquared = r * r
<|end_body_0|>
<|body_start_1|>
if collision:
return (-1.0, False)
ax = x - self._x0
ay = y - self._y0
bx = self._x1 - self._x0
by ... | Represents a driving task as a rectangle that the agent's car must enter. | Task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""Represents a driving task as a rectangle that the agent's car must enter."""
def __init__(self, x0, y0, x1, y1, r):
"""Initializes the task. The goal region is defined by a vector, and a distance to the vector that the car must be within to complete the task. Intuitively, ea... | stack_v2_sparse_classes_36k_train_017017 | 1,677 | no_license | [
{
"docstring": "Initializes the task. The goal region is defined by a vector, and a distance to the vector that the car must be within to complete the task. Intuitively, each task specifies a lane the car must enter. :param x0: the first x coordinate of the vector :param y0: the first y coordinate of the vector... | 2 | stack_v2_sparse_classes_30k_train_019724 | Implement the Python class `Task` described below.
Class description:
Represents a driving task as a rectangle that the agent's car must enter.
Method signatures and docstrings:
- def __init__(self, x0, y0, x1, y1, r): Initializes the task. The goal region is defined by a vector, and a distance to the vector that the... | Implement the Python class `Task` described below.
Class description:
Represents a driving task as a rectangle that the agent's car must enter.
Method signatures and docstrings:
- def __init__(self, x0, y0, x1, y1, r): Initializes the task. The goal region is defined by a vector, and a distance to the vector that the... | 381c019a3c930d943672a65ae651e5a4f52686f8 | <|skeleton|>
class Task:
"""Represents a driving task as a rectangle that the agent's car must enter."""
def __init__(self, x0, y0, x1, y1, r):
"""Initializes the task. The goal region is defined by a vector, and a distance to the vector that the car must be within to complete the task. Intuitively, ea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Task:
"""Represents a driving task as a rectangle that the agent's car must enter."""
def __init__(self, x0, y0, x1, y1, r):
"""Initializes the task. The goal region is defined by a vector, and a distance to the vector that the car must be within to complete the task. Intuitively, each task speci... | the_stack_v2_python_sparse | domains/driving/tasks.py | rtloftin/HAL | train | 0 |
c464bc8bb0fd18623b969de358f61ae9bd405f78 | [
"with open(fname, 'rb') as f:\n imghash = hashlib.md5(f.read()).hexdigest()\nif cls.query.filter(cls.hash == imghash).count() > 0:\n return imghash\nfrom PIL import Image\nimg = Image.open(fname)\nw = round(img.width * cls.target_size / max(img.width, img.height))\nh = round(img.height * cls.target_size / max... | <|body_start_0|>
with open(fname, 'rb') as f:
imghash = hashlib.md5(f.read()).hexdigest()
if cls.query.filter(cls.hash == imghash).count() > 0:
return imghash
from PIL import Image
img = Image.open(fname)
w = round(img.width * cls.target_size / max(img.wid... | Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression. | TeamLogo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamLogo:
"""Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression."""
def store_logo_file(cls, fname: str) -> str:
"""Store a source file from disk into database (if not already there). :param fname: :return: md5-h... | stack_v2_sparse_classes_36k_train_017018 | 20,941 | no_license | [
{
"docstring": "Store a source file from disk into database (if not already there). :param fname: :return: md5-hash that identifies this image later.",
"name": "store_logo_file",
"signature": "def store_logo_file(cls, fname: str) -> str"
},
{
"docstring": "Save a database image to disk, identifi... | 2 | null | Implement the Python class `TeamLogo` described below.
Class description:
Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression.
Method signatures and docstrings:
- def store_logo_file(cls, fname: str) -> str: Store a source file from disk into data... | Implement the Python class `TeamLogo` described below.
Class description:
Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression.
Method signatures and docstrings:
- def store_logo_file(cls, fname: str) -> str: Store a source file from disk into data... | b54f4581366348d5b50cada3023aad0538d87bc8 | <|skeleton|>
class TeamLogo:
"""Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression."""
def store_logo_file(cls, fname: str) -> str:
"""Store a source file from disk into database (if not already there). :param fname: :return: md5-h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamLogo:
"""Team logos stored in database. Each logo is keyed by the md5-hash of the original source image ("hash") before compression."""
def store_logo_file(cls, fname: str) -> str:
"""Store a source file from disk into database (if not already there). :param fname: :return: md5-hash that iden... | the_stack_v2_python_sparse | controlserver/models.py | efiens/saarctf-gameserver | train | 0 |
f2236117e4e9c1f865190bc568386c39a03b83b4 | [
"if not root:\n return ''\nstack = [root]\nans = []\nwhile stack:\n node = stack.pop()\n ans.append(str(node.val))\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\nreturn ','.join(ans)",
"if not data:\n return None\ndata = data.split(',')\nroot... | <|body_start_0|>
if not root:
return ''
stack = [root]
ans = []
while stack:
node = stack.pop()
ans.append(str(node.val))
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.le... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017019 | 1,684 | 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_003938 | 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:... | 5e09a5d36ac55d782628a888ad57d48e234b61ac | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
stack = [root]
ans = []
while stack:
node = stack.pop()
ans.append(str(node.val))
if node.r... | the_stack_v2_python_sparse | 449/449.py | sjzyjc/leetcode | train | 0 | |
ffe83492365d2d1bf5c19028b03e0bf01376c7da | [
"if not user:\n raise ValueError('User should not be None.')\nif not number:\n return\nproperties = {key: self.const_data_handler.get(key) for key, info in self.get_properties_info().items()}\nto_change = {key: value * number for key, value in properties.items() if value != 0}\nchanges = user.change_states(to... | <|body_start_0|>
if not user:
raise ValueError('User should not be None.')
if not number:
return
properties = {key: self.const_data_handler.get(key) for key, info in self.get_properties_info().items()}
to_change = {key: value * number for key, value in properties.... | This is a food. Players can use it to change their properties, such as hp, mp, strength, etc. | MudderyFood | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MudderyFood:
"""This is a food. Players can use it to change their properties, such as hp, mp, strength, etc."""
def take_effect(self, user, number):
"""Use this object. Args: user: (object) the object who uses this Returns: result: (string) a description of the result"""
<|b... | stack_v2_sparse_classes_36k_train_017020 | 7,037 | permissive | [
{
"docstring": "Use this object. Args: user: (object) the object who uses this Returns: result: (string) a description of the result",
"name": "take_effect",
"signature": "def take_effect(self, user, number)"
},
{
"docstring": "This returns a list of available commands. \"args\" must be a string... | 2 | null | Implement the Python class `MudderyFood` described below.
Class description:
This is a food. Players can use it to change their properties, such as hp, mp, strength, etc.
Method signatures and docstrings:
- def take_effect(self, user, number): Use this object. Args: user: (object) the object who uses this Returns: re... | Implement the Python class `MudderyFood` described below.
Class description:
This is a food. Players can use it to change their properties, such as hp, mp, strength, etc.
Method signatures and docstrings:
- def take_effect(self, user, number): Use this object. Args: user: (object) the object who uses this Returns: re... | 669fbbdb394d04995470e32e94f10d42f3387996 | <|skeleton|>
class MudderyFood:
"""This is a food. Players can use it to change their properties, such as hp, mp, strength, etc."""
def take_effect(self, user, number):
"""Use this object. Args: user: (object) the object who uses this Returns: result: (string) a description of the result"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MudderyFood:
"""This is a food. Players can use it to change their properties, such as hp, mp, strength, etc."""
def take_effect(self, user, number):
"""Use this object. Args: user: (object) the object who uses this Returns: result: (string) a description of the result"""
if not user:
... | the_stack_v2_python_sparse | muddery/server/elements/pocket_object.py | dongwudanci/muddery | train | 0 |
8606406f32f0194483f0e46218dafa1d1b72e9b2 | [
"for i1, n1 in enumerate(nums):\n for i2, n2 in enumerate(nums):\n if i1 == i2:\n continue\n if n1 + n2 == target:\n return (i1, i2)",
"d = defaultdict(list)\nfor i, n in enumerate(nums):\n d[n].append(i)\nfor n, i in d.iteritems():\n i1 = i[0]\n n2 = target - n\n ... | <|body_start_0|>
for i1, n1 in enumerate(nums):
for i2, n2 in enumerate(nums):
if i1 == i2:
continue
if n1 + n2 == target:
return (i1, i2)
<|end_body_0|>
<|body_start_1|>
d = defaultdict(list)
for i, n in enumer... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_HashTwoPass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def two... | stack_v2_sparse_classes_36k_train_017021 | 1,423 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_BruteForce",
"signature": "def twoSum_BruteForce(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_HashTwoPass",
"signature": "def... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_BruteForce(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_HashTwoPass(self, nums, target): :type nums: List[int] :type tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_BruteForce(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum_HashTwoPass(self, nums, target): :type nums: List[int] :type tar... | 5c2473f859da5efec73120256faad06ab8e0e359 | <|skeleton|>
class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_HashTwoPass(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def two... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_BruteForce(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i1, n1 in enumerate(nums):
for i2, n2 in enumerate(nums):
if i1 == i2:
continue
if n1 + n2 == target:
... | the_stack_v2_python_sparse | leetcode/two_sum.py | chlos/exercises_in_futility | train | 0 | |
294a01b88176af7806c788a0138eabd12a3e5e99 | [
"super(ICA, self).__init__(input_dim, False)\nself.input_dim = input_dim\nself.output_dim = input_dim\nself.trained = False",
"if self.input_dim != data.shape[1]:\n raise ValueError('Wrong data dimensionality.')\nself.projection_matrix = numx.random.randn(data.shape[1], data.shape[1])\nprojection_matrix_old = ... | <|body_start_0|>
super(ICA, self).__init__(input_dim, False)
self.input_dim = input_dim
self.output_dim = input_dim
self.trained = False
<|end_body_0|>
<|body_start_1|>
if self.input_dim != data.shape[1]:
raise ValueError('Wrong data dimensionality.')
self.pr... | Independent Component Analysis using FastICA. | ICA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICA:
"""Independent Component Analysis using FastICA."""
def __init__(self, input_dim):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int"""
<|body_0|>
def train(self, data, iterations=1000, convergence=0.0, status=False):
"""Training th... | stack_v2_sparse_classes_36k_train_017022 | 13,683 | no_license | [
{
"docstring": "Constructor. :param input_dim: Data dimensionality. :type input_dim: int",
"name": "__init__",
"signature": "def __init__(self, input_dim)"
},
{
"docstring": "Training the model (full batch). :param data: data for training. :type data: numpy array [num data point, data dimension]... | 3 | stack_v2_sparse_classes_30k_train_019559 | Implement the Python class `ICA` described below.
Class description:
Independent Component Analysis using FastICA.
Method signatures and docstrings:
- def __init__(self, input_dim): Constructor. :param input_dim: Data dimensionality. :type input_dim: int
- def train(self, data, iterations=1000, convergence=0.0, statu... | Implement the Python class `ICA` described below.
Class description:
Independent Component Analysis using FastICA.
Method signatures and docstrings:
- def __init__(self, input_dim): Constructor. :param input_dim: Data dimensionality. :type input_dim: int
- def train(self, data, iterations=1000, convergence=0.0, statu... | 997879373110b2ee69fba921d46a309443c8e374 | <|skeleton|>
class ICA:
"""Independent Component Analysis using FastICA."""
def __init__(self, input_dim):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int"""
<|body_0|>
def train(self, data, iterations=1000, convergence=0.0, status=False):
"""Training th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ICA:
"""Independent Component Analysis using FastICA."""
def __init__(self, input_dim):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int"""
super(ICA, self).__init__(input_dim, False)
self.input_dim = input_dim
self.output_dim = input_dim
... | the_stack_v2_python_sparse | pydeep/preprocessing.py | MelJan/PyDeep | train | 50 |
a43f8eaa4a9d29af119112e32cfd0a20815b4fa5 | [
"try:\n self.conf_file = conf_file\n self.port_details = port_details\n self.ports = []\n self.hostname = socket.gethostbyname(socket.gethostname())\nexcept Exception as e:\n print(e)\n sys.exit(1)",
"try:\n infile = open(self.conf_file)\n infile_content = infile.readlines()\n infile.cl... | <|body_start_0|>
try:
self.conf_file = conf_file
self.port_details = port_details
self.ports = []
self.hostname = socket.gethostbyname(socket.gethostname())
except Exception as e:
print(e)
sys.exit(1)
<|end_body_0|>
<|body_start_1|... | . | Ports | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ports:
"""."""
def __init__(self, conf_file, port_details):
"""."""
<|body_0|>
def get_ports_from_conf_to_port_details(self):
"""."""
<|body_1|>
def get_port_details_from_port_details_file(line):
"""."""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_017023 | 12,520 | no_license | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, conf_file, port_details)"
},
{
"docstring": ".",
"name": "get_ports_from_conf_to_port_details",
"signature": "def get_ports_from_conf_to_port_details(self)"
},
{
"docstring": ".",
"name": "get_port_detai... | 3 | stack_v2_sparse_classes_30k_train_019113 | Implement the Python class `Ports` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, conf_file, port_details): .
- def get_ports_from_conf_to_port_details(self): .
- def get_port_details_from_port_details_file(line): . | Implement the Python class `Ports` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, conf_file, port_details): .
- def get_ports_from_conf_to_port_details(self): .
- def get_port_details_from_port_details_file(line): .
<|skeleton|>
class Ports:
"""."""
def __init__... | e513224364dce05ea4d17ac25ecfa981238b1311 | <|skeleton|>
class Ports:
"""."""
def __init__(self, conf_file, port_details):
"""."""
<|body_0|>
def get_ports_from_conf_to_port_details(self):
"""."""
<|body_1|>
def get_port_details_from_port_details_file(line):
"""."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ports:
"""."""
def __init__(self, conf_file, port_details):
"""."""
try:
self.conf_file = conf_file
self.port_details = port_details
self.ports = []
self.hostname = socket.gethostbyname(socket.gethostname())
except Exception as e:
... | the_stack_v2_python_sparse | scripts_avx/scripts/scripts/Commons/appviewx_firewall_config.py | Poonammahunta/Integration | train | 0 |
b06fb0a67af2b4d00f281074cd37d2b21d85bd6c | [
"super().__init__(data, chunksize, axis, **kwargs)\na = self.kwargs.pop('start', 0)\nb = self.kwargs.pop('stop', self.data.shape[axis])\nself.start, self.stop, _ = slice(a, b).indices(data.shape[axis])\nself.data.close()",
"s = list(self.data.shape)\ns[self.axis] = self.stop - self.start\nreturn tuple(s)",
"sel... | <|body_start_0|>
super().__init__(data, chunksize, axis, **kwargs)
a = self.kwargs.pop('start', 0)
b = self.kwargs.pop('stop', self.data.shape[axis])
self.start, self.stop, _ = slice(a, b).indices(data.shape[axis])
self.data.close()
<|end_body_0|>
<|body_start_1|>
s = li... | A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read method of a file reader instance. Notes: The da... | ReaderProducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read metho... | stack_v2_sparse_classes_36k_train_017024 | 17,903 | permissive | [
{
"docstring": "Initialize this Producer with a closed 'data' Reader instance.",
"name": "__init__",
"signature": "def __init__(self, data, chunksize, axis, **kwargs)"
},
{
"docstring": "Return the summed shape of all arrays in this Reader.",
"name": "shape",
"signature": "def shape(self... | 3 | stack_v2_sparse_classes_30k_train_017469 | Implement the Python class `ReaderProducer` described below.
Class description:
A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops.... | Implement the Python class `ReaderProducer` described below.
Class description:
A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops.... | 09ee87e044c7272754e33636dc2f14932145c903 | <|skeleton|>
class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReaderProducer:
"""A Producer of ndarrays from an openseize file Reader instance. Attrs: Producer Attrs start: The start sample along production axis at which data production begins. stop: The stop sample along production axis at which data production stops. kwargs: Arguments passed to read method of a file r... | the_stack_v2_python_sparse | src/openseize/core/producer.py | mscaudill/openseize | train | 12 |
180b050d381ec9dee7845a74168e0c491adaf5e7 | [
"self.sectionId = sectionId\nself.scopeId = scopeId\nself.cameraId = cameraId\nself.imageRow = imageRow\nself.imageCol = imageCol\nself.stageX = stageX\nself.stageY = stageY\nself.rotation = rotation\nif force_pixelsize:\n pixelsize = 0.1 if pixelsize is None else pixelsize\nself.pixelsize = pixelsize\nself.dist... | <|body_start_0|>
self.sectionId = sectionId
self.scopeId = scopeId
self.cameraId = cameraId
self.imageRow = imageRow
self.imageCol = imageCol
self.stageX = stageX
self.stageY = stageY
self.rotation = rotation
if force_pixelsize:
pixelsi... | Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col layout this was taken imageCol : int column from a row,col layout this was ... | Layout | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Layout:
"""Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col layout this was taken imageCol : int colu... | stack_v2_sparse_classes_36k_train_017025 | 3,715 | permissive | [
{
"docstring": "Initialize Layout Parameters ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col layout this was taken imageCol : int column from a row,col layout this was take... | 3 | stack_v2_sparse_classes_30k_train_013957 | Implement the Python class `Layout` described below.
Class description:
Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col la... | Implement the Python class `Layout` described below.
Class description:
Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col la... | 42b926adf5417f1c3dcca30c5cbd840e36f7fd83 | <|skeleton|>
class Layout:
"""Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col layout this was taken imageCol : int colu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Layout:
"""Layout class to describe acquisition settings Attributes ---------- sectionId : str sectionId this tile was taken from scopeId : str what microscope this came from cameraId : str camera this was taken with imageRow : int what row from a row,col layout this was taken imageCol : int column from a row... | the_stack_v2_python_sparse | renderapi/layout.py | AllenInstitute/render-python | train | 3 |
530891ce0e430c68f51c74ca3a736cbc18339c37 | [
"current_collection_schema_version = feconf.CURRENT_COLLECTION_SCHEMA_VERSION\nfor version_num in range(1, current_collection_schema_version):\n self.assertTrue(hasattr(collection_domain.Collection, '_convert_collection_contents_v%s_dict_to_v%s_dict' % (version_num, version_num + 1)))\nself.assertFalse(hasattr(c... | <|body_start_0|>
current_collection_schema_version = feconf.CURRENT_COLLECTION_SCHEMA_VERSION
for version_num in range(1, current_collection_schema_version):
self.assertTrue(hasattr(collection_domain.Collection, '_convert_collection_contents_v%s_dict_to_v%s_dict' % (version_num, version_num ... | Tests the presence of appropriate schema migration methods in the Collection domain object class. | SchemaMigrationMethodsUnitTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaMigrationMethodsUnitTests:
"""Tests the presence of appropriate schema migration methods in the Collection domain object class."""
def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None:
"""Test that the right collection_contents schema conversion me... | stack_v2_sparse_classes_36k_train_017026 | 48,157 | permissive | [
{
"docstring": "Test that the right collection_contents schema conversion methods exist.",
"name": "test_correct_collection_contents_schema_conversion_methods_exist",
"signature": "def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None"
},
{
"docstring": "Test that th... | 2 | stack_v2_sparse_classes_30k_train_015791 | Implement the Python class `SchemaMigrationMethodsUnitTests` described below.
Class description:
Tests the presence of appropriate schema migration methods in the Collection domain object class.
Method signatures and docstrings:
- def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None: Tes... | Implement the Python class `SchemaMigrationMethodsUnitTests` described below.
Class description:
Tests the presence of appropriate schema migration methods in the Collection domain object class.
Method signatures and docstrings:
- def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None: Tes... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class SchemaMigrationMethodsUnitTests:
"""Tests the presence of appropriate schema migration methods in the Collection domain object class."""
def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None:
"""Test that the right collection_contents schema conversion me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaMigrationMethodsUnitTests:
"""Tests the presence of appropriate schema migration methods in the Collection domain object class."""
def test_correct_collection_contents_schema_conversion_methods_exist(self) -> None:
"""Test that the right collection_contents schema conversion methods exist."... | the_stack_v2_python_sparse | core/domain/collection_domain_test.py | oppia/oppia | train | 6,172 |
6cac0f31537727d617227d04df999bd63cf5b7a7 | [
"satisfied = []\nif restrictions:\n expened_restrictions = map(cls._expand_restriction, restrictions)\n if action:\n filterd_by_action_restrictions = filter(lambda item: item.get('action') == action, expened_restrictions)\n else:\n filterd_by_action_restrictions = expened_restrictions[:]\n ... | <|body_start_0|>
satisfied = []
if restrictions:
expened_restrictions = map(cls._expand_restriction, restrictions)
if action:
filterd_by_action_restrictions = filter(lambda item: item.get('action') == action, expened_restrictions)
else:
... | Mixin with restriction processing functionality | RestrictionBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestrictionBase:
"""Mixin with restriction processing functionality"""
def check_restrictions(cls, models, restrictions, action=None, strict=True):
"""Check if attribute satisfied restrictions :param models: objects which represent models in restrictions :type models: dict :param res... | stack_v2_sparse_classes_36k_train_017027 | 13,635 | permissive | [
{
"docstring": "Check if attribute satisfied restrictions :param models: objects which represent models in restrictions :type models: dict :param restrictions: list of restrictions to check :type restrictions: list :param action: filtering restrictions by action key :type action: string :param strict: disallow ... | 2 | null | Implement the Python class `RestrictionBase` described below.
Class description:
Mixin with restriction processing functionality
Method signatures and docstrings:
- def check_restrictions(cls, models, restrictions, action=None, strict=True): Check if attribute satisfied restrictions :param models: objects which repre... | Implement the Python class `RestrictionBase` described below.
Class description:
Mixin with restriction processing functionality
Method signatures and docstrings:
- def check_restrictions(cls, models, restrictions, action=None, strict=True): Check if attribute satisfied restrictions :param models: objects which repre... | 0e09dce510927f2cc490b898e5fe3f813bd791be | <|skeleton|>
class RestrictionBase:
"""Mixin with restriction processing functionality"""
def check_restrictions(cls, models, restrictions, action=None, strict=True):
"""Check if attribute satisfied restrictions :param models: objects which represent models in restrictions :type models: dict :param res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestrictionBase:
"""Mixin with restriction processing functionality"""
def check_restrictions(cls, models, restrictions, action=None, strict=True):
"""Check if attribute satisfied restrictions :param models: objects which represent models in restrictions :type models: dict :param restrictions: li... | the_stack_v2_python_sparse | nailgun/nailgun/utils/restrictions.py | mba811/fuel-web | train | 1 |
82662211c6a35edc85fbd4c5cb5e1b9f699d9bff | [
"_, accounts = BaseAccount.search()\nif ROLE_ADMIN not in session['user'].roles:\n accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))\nif accounts:\n return self.make_response({'message': None, 'accounts': [x.to_json(is_admin=ROLE_ADMIN in session['user'].roles or False) fo... | <|body_start_0|>
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))
if accounts:
return self.make_response({'message': None, 'accounts': [x.to_json(is_admin=... | AccountList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_0|>
def post(self):
"""Create a new account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
... | stack_v2_sparse_classes_36k_train_017028 | 9,518 | permissive | [
{
"docstring": "List all accounts",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new account",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007098 | Implement the Python class `AccountList` described below.
Class description:
Implement the AccountList class.
Method signatures and docstrings:
- def get(self): List all accounts
- def post(self): Create a new account | Implement the Python class `AccountList` described below.
Class description:
Implement the AccountList class.
Method signatures and docstrings:
- def get(self): List all accounts
- def post(self): Create a new account
<|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_0|>
def post(self):
"""Create a new account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountList:
def get(self):
"""List all accounts"""
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))
if accounts:
return self.make_respon... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/accounts.py | RiotGames/cloud-inquisitor | train | 468 | |
25f92074745d5500df3fe8faba7db564bbae874d | [
"self.__base_url = base_url\nself.__initialized = False\nself.__url_spec = {'%(instance)s': instance_name or ''}",
"if self.__initialized:\n return False\nself.__url_spec['%(type)s'] = message_type\nself.__url_spec['%(hash)s'] = message_digest.hash\nself.__url_spec['%(sizebytes)s'] = str(message_digest.size_by... | <|body_start_0|>
self.__base_url = base_url
self.__initialized = False
self.__url_spec = {'%(instance)s': instance_name or ''}
<|end_body_0|>
<|body_start_1|>
if self.__initialized:
return False
self.__url_spec['%(type)s'] = message_type
self.__url_spec['%(ha... | BrowserURL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserURL:
def __init__(self, base_url, instance_name=None):
"""Begins browser URL helper initialization."""
<|body_0|>
def for_message(self, message_type, message_digest):
"""Completes browser URL initialization for a protobuf message."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_017029 | 10,679 | permissive | [
{
"docstring": "Begins browser URL helper initialization.",
"name": "__init__",
"signature": "def __init__(self, base_url, instance_name=None)"
},
{
"docstring": "Completes browser URL initialization for a protobuf message.",
"name": "for_message",
"signature": "def for_message(self, mes... | 3 | stack_v2_sparse_classes_30k_train_002385 | Implement the Python class `BrowserURL` described below.
Class description:
Implement the BrowserURL class.
Method signatures and docstrings:
- def __init__(self, base_url, instance_name=None): Begins browser URL helper initialization.
- def for_message(self, message_type, message_digest): Completes browser URL initi... | Implement the Python class `BrowserURL` described below.
Class description:
Implement the BrowserURL class.
Method signatures and docstrings:
- def __init__(self, base_url, instance_name=None): Begins browser URL helper initialization.
- def for_message(self, message_type, message_digest): Completes browser URL initi... | f39416d81d55ff8bcfb83a50d6a12541f2884ffc | <|skeleton|>
class BrowserURL:
def __init__(self, base_url, instance_name=None):
"""Begins browser URL helper initialization."""
<|body_0|>
def for_message(self, message_type, message_digest):
"""Completes browser URL initialization for a protobuf message."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserURL:
def __init__(self, base_url, instance_name=None):
"""Begins browser URL helper initialization."""
self.__base_url = base_url
self.__initialized = False
self.__url_spec = {'%(instance)s': instance_name or ''}
def for_message(self, message_type, message_digest):
... | the_stack_v2_python_sparse | buildgrid/utils.py | henryaj/buildgrid | train | 0 | |
e87ad8be03d524a8b0d9653bbe799e93fb8d964d | [
"log.logger.debug('Creating a neural net')\nself.id = str(uuid.uuid4())\nlog.logger.debug('ID: ' + self.id)\nself.layers = list()\nself.layers.append(layer.InputLayer(n_inputs))\nself.layers.append(layer.Layer(n_neurons, n_inputs))\nfor _i in range(2, n_hidden_layers):\n self.layers.append(layer.Layer(n_neurons,... | <|body_start_0|>
log.logger.debug('Creating a neural net')
self.id = str(uuid.uuid4())
log.logger.debug('ID: ' + self.id)
self.layers = list()
self.layers.append(layer.InputLayer(n_inputs))
self.layers.append(layer.Layer(n_neurons, n_inputs))
for _i in range(2, n_... | A neural network. | Net | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net:
"""A neural network."""
def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons):
"""Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @type n_inputs: int @param n_outputs: Numper of outputs. @t... | stack_v2_sparse_classes_36k_train_017030 | 3,562 | no_license | [
{
"docstring": "Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @type n_inputs: int @param n_outputs: Numper of outputs. @type n_outputs: int @param n_neurons: Number of neurons in the hidden layer(s). @type n_neurons: int",
"name":... | 6 | stack_v2_sparse_classes_30k_train_013334 | Implement the Python class `Net` described below.
Class description:
A neural network.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @t... | Implement the Python class `Net` described below.
Class description:
A neural network.
Method signatures and docstrings:
- def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons): Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @t... | 227466e6ae9b0a1adcfd2bd191c746b3e09b8edb | <|skeleton|>
class Net:
"""A neural network."""
def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons):
"""Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @type n_inputs: int @param n_outputs: Numper of outputs. @t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Net:
"""A neural network."""
def __init__(self, n_inputs, n_outputs, n_hidden_layers, n_neurons):
"""Constructor. @param n_hidden_layers: Number of hidden layers. @type n_hidden_layers: int @param n_inputs: Numper of inputs. @type n_inputs: int @param n_outputs: Numper of outputs. @type n_outputs... | the_stack_v2_python_sparse | ANNbug/ann/net.py | deadbok/ANNbug | train | 0 |
02957aa942ccf02dcd094bf65db2c4b32a686072 | [
"def dfs(node):\n if node:\n res.append(node.val)\n dfs(node.left)\n dfs(node.right)\nres = []\ndfs(root)\nreturn ' '.join(map(str, res))",
"vals = deque((int(val) for val in data.split()))\n\ndef build(min_val, max_val):\n if vals and min_val < vals[o] < max_val:\n val = vals.po... | <|body_start_0|>
def dfs(node):
if node:
res.append(node.val)
dfs(node.left)
dfs(node.right)
res = []
dfs(root)
return ' '.join(map(str, res))
<|end_body_0|>
<|body_start_1|>
vals = deque((int(val) for val in data.split... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node):... | stack_v2_sparse_classes_36k_train_017031 | 2,281 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 35bb20951ee746bae6a36067ad0b0edbceb3aff4 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def dfs(node):
if node:
res.append(node.val)
dfs(node.left)
dfs(node.right)
res = []
dfs(root)
return ' '.join(map(str... | the_stack_v2_python_sparse | 2020 October LeetCoding Challenge/09_codec.py | candyer/leetcode | train | 2 | |
08dd77656cb692b79a43a89a11e05b28fd667fc4 | [
"self.events1 = events1\nself.events2 = events2\nself.fields_to_compare = {}\nself.match_field = match_field\nfor field_name1, field_name2 in list(fields_to_compare.items()):\n try:\n _ = self.get_subfield(self.events1[0], field_name1)\n _ = self.get_subfield(self.events2[0], field_name2)\n ... | <|body_start_0|>
self.events1 = events1
self.events2 = events2
self.fields_to_compare = {}
self.match_field = match_field
for field_name1, field_name2 in list(fields_to_compare.items()):
try:
_ = self.get_subfield(self.events1[0], field_name1)
... | Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison | StimComparator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StimComparator:
"""Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison"""
def __init__(self, events1, events2, fields_to_compare, exceptions, match_field='mstime'):
""":param events1: :param events2: :param fields_to_compare: ... | stack_v2_sparse_classes_36k_train_017032 | 42,123 | no_license | [
{
"docstring": ":param events1: :param events2: :param fields_to_compare: {'field1.subfield1' -> 'field2.subfield2'} :param exceptions: function that defines okay mismatches :param match_field: which field to match events based upon",
"name": "__init__",
"signature": "def __init__(self, events1, events2... | 4 | stack_v2_sparse_classes_30k_train_012396 | Implement the Python class `StimComparator` described below.
Class description:
Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison
Method signatures and docstrings:
- def __init__(self, events1, events2, fields_to_compare, exceptions, match_field='mstime'): :... | Implement the Python class `StimComparator` described below.
Class description:
Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison
Method signatures and docstrings:
- def __init__(self, events1, events2, fields_to_compare, exceptions, match_field='mstime'): :... | 0c457fdf95416c3256bd01dea9dcae62ccb7d4dc | <|skeleton|>
class StimComparator:
"""Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison"""
def __init__(self, events1, events2, fields_to_compare, exceptions, match_field='mstime'):
""":param events1: :param events2: :param fields_to_compare: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StimComparator:
"""Similar to EventComparator, but specifically for stimulation events, as it requires field/subfield comparison"""
def __init__(self, events1, events2, fields_to_compare, exceptions, match_field='mstime'):
""":param events1: :param events2: :param fields_to_compare: {'field1.subf... | the_stack_v2_python_sparse | event_creation/submission/parsers/base_log_parser.py | pennmem/event_creation | train | 5 |
952c47525b3cb8ed2d97ec70f31695ae0a766477 | [
"seed(datetime.now())\nheight = randint(HEIGHT[0], HEIGHT[1])\nscratch = AVLHandler.from_scratch(height, POINT_CAP)\nstate = scratch.get_gamestate()\nhandler = AVLHandler.from_graph(state)\nreturn handler",
"successes = 0\nfailures = 0\niterations = NUM_CALLS\nfor _ in range(iterations):\n handler = self.new_h... | <|body_start_0|>
seed(datetime.now())
height = randint(HEIGHT[0], HEIGHT[1])
scratch = AVLHandler.from_scratch(height, POINT_CAP)
state = scratch.get_gamestate()
handler = AVLHandler.from_graph(state)
return handler
<|end_body_0|>
<|body_start_1|>
successes = 0
... | Test the state of the AVL tree upon generation from deserialization | AVLOldGeneration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AVLOldGeneration:
"""Test the state of the AVL tree upon generation from deserialization"""
def new_handler():
"""create new handler to test"""
<|body_0|>
def test_golden_old(self):
"""make sure new avl is generated with correct golden node"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017033 | 20,558 | permissive | [
{
"docstring": "create new handler to test",
"name": "new_handler",
"signature": "def new_handler()"
},
{
"docstring": "make sure new avl is generated with correct golden node",
"name": "test_golden_old",
"signature": "def test_golden_old(self)"
},
{
"docstring": "make sure nodes... | 4 | stack_v2_sparse_classes_30k_train_012531 | Implement the Python class `AVLOldGeneration` described below.
Class description:
Test the state of the AVL tree upon generation from deserialization
Method signatures and docstrings:
- def new_handler(): create new handler to test
- def test_golden_old(self): make sure new avl is generated with correct golden node
-... | Implement the Python class `AVLOldGeneration` described below.
Class description:
Test the state of the AVL tree upon generation from deserialization
Method signatures and docstrings:
- def new_handler(): create new handler to test
- def test_golden_old(self): make sure new avl is generated with correct golden node
-... | a47c849ea97763eff1005273a58aa3d8ab663ff2 | <|skeleton|>
class AVLOldGeneration:
"""Test the state of the AVL tree upon generation from deserialization"""
def new_handler():
"""create new handler to test"""
<|body_0|>
def test_golden_old(self):
"""make sure new avl is generated with correct golden node"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AVLOldGeneration:
"""Test the state of the AVL tree upon generation from deserialization"""
def new_handler():
"""create new handler to test"""
seed(datetime.now())
height = randint(HEIGHT[0], HEIGHT[1])
scratch = AVLHandler.from_scratch(height, POINT_CAP)
state = ... | the_stack_v2_python_sparse | game_board/avl/test_avl.py | Plongesam/data-structures-game | train | 2 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"params = init_perfect_foresight.copy()\nparams.update(kwds)\nIndShockConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)\nself.solve_one_period = make_one_period_oo_solver(ConsPerfForesightLabeledSolver)",
"u = UtilityFuncCRRA(self.CRRA)\nmNrm = xr.DataArray(np.append(0.0, self.aXtraGrid), name='... | <|body_start_0|>
params = init_perfect_foresight.copy()
params.update(kwds)
IndShockConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)
self.solve_one_period = make_one_period_oo_solver(ConsPerfForesightLabeledSolver)
<|end_body_0|>
<|body_start_1|>
u = UtilityFu... | A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so the only state variable is market resources m. | PerfForesightLabeledType | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerfForesightLabeledType:
"""A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so the only state variable is market resour... | stack_v2_sparse_classes_36k_train_017034 | 40,507 | permissive | [
{
"docstring": "Initialize a new instance of a perfect foresight consumer type.",
"name": "__init__",
"signature": "def __init__(self, verbose=1, quiet=False, **kwds)"
},
{
"docstring": "Update the terminal solution of the model by creating a terminal value function and terminal marginal value f... | 2 | stack_v2_sparse_classes_30k_train_017628 | Implement the Python class `PerfForesightLabeledType` described below.
Class description:
A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so t... | Implement the Python class `PerfForesightLabeledType` described below.
Class description:
A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so t... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class PerfForesightLabeledType:
"""A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so the only state variable is market resour... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerfForesightLabeledType:
"""A labeled perfect foresight consumer type. This class is a subclass of IndShockConsumerType, and inherits all of its methods and attributes. Perfect foresight consumers have no uncertainty about income or interest rates, and so the only state variable is market resources m."""
... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
183e6b3e8f7c23efd6e6e6360ee7095e191b6462 | [
"class ClassMethodTest(NSObject):\n\n def clsMeth(self):\n return 'hello'\n clsMeth = classmethod(clsMeth)\nself.assertIsInstance(ClassMethodTest.clsMeth, objc.selector)\nself.assertTrue(ClassMethodTest.clsMeth.isClassMethod)",
"class StaticMethodTest(NSObject):\n\n def stMeth(self):\n retu... | <|body_start_0|>
class ClassMethodTest(NSObject):
def clsMeth(self):
return 'hello'
clsMeth = classmethod(clsMeth)
self.assertIsInstance(ClassMethodTest.clsMeth, objc.selector)
self.assertTrue(ClassMethodTest.clsMeth.isClassMethod)
<|end_body_0|>
<|body_... | TestClassMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestClassMethods:
def testClassMethod(self):
"""check that classmethod()-s are converted to selectors"""
<|body_0|>
def testStaticMethod(self):
"""check that staticmethod()-s are not converted to selectors"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017035 | 36,093 | permissive | [
{
"docstring": "check that classmethod()-s are converted to selectors",
"name": "testClassMethod",
"signature": "def testClassMethod(self)"
},
{
"docstring": "check that staticmethod()-s are not converted to selectors",
"name": "testStaticMethod",
"signature": "def testStaticMethod(self)... | 2 | stack_v2_sparse_classes_30k_train_008717 | Implement the Python class `TestClassMethods` described below.
Class description:
Implement the TestClassMethods class.
Method signatures and docstrings:
- def testClassMethod(self): check that classmethod()-s are converted to selectors
- def testStaticMethod(self): check that staticmethod()-s are not converted to se... | Implement the Python class `TestClassMethods` described below.
Class description:
Implement the TestClassMethods class.
Method signatures and docstrings:
- def testClassMethod(self): check that classmethod()-s are converted to selectors
- def testStaticMethod(self): check that staticmethod()-s are not converted to se... | 77b98382e52818690449111cd2e23cd469b53cf5 | <|skeleton|>
class TestClassMethods:
def testClassMethod(self):
"""check that classmethod()-s are converted to selectors"""
<|body_0|>
def testStaticMethod(self):
"""check that staticmethod()-s are not converted to selectors"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestClassMethods:
def testClassMethod(self):
"""check that classmethod()-s are converted to selectors"""
class ClassMethodTest(NSObject):
def clsMeth(self):
return 'hello'
clsMeth = classmethod(clsMeth)
self.assertIsInstance(ClassMethodTest.clsM... | the_stack_v2_python_sparse | pyobjc-core/PyObjCTest/test_subclass.py | ronaldoussoren/pyobjc | train | 439 | |
368a42a32ba3f66099a941172b7a9f92033867cd | [
"RAMSTKBook.__init__(self, controller)\nself.dic_list_view = {'revision': [lvwUsageProfile(controller), lvwFailureDefinition(controller)], 'function': [FunctionHardware(controller, matrix_type='fnctn_hrdwr')], 'requirement': [lvwStakeholder(controller), RequirementHardware(controller, matrix_type='rqrmnt_hrdwr'), R... | <|body_start_0|>
RAMSTKBook.__init__(self, controller)
self.dic_list_view = {'revision': [lvwUsageProfile(controller), lvwFailureDefinition(controller)], 'function': [FunctionHardware(controller, matrix_type='fnctn_hrdwr')], 'requirement': [lvwStakeholder(controller), RequirementHardware(controller, mat... | This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: :ivar dict dic_list_view: dictionary containing the List Views and/or Matri... | ListBook | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListBook:
"""This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: :ivar dict dic_list_view: dictionary co... | stack_v2_sparse_classes_36k_train_017036 | 5,882 | permissive | [
{
"docstring": "Initialize an instance of the RAMSTK List View class. :param controller: the RAMSTK master data controller. :type controller: :class:`ramstk.RAMSTK.RAMSTK`",
"name": "__init__",
"signature": "def __init__(self, controller)"
},
{
"docstring": "Update the Modules Views when a RAMST... | 4 | null | Implement the Python class `ListBook` described below.
Class description:
This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: ... | Implement the Python class `ListBook` described below.
Class description:
This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: ... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class ListBook:
"""This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: :ivar dict dic_list_view: dictionary co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListBook:
"""This is the List Book class for the pyGTK multiple window interface. The List Book provides the container for any List Views and Matrix Views associated with the RAMSTK module selected in the RAMSTK Module View. Attributes of the List Book are: :ivar dict dic_list_view: dictionary containing the ... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/mwi/ListBook.py | JmiXIII/ramstk | train | 0 |
273b73b50418fda6cc180a51f1ccb5df5eab6504 | [
"data = np.genfromtxt(datafile)\nfor key in self.mapped_quantities:\n self.raw_mapping[key] = data[:, coldict[key]]\nself.n_sources = data.shape[0]",
"for key in self.mapped_quantities:\n if key in datadict:\n self.raw_mapping[key] = datadict[key]\n else:\n Exception(f'Mapped property {key}... | <|body_start_0|>
data = np.genfromtxt(datafile)
for key in self.mapped_quantities:
self.raw_mapping[key] = data[:, coldict[key]]
self.n_sources = data.shape[0]
<|end_body_0|>
<|body_start_1|>
for key in self.mapped_quantities:
if key in datadict:
... | Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter. | Events | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
"""Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter."""
def fromfile(self, datafile, coldict):
"""Take input data from ASCII file Args: d... | stack_v2_sparse_classes_36k_train_017037 | 11,231 | permissive | [
{
"docstring": "Take input data from ASCII file Args: datafile (:obj:`str`): path to input data file coldict (:obj:`dict`): keys are self.mapped_values, with entries integer indexes for their corresponding column.",
"name": "fromfile",
"signature": "def fromfile(self, datafile, coldict)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_004804 | Implement the Python class `Events` described below.
Class description:
Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter.
Method signatures and docstrings:
- def fromfile(self, da... | Implement the Python class `Events` described below.
Class description:
Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter.
Method signatures and docstrings:
- def fromfile(self, da... | 74607ea7c33715d79e5675f6f75a2beb11bf6a7d | <|skeleton|>
class Events:
"""Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter."""
def fromfile(self, datafile, coldict):
"""Take input data from ASCII file Args: d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Events:
"""Represent data as time-discrete events. Child class of `Source`, for `Event`-type sources. Each `Event` is discrete in `time` with single data values mapped to each sonification parameter."""
def fromfile(self, datafile, coldict):
"""Take input data from ASCII file Args: datafile (:obj... | the_stack_v2_python_sparse | src/strauss/sources.py | james-trayford/strauss | train | 24 |
d432a1148166f85b515f6f23ff9a0c1bc4becf0f | [
"for event in self:\n if event.active and event.interval:\n event.next_call = datetime.now() + timedelta(hours=event.interval)\n else:\n event.next_call = False",
"next_call = str2dt(cycle.create_date) + timedelta(hours=self.interval)\nif self.interval <= 0:\n times_to_raise = -1\nelse:\n ... | <|body_start_0|>
for event in self:
if event.active and event.interval:
event.next_call = datetime.now() + timedelta(hours=event.interval)
else:
event.next_call = False
<|end_body_0|>
<|body_start_1|>
next_call = str2dt(cycle.create_date) + timede... | BasicEvent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicEvent:
def get_next_call(self):
"""Compute the next evaluation date."""
<|body_0|>
def update_event(self, value, cycle):
"""Update the fields next call, state and action for an event. When an event is evaluated is necessary to update its values."""
<|bod... | stack_v2_sparse_classes_36k_train_017038 | 9,828 | no_license | [
{
"docstring": "Compute the next evaluation date.",
"name": "get_next_call",
"signature": "def get_next_call(self)"
},
{
"docstring": "Update the fields next call, state and action for an event. When an event is evaluated is necessary to update its values.",
"name": "update_event",
"sign... | 3 | stack_v2_sparse_classes_30k_test_000010 | Implement the Python class `BasicEvent` described below.
Class description:
Implement the BasicEvent class.
Method signatures and docstrings:
- def get_next_call(self): Compute the next evaluation date.
- def update_event(self, value, cycle): Update the fields next call, state and action for an event. When an event i... | Implement the Python class `BasicEvent` described below.
Class description:
Implement the BasicEvent class.
Method signatures and docstrings:
- def get_next_call(self): Compute the next evaluation date.
- def update_event(self, value, cycle): Update the fields next call, state and action for an event. When an event i... | 8af5b65d3759721813afa8360876899f79ce51f8 | <|skeleton|>
class BasicEvent:
def get_next_call(self):
"""Compute the next evaluation date."""
<|body_0|>
def update_event(self, value, cycle):
"""Update the fields next call, state and action for an event. When an event is evaluated is necessary to update its values."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicEvent:
def get_next_call(self):
"""Compute the next evaluation date."""
for event in self:
if event.active and event.interval:
event.next_call = datetime.now() + timedelta(hours=event.interval)
else:
event.next_call = False
def ... | the_stack_v2_python_sparse | xopgi/xopgi_cdr/system_event.py | merchise/xopgi.base | train | 0 | |
dfc41e846b29df10336f25a683ef32085b1e83bf | [
"serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nSprinkleSchedule.objects.update_or_create(device=serializer.validated_data['device'], defaults=serializer.validated_data)\nreturn JsonResponse(serializer.data, status=status.HTTP_201_CREATED)",
"try:\n schedule = S... | <|body_start_0|>
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
SprinkleSchedule.objects.update_or_create(device=serializer.validated_data['device'], defaults=serializer.validated_data)
return JsonResponse(serializer.data, status=status.HTTP... | Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific. | ScheduleViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_017039 | 2,458 | no_license | [
{
"docstring": "Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation.",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Get the current scheduled sprinkle configuration. <br /> If the device does not have any configurat... | 3 | stack_v2_sparse_classes_30k_train_013311 | Implement the Python class `ScheduleViewSet` described below.
Class description:
Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Set the sprinkle schedule for one device <br /> This is an... | Implement the Python class `ScheduleViewSet` described below.
Class description:
Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Set the sprinkle schedule for one device <br /> This is an... | 58ac6554ee92f94130900d49b7d55dd30eabf9ab | <|skeleton|>
class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleViewSet:
"""Scheduled Sprinkles of a device. <b>Note</b>: This endpoint is particularly non-RESTfull specific."""
def create(self, request, *args, **kwargs):
"""Set the sprinkle schedule for one device <br /> This is an <i>upsert</i> operation."""
serializer = self.get_serializer(... | the_stack_v2_python_sparse | aquas_web/devices/views/api/schedule.py | jaconsta/aquas_web | train | 0 |
c1cc06d2e5d4a380e210558fc97d6bfc6b47958d | [
"if name.lower() in dataset2target_lists.keys():\n if label_name is None:\n raise ValueError(\"Please select a label name. You can use tdc.utils.retrieve_label_name_list('\" + name.lower() + \"') to retrieve all available label names.\")\nentity1, y, entity1_idx = property_dataset_load(name, path, label_n... | <|body_start_0|>
if name.lower() in dataset2target_lists.keys():
if label_name is None:
raise ValueError("Please select a label name. You can use tdc.utils.retrieve_label_name_list('" + name.lower() + "') to retrieve all available label names.")
entity1, y, entity1_idx = prop... | A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dataset_names (list): A list of dataset names available for a task convert_forma... | DataLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLoader:
"""A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dataset_names (list): A list of dataset na... | stack_v2_sparse_classes_36k_train_017040 | 5,348 | permissive | [
{
"docstring": "Create a base dataloader object that each single instance prediction task dataloader class can inherit from. Raises: ValueError: for a dataset with multiple labels, specify the label. Use tdc.utils.retrieve_label_name_list to see the available label names",
"name": "__init__",
"signature... | 4 | stack_v2_sparse_classes_30k_train_004824 | Implement the Python class `DataLoader` described below.
Class description:
A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dat... | Implement the Python class `DataLoader` described below.
Class description:
A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dat... | ea7b3270b0b37cec012ac0f9dbc1e92e14212f52 | <|skeleton|>
class DataLoader:
"""A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dataset_names (list): A list of dataset na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataLoader:
"""A base data loader class. Args: name (str): the dataset name. path (str): The path to save the data file label_name (str): For multi-label dataset, specify the label name print_stats (bool): Whether to print basic statistics of the dataset dataset_names (list): A list of dataset names available... | the_stack_v2_python_sparse | tdc/single_pred/single_pred_dataset.py | samsledje/TDC | train | 0 |
0a7bb81c88338d5bcebdb82e6c6931febb20808c | [
"super().__init__()\nself._use_condition = use_condition\nself._model = tf.keras.Sequential([tf.keras.layers.Dense(7 * 7 * 256, use_bias=False), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), tf.keras.layers.Reshape([7, 7, 256]), tf.keras.layers.Conv2DTranspose(128, [5, 5], padding='same', use_bias=F... | <|body_start_0|>
super().__init__()
self._use_condition = use_condition
self._model = tf.keras.Sequential([tf.keras.layers.Dense(7 * 7 * 256, use_bias=False), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), tf.keras.layers.Reshape([7, 7, 256]), tf.keras.layers.Conv2DTranspose(128, ... | Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: | ClassConditionedDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassConditionedDecoder:
"""Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model:"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
<|body_0|>
def call(self, noise, embeddi... | stack_v2_sparse_classes_36k_train_017041 | 10,560 | no_license | [
{
"docstring": "Initializes the object. Args: use_condition:",
"name": "__init__",
"signature": "def __init__(self, use_condition)"
},
{
"docstring": "Applies the model to the inputs. Args: noise: embedding: Returns:",
"name": "call",
"signature": "def call(self, noise, embedding)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017482 | Implement the Python class `ClassConditionedDecoder` described below.
Class description:
Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model:
Method signatures and docstrings:
- def __init__(self, use_condition): Initializes the object. Args: use_condition:... | Implement the Python class `ClassConditionedDecoder` described below.
Class description:
Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model:
Method signatures and docstrings:
- def __init__(self, use_condition): Initializes the object. Args: use_condition:... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class ClassConditionedDecoder:
"""Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model:"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
<|body_0|>
def call(self, noise, embeddi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassConditionedDecoder:
"""Class conditioned decoder. This decoder is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model:"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
super().__init__()
self._use_condition = use_condi... | the_stack_v2_python_sparse | vae.py | gaotianxiang/text-to-image-synthesis | train | 0 |
4296d056f7de9811e0db06b63b3d5b80d3c7e8d6 | [
"print('Inside __init__()')\nself.arg1 = arg1\nself.arg2 = arg2\nself.arg3 = arg3",
"print('Inside __call__()')\n\ndef wrapped_f(*args):\n print('Inside wrapped_f()')\n print('Decorator arguments:', self.arg1, self.arg2, self.arg3)\n f(*args)\n print('After f(*args)')\nreturn wrapped_f"
] | <|body_start_0|>
print('Inside __init__()')
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
<|end_body_0|>
<|body_start_1|>
print('Inside __call__()')
def wrapped_f(*args):
print('Inside wrapped_f()')
print('Decorator arguments:', self.arg1, s... | decorator_with_arguments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class decorator_with_arguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator arguments, __call__() is only called onc... | stack_v2_sparse_classes_36k_train_017042 | 2,326 | no_license | [
{
"docstring": "If there are decorator arguments, the function to be decorated is not passed to the constructor!",
"name": "__init__",
"signature": "def __init__(self, arg1, arg2, arg3)"
},
{
"docstring": "If there are decorator arguments, __call__() is only called once, as part of the decoratio... | 2 | stack_v2_sparse_classes_30k_train_017781 | Implement the Python class `decorator_with_arguments` described below.
Class description:
Implement the decorator_with_arguments class.
Method signatures and docstrings:
- def __init__(self, arg1, arg2, arg3): If there are decorator arguments, the function to be decorated is not passed to the constructor!
- def __cal... | Implement the Python class `decorator_with_arguments` described below.
Class description:
Implement the decorator_with_arguments class.
Method signatures and docstrings:
- def __init__(self, arg1, arg2, arg3): If there are decorator arguments, the function to be decorated is not passed to the constructor!
- def __cal... | 73496b820ad0c7236022873144468a6ff325d114 | <|skeleton|>
class decorator_with_arguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator arguments, __call__() is only called onc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class decorator_with_arguments:
def __init__(self, arg1, arg2, arg3):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
print('Inside __init__()')
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def __call__(self, f... | the_stack_v2_python_sparse | Decorator/decoratingFunc/decorator_with_arguments.py | kitianFresh/flask-study | train | 1 | |
a517c275124d88153efbcb7f91030161519aae0e | [
"x_headers = 'x-ms-date:' + date\nstring_to_hash = method + '\\n' + str(content_length) + '\\n' + content_type + '\\n' + x_headers + '\\n' + resource\nbytes_to_hash = bytes(string_to_hash, encoding='utf-8')\ndecoded_key = base64.b64decode(shared_key)\nencoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_h... | <|body_start_0|>
x_headers = 'x-ms-date:' + date
string_to_hash = method + '\n' + str(content_length) + '\n' + content_type + '\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash, encoding='utf-8')
decoded_key = base64.b64decode(shared_key)
encoded_hash = base6... | AzureSentinel is Used to post data to log analytics. | AzureSentinel | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
<|body_0|>
def post_data(self, customer_id, body, log_type):
"""Build and send... | stack_v2_sparse_classes_36k_train_017043 | 7,907 | permissive | [
{
"docstring": "To build the signature.",
"name": "build_signature",
"signature": "def build_signature(self, date, content_length, method, content_type, resource)"
},
{
"docstring": "Build and send a request to the POST API.",
"name": "post_data",
"signature": "def post_data(self, custom... | 2 | null | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel is Used to post data to log analytics.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build the signature.
- def post_data(self, customer_id, body, log_... | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel is Used to post data to log analytics.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build the signature.
- def post_data(self, customer_id, body, log_... | 4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
<|body_0|>
def post_data(self, customer_id, body, log_type):
"""Build and send... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
x_headers = 'x-ms-date:' + date
string_to_hash = method + '\n' + str(content_length) + '\n' + co... | the_stack_v2_python_sparse | Solutions/SecurityScorecard Cybersecurity Ratings/Data Connectors/SecurityScorecardIssue/SecurityScorecardIssueSentinelConnector/writers.py | Azure/Azure-Sentinel | train | 3,697 |
d46295ee89cd8f36f310ab44c71850d1fe2b696f | [
"num_frames = tf.shape(tensor)[0]\nnum_crop_points = tf.cast(tf.math.ceil(num_frames / self.length), tf.int32)\ncrop_point = tf.random.stateless_uniform(shape=(), minval=0, maxval=num_crop_points, dtype=tf.int32, seed=seed)\ncrop_point *= self.length\nframes_sample = tensor[crop_point:crop_point + self.length]\nfra... | <|body_start_0|>
num_frames = tf.shape(tensor)[0]
num_crop_points = tf.cast(tf.math.ceil(num_frames / self.length), tf.int32)
crop_point = tf.random.stateless_uniform(shape=(), minval=0, maxval=num_crop_points, dtype=tf.int32, seed=seed)
crop_point *= self.length
frames_sample = ... | Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all possible slices of `length` frames from the video. For the following video and `length=3`: [1, 2,... | TemporalRandomStridedWindow | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalRandomStridedWindow:
"""Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all possible slices of `length` frames from th... | stack_v2_sparse_classes_36k_train_017044 | 45,414 | permissive | [
{
"docstring": "Applies the strided crop operation to the video tensor.",
"name": "_apply",
"signature": "def _apply(self, tensor, seed, constant_values)"
},
{
"docstring": "See base class.",
"name": "apply",
"signature": "def apply(self, tensor, seed, key=None, video_shape=None)"
}
] | 2 | null | Implement the Python class `TemporalRandomStridedWindow` described below.
Class description:
Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all pos... | Implement the Python class `TemporalRandomStridedWindow` described below.
Class description:
Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all pos... | c1ae273841592fce4c993bf35cdd0a6424e73da4 | <|skeleton|>
class TemporalRandomStridedWindow:
"""Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all possible slices of `length` frames from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemporalRandomStridedWindow:
"""Gets a random strided slice (window) along 0-th axis of input tensor. This op is like TemporalRandomWindow but it samples from one of a set of strides of the video, whereas TemporalRandomWindow will densely sample from all possible slices of `length` frames from the video. For ... | the_stack_v2_python_sparse | invariant_slot_attention/lib/preprocessing.py | ishine/google-research | train | 0 |
2d4314a8933a5209e1cedf29df40d4e6c4f098a5 | [
"id_asignacion = request.data['id_asignacion']\ndata = request.data['data']\nasignacion_ii = inv_m.InventarioInterno.objects.get(id=id_asignacion)\nif asignacion_ii:\n try:\n usuario = User.objects.get(id=data)\n asignacion_ii.colaborador_asignado = usuario\n asignacion_ii.creada_por = reque... | <|body_start_0|>
id_asignacion = request.data['id_asignacion']
data = request.data['data']
asignacion_ii = inv_m.InventarioInterno.objects.get(id=id_asignacion)
if asignacion_ii:
try:
usuario = User.objects.get(id=data)
asignacion_ii.colaborado... | ViewSet para generar informe de la :class 'InventarioInterno' | InventarioInternoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventarioInternoViewSet:
"""ViewSet para generar informe de la :class 'InventarioInterno'"""
def reasignar_registro(self, request, pk=None):
"""Método para reasignar una salida de inventario interno"""
<|body_0|>
def entregar_asignacion(self, request, pk=None):
... | stack_v2_sparse_classes_36k_train_017045 | 10,585 | no_license | [
{
"docstring": "Método para reasignar una salida de inventario interno",
"name": "reasignar_registro",
"signature": "def reasignar_registro(self, request, pk=None)"
},
{
"docstring": "Método para finalizar la asignación de inventario interno",
"name": "entregar_asignacion",
"signature": ... | 3 | null | Implement the Python class `InventarioInternoViewSet` described below.
Class description:
ViewSet para generar informe de la :class 'InventarioInterno'
Method signatures and docstrings:
- def reasignar_registro(self, request, pk=None): Método para reasignar una salida de inventario interno
- def entregar_asignacion(s... | Implement the Python class `InventarioInternoViewSet` described below.
Class description:
ViewSet para generar informe de la :class 'InventarioInterno'
Method signatures and docstrings:
- def reasignar_registro(self, request, pk=None): Método para reasignar una salida de inventario interno
- def entregar_asignacion(s... | 0e37786d7173abe820fd10b094ffcc2db9593a9c | <|skeleton|>
class InventarioInternoViewSet:
"""ViewSet para generar informe de la :class 'InventarioInterno'"""
def reasignar_registro(self, request, pk=None):
"""Método para reasignar una salida de inventario interno"""
<|body_0|>
def entregar_asignacion(self, request, pk=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InventarioInternoViewSet:
"""ViewSet para generar informe de la :class 'InventarioInterno'"""
def reasignar_registro(self, request, pk=None):
"""Método para reasignar una salida de inventario interno"""
id_asignacion = request.data['id_asignacion']
data = request.data['data']
... | the_stack_v2_python_sparse | src/apps/inventario/api_views/interno.py | jinchuika/app-suni | train | 7 |
ffcde84ad1fd54b47f8d68485dc5e3ad96043250 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.onenoteOperation'.casefold():\n from .on... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | Operation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Operation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Operation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Operat... | stack_v2_sparse_classes_36k_train_017046 | 3,287 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Operation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `Operation` described below.
Class description:
Implement the Operation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Operation: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `Operation` described below.
Class description:
Implement the Operation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Operation: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Operation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Operation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Operat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Operation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Operation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Operation"""
... | the_stack_v2_python_sparse | msgraph/generated/models/operation.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fee941112eda563154ec9e1ea07d7daf775ca48e | [
"\"\"\"\n string是一种不可变的数据类型\n O(n)的时间复杂度,还有各种类型转换\n \"\"\"\nx_s = list(str(x))\nif len(x_s) <= 1:\n return x\nsign = 1\nif x_s[0] == '-':\n sign = -1\n x_s = x_s[1:]\ni, j = (0, len(x_s) - 1)\nwhile i < j:\n x_s[i], x_s[j] = (x_s[j], x_s[i])\n i += 1\n j -= 1\nresult = sign * ... | <|body_start_0|>
"""
string是一种不可变的数据类型
O(n)的时间复杂度,还有各种类型转换
"""
x_s = list(str(x))
if len(x_s) <= 1:
return x
sign = 1
if x_s[0] == '-':
sign = -1
x_s = x_s[1:]
i, j = (0, len(x_s) - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_2(self, x):
"""rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
string是一种不可变的数据... | stack_v2_sparse_classes_36k_train_017047 | 1,619 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": "rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:",
"name": "reverse_2",
"signature": "def reverse_2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011294 | 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 reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return: | 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 reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:
<|skeleton|>
class Solution:
def r... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_2(self, x):
"""rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
"""
string是一种不可变的数据类型
O(n)的时间复杂度,还有各种类型转换
"""
x_s = list(str(x))
if len(x_s) <= 1:
return x
sign = 1
if x_s[0] == '-':
sign = -... | the_stack_v2_python_sparse | tuter_start/7_int.py | cainingning/leetcode | train | 1 | |
08680a290599d5bf16fbc8958a45ba36ab25dbc2 | [
"self.open_rings = open_rings\nself.opt_steps = opt_steps\nif edges is None:\n self.mol_graph = MoleculeGraph.with_local_env_strategy(molecule, OpenBabelNN(), reorder=False, extend_structure=False)\nelse:\n edges = {(e[0], e[1]): None for e in edges}\n self.mol_graph = MoleculeGraph.with_edges(molecule, ed... | <|body_start_0|>
self.open_rings = open_rings
self.opt_steps = opt_steps
if edges is None:
self.mol_graph = MoleculeGraph.with_local_env_strategy(molecule, OpenBabelNN(), reorder=False, extend_structure=False)
else:
edges = {(e[0], e[1]): None for e in edges}
... | Fragmenter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fragmenter:
def __init__(self, molecule, edges=None, depth=1, open_rings=True, opt_steps=10000):
"""Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule to fragment edges (list): List of index pairs that define graph edges, aka molecule bonds. If not se... | stack_v2_sparse_classes_36k_train_017048 | 8,264 | permissive | [
{
"docstring": "Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule to fragment edges (list): List of index pairs that define graph edges, aka molecule bonds. If not set, edges will be determined with OpenBabel. depth (int): The number of levels of iterative fragmentation to ... | 3 | stack_v2_sparse_classes_30k_train_017228 | Implement the Python class `Fragmenter` described below.
Class description:
Implement the Fragmenter class.
Method signatures and docstrings:
- def __init__(self, molecule, edges=None, depth=1, open_rings=True, opt_steps=10000): Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule t... | Implement the Python class `Fragmenter` described below.
Class description:
Implement the Fragmenter class.
Method signatures and docstrings:
- def __init__(self, molecule, edges=None, depth=1, open_rings=True, opt_steps=10000): Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule t... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class Fragmenter:
def __init__(self, molecule, edges=None, depth=1, open_rings=True, opt_steps=10000):
"""Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule to fragment edges (list): List of index pairs that define graph edges, aka molecule bonds. If not se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fragmenter:
def __init__(self, molecule, edges=None, depth=1, open_rings=True, opt_steps=10000):
"""Standard constructor for molecule fragmentation Args: molecule (Molecule): The molecule to fragment edges (list): List of index pairs that define graph edges, aka molecule bonds. If not set, edges will ... | the_stack_v2_python_sparse | pymatgen/analysis/fragmenter.py | montoyjh/pymatgen | train | 2 | |
32cc433a2b1ee72404159c5ec5552877056db215 | [
"http_client = await http_client_dependency()\nawait pydantic_schema_manager_dependency.initialize(http_client=http_client, registry_url=config.registry_url, models=[UrlIngestKeyV1, LtdUrlIngestV1], suffix=config.subject_suffix, compatibility=config.subject_compatibility)\nawait kafka_producer_dependency.initialize... | <|body_start_0|>
http_client = await http_client_dependency()
await pydantic_schema_manager_dependency.initialize(http_client=http_client, registry_url=config.registry_url, models=[UrlIngestKeyV1, LtdUrlIngestV1], suffix=config.subject_suffix, compatibility=config.subject_compatibility)
await ka... | Holds singletons in the context of a Ook process, which might be a API server or a CLI command. | ProcessContext | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessContext:
"""Holds singletons in the context of a Ook process, which might be a API server or a CLI command."""
async def create(cls) -> ProcessContext:
"""Create a ProcessContext."""
<|body_0|>
async def aclose(self) -> None:
"""Clean up a process context.... | stack_v2_sparse_classes_36k_train_017049 | 8,220 | permissive | [
{
"docstring": "Create a ProcessContext.",
"name": "create",
"signature": "async def create(cls) -> ProcessContext"
},
{
"docstring": "Clean up a process context. Called during shutdown, or before recreating the process context using a different configuration.",
"name": "aclose",
"signat... | 2 | stack_v2_sparse_classes_30k_train_020010 | Implement the Python class `ProcessContext` described below.
Class description:
Holds singletons in the context of a Ook process, which might be a API server or a CLI command.
Method signatures and docstrings:
- async def create(cls) -> ProcessContext: Create a ProcessContext.
- async def aclose(self) -> None: Clean ... | Implement the Python class `ProcessContext` described below.
Class description:
Holds singletons in the context of a Ook process, which might be a API server or a CLI command.
Method signatures and docstrings:
- async def create(cls) -> ProcessContext: Create a ProcessContext.
- async def aclose(self) -> None: Clean ... | 39b76d8495159426df2f54e51dd56474ed5b8e98 | <|skeleton|>
class ProcessContext:
"""Holds singletons in the context of a Ook process, which might be a API server or a CLI command."""
async def create(cls) -> ProcessContext:
"""Create a ProcessContext."""
<|body_0|>
async def aclose(self) -> None:
"""Clean up a process context.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessContext:
"""Holds singletons in the context of a Ook process, which might be a API server or a CLI command."""
async def create(cls) -> ProcessContext:
"""Create a ProcessContext."""
http_client = await http_client_dependency()
await pydantic_schema_manager_dependency.initi... | the_stack_v2_python_sparse | src/ook/factory.py | lsst-sqre/ook | train | 1 |
493dec1c31ec298c00c77ebc95713a1444c2314f | [
"if request.COOKIES.get('site_language'):\n if request.COOKIES['site_language'] == '':\n language = 'fr'\n else:\n language = request.COOKIES['site_language']\n translation.activate(language)\n request.LANGUAGE_CODE = translation.get_language()",
"if not request.COOKIES.get('site_languag... | <|body_start_0|>
if request.COOKIES.get('site_language'):
if request.COOKIES['site_language'] == '':
language = 'fr'
else:
language = request.COOKIES['site_language']
translation.activate(language)
request.LANGUAGE_CODE = translatio... | LanguageCookieMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
<|body_0|>
def process_response(self, request, response):
"""Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/130312... | stack_v2_sparse_classes_36k_train_017050 | 1,353 | no_license | [
{
"docstring": "Sets language from the cookie value.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/13031239/388835 )",
"name": "process_response"... | 2 | stack_v2_sparse_classes_30k_train_000573 | Implement the Python class `LanguageCookieMiddleware` described below.
Class description:
Implement the LanguageCookieMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Sets language from the cookie value.
- def process_response(self, request, response): Create cookie if not the... | Implement the Python class `LanguageCookieMiddleware` described below.
Class description:
Implement the LanguageCookieMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Sets language from the cookie value.
- def process_response(self, request, response): Create cookie if not the... | d5aff19e4557fe1eb9e0765e40337df99d5e1935 | <|skeleton|>
class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
<|body_0|>
def process_response(self, request, response):
"""Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/130312... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
if request.COOKIES.get('site_language'):
if request.COOKIES['site_language'] == '':
language = 'fr'
else:
language = request.COOKIES[... | the_stack_v2_python_sparse | visualexpcode/visualexpcode/middleware/languages/language_cookie.py | mlemaire79/visualexp | train | 0 | |
857353a2daf7e0e0a63695ee984cc0b558519b43 | [
"app_bundle = bundles[-1]\ntry:\n self.import_bundle_modules(app_bundle)[0]\nexcept IndexError:\n routes = self.collect_from_bundle(app_bundle)\nelse:\n try:\n routes = self.get_explicit_routes(app_bundle)\n except AttributeError as e:\n if not app_bundle.is_single_module:\n rai... | <|body_start_0|>
app_bundle = bundles[-1]
try:
self.import_bundle_modules(app_bundle)[0]
except IndexError:
routes = self.collect_from_bundle(app_bundle)
else:
try:
routes = self.get_explicit_routes(app_bundle)
except Attrib... | Registers routes. | RegisterRoutesHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
<|body_0|>
def process_objects(self, app: FlaskUnchained, routes: Iter... | stack_v2_sparse_classes_36k_train_017051 | 6,728 | permissive | [
{
"docstring": "Discover and register routes.",
"name": "run_hook",
"signature": "def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None"
},
{
"docstring": "Organize routes by where they came from, and then register them with the a... | 5 | null | Implement the Python class `RegisterRoutesHook` described below.
Class description:
Registers routes.
Method signatures and docstrings:
- def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None: Discover and register routes.
- def process_objects(self, a... | Implement the Python class `RegisterRoutesHook` described below.
Class description:
Registers routes.
Method signatures and docstrings:
- def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None: Discover and register routes.
- def process_objects(self, a... | a1f1323f63f59760e430001efef43af9b829ebed | <|skeleton|>
class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
<|body_0|>
def process_objects(self, app: FlaskUnchained, routes: Iter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
app_bundle = bundles[-1]
try:
self.import_bundle_modules(app_bundle)... | the_stack_v2_python_sparse | flask_unchained/bundles/controller/hooks/register_routes_hook.py | briancappello/flask-unchained | train | 77 |
ac3dfc77362839832b073d6fe3e68dbf94082328 | [
"self._type = 'integration'\nsuper(IntegrationTestCase, self).__init__(cfg)\nself._logger = logging.getLogger(__name__)\nself._step_check = True",
"if self.test:\n tmp_results = OrderedDict()\n tmp_results['status'] = 'OK' if self._step_status['status'] else 'FAILED'\n tmp_results['details'] = self._step... | <|body_start_0|>
self._type = 'integration'
super(IntegrationTestCase, self).__init__(cfg)
self._logger = logging.getLogger(__name__)
self._step_check = True
<|end_body_0|>
<|body_start_1|>
if self.test:
tmp_results = OrderedDict()
tmp_results['status'] =... | IntegrationTestCase class | IntegrationTestCase | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegrationTestCase:
"""IntegrationTestCase class"""
def __init__(self, cfg):
"""Testcase initialization"""
<|body_0|>
def run_report(self):
"""Report test results"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._type = 'integration'
... | stack_v2_sparse_classes_36k_train_017052 | 1,795 | permissive | [
{
"docstring": "Testcase initialization",
"name": "__init__",
"signature": "def __init__(self, cfg)"
},
{
"docstring": "Report test results",
"name": "run_report",
"signature": "def run_report(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017046 | Implement the Python class `IntegrationTestCase` described below.
Class description:
IntegrationTestCase class
Method signatures and docstrings:
- def __init__(self, cfg): Testcase initialization
- def run_report(self): Report test results | Implement the Python class `IntegrationTestCase` described below.
Class description:
IntegrationTestCase class
Method signatures and docstrings:
- def __init__(self, cfg): Testcase initialization
- def run_report(self): Report test results
<|skeleton|>
class IntegrationTestCase:
"""IntegrationTestCase class"""
... | d5c0a03054f720da2a5ff9eba74feee57fb0296d | <|skeleton|>
class IntegrationTestCase:
"""IntegrationTestCase class"""
def __init__(self, cfg):
"""Testcase initialization"""
<|body_0|>
def run_report(self):
"""Report test results"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntegrationTestCase:
"""IntegrationTestCase class"""
def __init__(self, cfg):
"""Testcase initialization"""
self._type = 'integration'
super(IntegrationTestCase, self).__init__(cfg)
self._logger = logging.getLogger(__name__)
self._step_check = True
def run_rep... | the_stack_v2_python_sparse | testcases/integration.py | shreyagupta30/vineperf | train | 0 |
6806e0d3dcfae4849b8586447c1c77d7c28763f6 | [
"exp_value = True\nobj = Boolean(exp_value)\nself.assertEqual(exp_value, obj.icpw_value)\nexp_value = False\nobj = Boolean(exp_value)\nself.assertEqual(exp_value, obj.icpw_value)",
"for exp_value in [True, False]:\n obj0 = Boolean(exp_value)\n obj1 = Boolean(exp_value)\n self.assertEqual(obj0, obj1)",
... | <|body_start_0|>
exp_value = True
obj = Boolean(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
exp_value = False
obj = Boolean(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
<|end_body_0|>
<|body_start_1|>
for exp_value in [True, False]:
... | BooleanTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooleanTester:
def test_value(self):
"""Test retrieving the value of a Boolean."""
<|body_0|>
def test_eq(self):
"""Test that Boolean's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that Boolean's with different valu... | stack_v2_sparse_classes_36k_train_017053 | 42,194 | permissive | [
{
"docstring": "Test retrieving the value of a Boolean.",
"name": "test_value",
"signature": "def test_value(self)"
},
{
"docstring": "Test that Boolean's with the same value compare equal.",
"name": "test_eq",
"signature": "def test_eq(self)"
},
{
"docstring": "Test that Boolean... | 4 | stack_v2_sparse_classes_30k_train_007994 | Implement the Python class `BooleanTester` described below.
Class description:
Implement the BooleanTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a Boolean.
- def test_eq(self): Test that Boolean's with the same value compare equal.
- def test_ne(self): Test that... | Implement the Python class `BooleanTester` described below.
Class description:
Implement the BooleanTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a Boolean.
- def test_eq(self): Test that Boolean's with the same value compare equal.
- def test_ne(self): Test that... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class BooleanTester:
def test_value(self):
"""Test retrieving the value of a Boolean."""
<|body_0|>
def test_eq(self):
"""Test that Boolean's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that Boolean's with different valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BooleanTester:
def test_value(self):
"""Test retrieving the value of a Boolean."""
exp_value = True
obj = Boolean(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
exp_value = False
obj = Boolean(exp_value)
self.assertEqual(exp_value, obj.icpw_value... | the_stack_v2_python_sparse | icypaw/test_types.py | sandialabs/IcyPaw | train | 0 | |
d5d778e5a37926f9cffd3e47b35bf56621573fe6 | [
"tmp = self.mkdtemp()\nret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('CC', GOANNA_WRAPPER), ('CFLAGS', '--license-server=%s' % GOANNA_LICENSE_SERVER)]))\nif ret != 0:\n self.fail('cmake failed:\\n%s\\n%s' % (stdout, stderr))\nret, stdout, s... | <|body_start_0|>
tmp = self.mkdtemp()
ret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('CC', GOANNA_WRAPPER), ('CFLAGS', '--license-server=%s' % GOANNA_LICENSE_SERVER)]))
if ret != 0:
self.fail('cmake failed:\n%s\n... | TestStaticAnalysis | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
<|body_0|>
def test_clang_static_analyser(self):
"""Run the Clang static analyser on the accelerator."""
<|body_1|... | stack_v2_sparse_classes_36k_train_017054 | 4,207 | permissive | [
{
"docstring": "Test whether the Goanna static analyser can find any problems with the accelerator.",
"name": "test_goanna_compilation",
"signature": "def test_goanna_compilation(self)"
},
{
"docstring": "Run the Clang static analyser on the accelerator.",
"name": "test_clang_static_analyser... | 3 | stack_v2_sparse_classes_30k_train_011855 | Implement the Python class `TestStaticAnalysis` described below.
Class description:
Implement the TestStaticAnalysis class.
Method signatures and docstrings:
- def test_goanna_compilation(self): Test whether the Goanna static analyser can find any problems with the accelerator.
- def test_clang_static_analyser(self):... | Implement the Python class `TestStaticAnalysis` described below.
Class description:
Implement the TestStaticAnalysis class.
Method signatures and docstrings:
- def test_goanna_compilation(self): Test whether the Goanna static analyser can find any problems with the accelerator.
- def test_clang_static_analyser(self):... | 26bae4a3f000afca18bc7cf84a55e54f8fa9e4c2 | <|skeleton|>
class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
<|body_0|>
def test_clang_static_analyser(self):
"""Run the Clang static analyser on the accelerator."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
tmp = self.mkdtemp()
ret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('... | the_stack_v2_python_sparse | tools/camkes/tools/accelerator/teststaticanalysis.py | ifscamkes/staticifs-camkes | train | 0 | |
356865ed511d54a2f02223ad1556d14a0c255e83 | [
"self.path_to_raster = base_raster_file\nself.path_agg_raster = '../tmp/local_raster.tif'\nself.x_size, self.top_left_x_coords, self.top_left_y_coords, self.centroid_x_coords, self.centroid_y_coords, self.bands_data = self._read_raster(self.path_to_raster)\nif lon is not None:\n self.lon, self.lat = (lon, lat)\n... | <|body_start_0|>
self.path_to_raster = base_raster_file
self.path_agg_raster = '../tmp/local_raster.tif'
self.x_size, self.top_left_x_coords, self.top_left_y_coords, self.centroid_x_coords, self.centroid_y_coords, self.bands_data = self._read_raster(self.path_to_raster)
if lon is not Non... | Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords (array): longitudes for the top left corner of each pixel. self.top_left_y_... | BaseLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLayer:
"""Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords (array): longitudes for the top left c... | stack_v2_sparse_classes_36k_train_017055 | 5,866 | permissive | [
{
"docstring": "Args: base_raster_file (str): path to the .tif raster to use. lon (list): list of longitudes of the survey. lat (list): list of latitudes of the survey.",
"name": "__init__",
"signature": "def __init__(self, base_raster_file, lon=None, lat=None)"
},
{
"docstring": "takes lon lat ... | 5 | stack_v2_sparse_classes_30k_val_001154 | Implement the Python class `BaseLayer` described below.
Class description:
Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords... | Implement the Python class `BaseLayer` described below.
Class description:
Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords... | 7f54196ae10e1b3712d4907c9ddd202b56eb3606 | <|skeleton|>
class BaseLayer:
"""Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords (array): longitudes for the top left c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseLayer:
"""Class that handles the geometries and data. We use a raster as input to define the geo-spatial attributes of our data. Attributes: path_to_raster (str): path to existing raster file. x_size (float): size of a pixel in degrees. top_left_x_coords (array): longitudes for the top left corner of each... | the_stack_v2_python_sparse | Src/base_layer.py | alexnwoko/HRM | train | 0 |
a36cfc01a58d687b6dace40ce068b34e2fa88beb | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)",
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTimeInMicrosecon... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if tim... | Shared SQLite parser plugin for Mozilla Firefox cookies database files. | BaseFirefoxCookiePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFirefoxCookiePlugin:
"""Shared SQLite parser plugin for Mozilla Firefox cookies database files."""
def _GetPosixTimeDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a POSIX time (in seconds) date and time value from the row. Args: query_hash (int): hash of the qu... | stack_v2_sparse_classes_36k_train_017056 | 7,809 | permissive | [
{
"docstring": "Retrieves a POSIX time (in seconds) date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if no... | 3 | null | Implement the Python class `BaseFirefoxCookiePlugin` described below.
Class description:
Shared SQLite parser plugin for Mozilla Firefox cookies database files.
Method signatures and docstrings:
- def _GetPosixTimeDateTimeRowValue(self, query_hash, row, value_name): Retrieves a POSIX time (in seconds) date and time v... | Implement the Python class `BaseFirefoxCookiePlugin` described below.
Class description:
Shared SQLite parser plugin for Mozilla Firefox cookies database files.
Method signatures and docstrings:
- def _GetPosixTimeDateTimeRowValue(self, query_hash, row, value_name): Retrieves a POSIX time (in seconds) date and time v... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class BaseFirefoxCookiePlugin:
"""Shared SQLite parser plugin for Mozilla Firefox cookies database files."""
def _GetPosixTimeDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a POSIX time (in seconds) date and time value from the row. Args: query_hash (int): hash of the qu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFirefoxCookiePlugin:
"""Shared SQLite parser plugin for Mozilla Firefox cookies database files."""
def _GetPosixTimeDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a POSIX time (in seconds) date and time value from the row. Args: query_hash (int): hash of the query, that uni... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/firefox_cookies.py | log2timeline/plaso | train | 1,506 |
7b19223f4405f6e23b5a3de48027ec9fb9de5fab | [
"height_len = len(height)\nmax_water = 0\nfor i in range(height_len - 1):\n j = i + 1\n while j < height_len:\n lower_border = height[i] if height[i] < height[j] else height[j]\n water = lower_border * (j - i)\n max_water = max(water, max_water)\n j += 1\nreturn max_water",
"heig... | <|body_start_0|>
height_len = len(height)
max_water = 0
for i in range(height_len - 1):
j = i + 1
while j < height_len:
lower_border = height[i] if height[i] < height[j] else height[j]
water = lower_border * (j - i)
max_wate... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_brute_force(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea_select_only_biggest_TLE(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def maxArea_select_2_pointer(self, height):
... | stack_v2_sparse_classes_36k_train_017057 | 2,556 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_brute_force",
"signature": "def maxArea_brute_force(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_select_only_biggest_TLE",
"signature": "def maxArea_select_only_biggest_TLE(... | 3 | stack_v2_sparse_classes_30k_train_017039 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_brute_force(self, height): :type height: List[int] :rtype: int
- def maxArea_select_only_biggest_TLE(self, height): :type height: List[int] :rtype: int
- def maxArea_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_brute_force(self, height): :type height: List[int] :rtype: int
- def maxArea_select_only_biggest_TLE(self, height): :type height: List[int] :rtype: int
- def maxArea_... | 83e5dea02e99e512d2b34dac05dabebfdb66ef2a | <|skeleton|>
class Solution:
def maxArea_brute_force(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea_select_only_biggest_TLE(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def maxArea_select_2_pointer(self, height):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea_brute_force(self, height):
""":type height: List[int] :rtype: int"""
height_len = len(height)
max_water = 0
for i in range(height_len - 1):
j = i + 1
while j < height_len:
lower_border = height[i] if height[i] < heig... | the_stack_v2_python_sparse | unclassified/11_maxArea.py | wscheng/LeetCode | train | 0 | |
0e691ac7febb18c3510ed79ef05ee2592ef4e926 | [
"super(MultiheadAttention, self).__init__()\nself.num_hidden_k = num_hidden_k\nself.attn_dropout = nn.Dropout(p=0.1)",
"attn = t.bmm(query, key.transpose(1, 2))\nattn = attn / math.sqrt(self.num_hidden_k)\nif gaussian_factor is not None:\n attn = attn - gaussian_factor\nif mask is not None:\n attn = attn.ma... | <|body_start_0|>
super(MultiheadAttention, self).__init__()
self.num_hidden_k = num_hidden_k
self.attn_dropout = nn.Dropout(p=0.1)
<|end_body_0|>
<|body_start_1|>
attn = t.bmm(query, key.transpose(1, 2))
attn = attn / math.sqrt(self.num_hidden_k)
if gaussian_factor is no... | Multihead attention mechanism (dot attention). | MultiheadAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiheadAttention:
"""Multihead attention mechanism (dot attention)."""
def __init__(self, num_hidden_k):
""":param num_hidden_k: dimension of hidden."""
<|body_0|>
def forward(self, key, value, query, mask=None, query_mask=None, gaussian_factor=None):
"""forwar... | stack_v2_sparse_classes_36k_train_017058 | 17,934 | permissive | [
{
"docstring": ":param num_hidden_k: dimension of hidden.",
"name": "__init__",
"signature": "def __init__(self, num_hidden_k)"
},
{
"docstring": "forward.",
"name": "forward",
"signature": "def forward(self, key, value, query, mask=None, query_mask=None, gaussian_factor=None)"
}
] | 2 | null | Implement the Python class `MultiheadAttention` described below.
Class description:
Multihead attention mechanism (dot attention).
Method signatures and docstrings:
- def __init__(self, num_hidden_k): :param num_hidden_k: dimension of hidden.
- def forward(self, key, value, query, mask=None, query_mask=None, gaussian... | Implement the Python class `MultiheadAttention` described below.
Class description:
Multihead attention mechanism (dot attention).
Method signatures and docstrings:
- def __init__(self, num_hidden_k): :param num_hidden_k: dimension of hidden.
- def forward(self, key, value, query, mask=None, query_mask=None, gaussian... | 31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39 | <|skeleton|>
class MultiheadAttention:
"""Multihead attention mechanism (dot attention)."""
def __init__(self, num_hidden_k):
""":param num_hidden_k: dimension of hidden."""
<|body_0|>
def forward(self, key, value, query, mask=None, query_mask=None, gaussian_factor=None):
"""forwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiheadAttention:
"""Multihead attention mechanism (dot attention)."""
def __init__(self, num_hidden_k):
""":param num_hidden_k: dimension of hidden."""
super(MultiheadAttention, self).__init__()
self.num_hidden_k = num_hidden_k
self.attn_dropout = nn.Dropout(p=0.1)
... | the_stack_v2_python_sparse | SVS/model/layers/pretrain_module.py | SJTMusicTeam/SVS_system | train | 85 |
a8322e590a660a091d0338a800267cb5bb1c1795 | [
"unused = []\nonce = []\nmultiple = []\nrecently_changed = []\ntoday = datetime.date.today()\nfor content_item in self.get_query_set().annotate(num_pages=models.Count('page')):\n count = content_item.num_pages\n if count == 0:\n unused.append(content_item)\n elif count == 1:\n once.append(con... | <|body_start_0|>
unused = []
once = []
multiple = []
recently_changed = []
today = datetime.date.today()
for content_item in self.get_query_set().annotate(num_pages=models.Count('page')):
count = content_item.num_pages
if count == 0:
... | ContentItemManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentItemManager:
def get_content_groups(self):
"""Get content groups: - recently changed - unused - used once - used more than once"""
<|body_0|>
def rename_url(self, old_url, new_url):
"""Change the urls in all content pages. Also changes the urls that begin with... | stack_v2_sparse_classes_36k_train_017059 | 3,754 | no_license | [
{
"docstring": "Get content groups: - recently changed - unused - used once - used more than once",
"name": "get_content_groups",
"signature": "def get_content_groups(self)"
},
{
"docstring": "Change the urls in all content pages. Also changes the urls that begin with this url.",
"name": "re... | 2 | stack_v2_sparse_classes_30k_test_000197 | Implement the Python class `ContentItemManager` described below.
Class description:
Implement the ContentItemManager class.
Method signatures and docstrings:
- def get_content_groups(self): Get content groups: - recently changed - unused - used once - used more than once
- def rename_url(self, old_url, new_url): Chan... | Implement the Python class `ContentItemManager` described below.
Class description:
Implement the ContentItemManager class.
Method signatures and docstrings:
- def get_content_groups(self): Get content groups: - recently changed - unused - used once - used more than once
- def rename_url(self, old_url, new_url): Chan... | f05505cbac6d4a679c6616af64a79ae28f538a82 | <|skeleton|>
class ContentItemManager:
def get_content_groups(self):
"""Get content groups: - recently changed - unused - used once - used more than once"""
<|body_0|>
def rename_url(self, old_url, new_url):
"""Change the urls in all content pages. Also changes the urls that begin with... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContentItemManager:
def get_content_groups(self):
"""Get content groups: - recently changed - unused - used once - used more than once"""
unused = []
once = []
multiple = []
recently_changed = []
today = datetime.date.today()
for content_item in self.get... | the_stack_v2_python_sparse | cultureplex/fiber/managers.py | CulturePlex/website | train | 0 | |
cf021c320afb3625e5616fa68622051a3293e6d8 | [
"prev = None\nwhile head:\n nxt = head.next\n head.next = prev\n prev = head\n head = nxt\nreturn prev",
"if not head:\n return head\ndummy = ListNode(None)\ndummy.next = head\nprev = dummy\ntail = prev\nwhile tail.next:\n tail = tail.next\nwhile prev.next != tail:\n cur = prev.next\n prev... | <|body_start_0|>
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
<|end_body_0|>
<|body_start_1|>
if not head:
return head
dummy = ListNode(None)
dummy.next = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList_1(self, head: ListNode) -> ListNode:
"""1. 迭代:prev、head、next 三个指针的依次操作"""
<|body_0|>
def reverseList_2(self, head: ListNode) -> ListNode:
"""2. 迭代:尾插法"""
<|body_1|>
def reverseList_3(self, head: ListNode) -> ListNode:
""... | stack_v2_sparse_classes_36k_train_017060 | 2,572 | no_license | [
{
"docstring": "1. 迭代:prev、head、next 三个指针的依次操作",
"name": "reverseList_1",
"signature": "def reverseList_1(self, head: ListNode) -> ListNode"
},
{
"docstring": "2. 迭代:尾插法",
"name": "reverseList_2",
"signature": "def reverseList_2(self, head: ListNode) -> ListNode"
},
{
"docstring"... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_1(self, head: ListNode) -> ListNode: 1. 迭代:prev、head、next 三个指针的依次操作
- def reverseList_2(self, head: ListNode) -> ListNode: 2. 迭代:尾插法
- def reverseList_3(self, hea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_1(self, head: ListNode) -> ListNode: 1. 迭代:prev、head、next 三个指针的依次操作
- def reverseList_2(self, head: ListNode) -> ListNode: 2. 迭代:尾插法
- def reverseList_3(self, hea... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def reverseList_1(self, head: ListNode) -> ListNode:
"""1. 迭代:prev、head、next 三个指针的依次操作"""
<|body_0|>
def reverseList_2(self, head: ListNode) -> ListNode:
"""2. 迭代:尾插法"""
<|body_1|>
def reverseList_3(self, head: ListNode) -> ListNode:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList_1(self, head: ListNode) -> ListNode:
"""1. 迭代:prev、head、next 三个指针的依次操作"""
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
def reverseList_2(self, head: Lis... | the_stack_v2_python_sparse | .leetcode/206.反转链表.py | xiaoruijiang/algorithm | train | 0 | |
774802594ebff12fd1bd1818c2d74cf7e8c32f7f | [
"if left == right:\n if self.nums[self.new_index(left)] == self.target:\n print(left, self.new_index(left))\n return self.new_index(left)\n print(-1)\n return -1\nmid = left + right >> 1\nif self.nums[self.new_index(mid)] == self.target:\n print(mid, self.new_index(mid))\n return self.n... | <|body_start_0|>
if left == right:
if self.nums[self.new_index(left)] == self.target:
print(left, self.new_index(left))
return self.new_index(left)
print(-1)
return -1
mid = left + right >> 1
if self.nums[self.new_index(mid)] ==... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bin_search(self, left, right):
""":param left: int :param right: int :return: int"""
<|body_0|>
def search(self, nums, target):
""":type nums: list[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l... | stack_v2_sparse_classes_36k_train_017061 | 2,399 | no_license | [
{
"docstring": ":param left: int :param right: int :return: int",
"name": "bin_search",
"signature": "def bin_search(self, left, right)"
},
{
"docstring": ":type nums: list[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018948 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_search(self, left, right): :param left: int :param right: int :return: int
- def search(self, nums, target): :type nums: list[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_search(self, left, right): :param left: int :param right: int :return: int
- def search(self, nums, target): :type nums: list[int] :type target: int :rtype: int
<|skelet... | f8f3b0cdb47ee6bb4bf9bdc7c2a983f4a882d9dd | <|skeleton|>
class Solution:
def bin_search(self, left, right):
""":param left: int :param right: int :return: int"""
<|body_0|>
def search(self, nums, target):
""":type nums: list[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bin_search(self, left, right):
""":param left: int :param right: int :return: int"""
if left == right:
if self.nums[self.new_index(left)] == self.target:
print(left, self.new_index(left))
return self.new_index(left)
print(-1... | the_stack_v2_python_sparse | solutions/033-search-in-rotated-sorted-array/main.py | CallMeNP/leetcode | train | 0 | |
d58c2ceeae1a93b620158b02b44ec9ddfbee8ee1 | [
"self.bin_name = bin_name\nself.fastsimcoal_dir = fastsimcoal_dir\nif fastsimcoal_dir is None:\n for path in os.environ['PATH'].split(os.pathsep):\n if os.path.isfile(os.path.join(path, self.bin_name)):\n self.fastsimcoal_dir = path\n if self.fastsimcoal_dir is None:\n raise IOError('... | <|body_start_0|>
self.bin_name = bin_name
self.fastsimcoal_dir = fastsimcoal_dir
if fastsimcoal_dir is None:
for path in os.environ['PATH'].split(os.pathsep):
if os.path.isfile(os.path.join(path, self.bin_name)):
self.fastsimcoal_dir = path
... | FastSimCoalController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastSimCoalController:
def __init__(self, fastsimcoal_dir=None, bin_name='fsc252'):
"""Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By default the binary should be called fsc252. bin_name specifies a different name for the binary. The initializer che... | stack_v2_sparse_classes_36k_train_017062 | 11,968 | permissive | [
{
"docstring": "Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By default the binary should be called fsc252. bin_name specifies a different name for the binary. The initializer checks for existence and executability of binaries and sets up the command line controller. Fastsi... | 2 | stack_v2_sparse_classes_30k_train_014483 | Implement the Python class `FastSimCoalController` described below.
Class description:
Implement the FastSimCoalController class.
Method signatures and docstrings:
- def __init__(self, fastsimcoal_dir=None, bin_name='fsc252'): Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By defau... | Implement the Python class `FastSimCoalController` described below.
Class description:
Implement the FastSimCoalController class.
Method signatures and docstrings:
- def __init__(self, fastsimcoal_dir=None, bin_name='fsc252'): Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By defau... | 2632aa3484ef64c9539c4885026b705b737f6d1e | <|skeleton|>
class FastSimCoalController:
def __init__(self, fastsimcoal_dir=None, bin_name='fsc252'):
"""Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By default the binary should be called fsc252. bin_name specifies a different name for the binary. The initializer che... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastSimCoalController:
def __init__(self, fastsimcoal_dir=None, bin_name='fsc252'):
"""Initializes the controller. fastsimcoal_dir is the directory where fastsimcoal is. By default the binary should be called fsc252. bin_name specifies a different name for the binary. The initializer checks for existe... | the_stack_v2_python_sparse | resources/usr/local/lib/python2.7/dist-packages/Bio/PopGen/SimCoal/Controller.py | edawson/parliament2 | train | 0 | |
311a75d990d50170b1aa6a228895890966cf193a | [
"if T is None:\n T = len(index)\nout = generate_gbm_paths(S0, mu, sigma, T, len(index), I, seed=seed)[1:]\nif out.shape[1] == 1:\n return pd.Series(out[:, 0], index=index)\ncolumns = pd.RangeIndex(stop=out.shape[1], name='path')\nreturn pd.DataFrame(out, index=index, columns=columns)",
"download_kwargs = se... | <|body_start_0|>
if T is None:
T = len(index)
out = generate_gbm_paths(S0, mu, sigma, T, len(index), I, seed=seed)[1:]
if out.shape[1] == 1:
return pd.Series(out[:, 0], index=index)
columns = pd.RangeIndex(stop=out.shape[1], name='path')
return pd.DataFram... | `SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-05-02 14:14:15.182089+00:00 102.386... | GBMData | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-... | stack_v2_sparse_classes_36k_train_017063 | 30,831 | permissive | [
{
"docstring": "Generate the symbol using `generate_gbm_paths`. Args: symbol (str): Symbol. index (pd.Index): Pandas index. S0 (float): Value at time 0. Does not appear as the first value in the output data. mu (float): Drift, or mean of the percentage change. sigma (float): Standard deviation of the percentage... | 2 | stack_v2_sparse_classes_30k_train_001000 | Implement the Python class `GBMData` described below.
Class description:
`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1... | Implement the Python class `GBMData` described below.
Class description:
`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1... | 0cd596e1be975d4af6379d883090ffb5b7375d08 | <|skeleton|>
class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-05-02 14:14:1... | the_stack_v2_python_sparse | vectorbt/data/custom.py | davidandreoletti/vectorbt | train | 0 |
d6e7cf3c9edf18bd33d7f270bdd6482b06c36740 | [
"if not l1 or not l2:\n return l1 or l2\nif l1.val <= l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2",
"dummy = ListNode(0)\nlast = dummy\nwhile l1 and l2:\n if l1.val <= l2.val:\n last.next = l1\n l1 =... | <|body_start_0|>
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
<|end_body_0|>
<|body_start_1|>
dummy = Li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_v1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
def mergeTwoLists_v0(self, l1, ... | stack_v2_sparse_classes_36k_train_017064 | 3,475 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists_v1",
"signature": "def mergeTwoLists_v1(self... | 3 | stack_v2_sparse_classes_30k_train_013687 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_v1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_v1(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNo... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_v1(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
def mergeTwoLists_v0(self, l1, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = ... | the_stack_v2_python_sparse | python/21_Merge_Two_Sorted_Lists.py | Moby5/myleetcode | train | 2 | |
05b426e3a4ff61e8a83a41dba9babfffd47ee616 | [
"if isinstance(sigma, (float, int)):\n self.sigma = lambda t: sigma\nelif callable(sigma):\n self.sigma = sigma\nif isinstance(beta, (float, int)):\n self.beta = lambda t: beta\nelif callable(beta):\n self.beta = beta\nif isinstance(ds, (float, int)):\n self.ds = lambda t: ds\nelif callable(ds):\n ... | <|body_start_0|>
if isinstance(sigma, (float, int)):
self.sigma = lambda t: sigma
elif callable(sigma):
self.sigma = sigma
if isinstance(beta, (float, int)):
self.beta = lambda t: beta
elif callable(beta):
self.beta = beta
if isinst... | ProblemSIZR | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProblemSIZR:
def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T):
"""nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]"""
<|body_0|>
def __call__(self, u, t):
"""Høyresiden(e) i ODE-systemet"""
<|body_1|... | stack_v2_sparse_classes_36k_train_017065 | 3,967 | no_license | [
{
"docstring": "nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]",
"name": "__init__",
"signature": "def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T)"
},
{
"docstring": "Høyresiden(e) i ODE-systemet",
"name": "__call__",
"signat... | 2 | stack_v2_sparse_classes_30k_train_014980 | Implement the Python class `ProblemSIZR` described below.
Class description:
Implement the ProblemSIZR class.
Method signatures and docstrings:
- def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T): nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]
- def __call_... | Implement the Python class `ProblemSIZR` described below.
Class description:
Implement the ProblemSIZR class.
Method signatures and docstrings:
- def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T): nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]
- def __call_... | c8d97c2903078471f8e419f88cc8488d9b8fc7da | <|skeleton|>
class ProblemSIZR:
def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T):
"""nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]"""
<|body_0|>
def __call__(self, u, t):
"""Høyresiden(e) i ODE-systemet"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProblemSIZR:
def __init__(self, sigma, beta, ds, di, rho, alfa, S0, I0, Z0, R0, T):
"""nu, beta: parametere i ODE-systemet S0,I0,R0 = init verdier T: Simulering for t i [0,T]"""
if isinstance(sigma, (float, int)):
self.sigma = lambda t: sigma
elif callable(sigma):
... | the_stack_v2_python_sparse | Prosjekt/SIZR.py | lasse-steinnes/IN1900 | train | 0 | |
a704318d9ef4903611cf2faefde88fdfd9b5348b | [
"if not root:\n return\nself.inorderTraversal_re(root.left)\nprint(root.val)\nself.inorderTraversal_re(root.right)",
"visited = []\nstack = []\nwhile True:\n if root:\n stack.append(root)\n root = root.left\n elif len(stack) > 0:\n root = stack.pop()\n visited.append(root.val)... | <|body_start_0|>
if not root:
return
self.inorderTraversal_re(root.left)
print(root.val)
self.inorderTraversal_re(root.right)
<|end_body_0|>
<|body_start_1|>
visited = []
stack = []
while True:
if root:
stack.append(root)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal_re(self, root):
"""retcursive :param root: :return:"""
<|body_0|>
def inorderTraversal(self, root):
"""stack :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
... | stack_v2_sparse_classes_36k_train_017066 | 1,257 | no_license | [
{
"docstring": "retcursive :param root: :return:",
"name": "inorderTraversal_re",
"signature": "def inorderTraversal_re(self, root)"
},
{
"docstring": "stack :param root: :return:",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018164 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal_re(self, root): retcursive :param root: :return:
- def inorderTraversal(self, root): stack :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal_re(self, root): retcursive :param root: :return:
- def inorderTraversal(self, root): stack :param root: :return:
<|skeleton|>
class Solution:
def inord... | 84bd4a00160e6b2a723a57e149474c6bb38bcce2 | <|skeleton|>
class Solution:
def inorderTraversal_re(self, root):
"""retcursive :param root: :return:"""
<|body_0|>
def inorderTraversal(self, root):
"""stack :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal_re(self, root):
"""retcursive :param root: :return:"""
if not root:
return
self.inorderTraversal_re(root.left)
print(root.val)
self.inorderTraversal_re(root.right)
def inorderTraversal(self, root):
"""stack :param ... | the_stack_v2_python_sparse | tree/inorder_traversal.py | yanghongkai/yhkleetcode | train | 0 | |
85c26497b4a9ded635b3bc22c6142db31ed7bb1f | [
"self.calc_id = calc_id\nself.data_top_dir = os.path.join(tdc_Filenames.get_vis_results_dir(), 'FMCI__%s' % calc_id)\nself.particles = self.__default_particles if particles is None else particles\ntimeinfo = tdc_TimeInfo(calc_id, self.particles[0] + '.h5')\ni_ts_max = timeinfo.get_number_of_ts()\nself.default__i_ts... | <|body_start_0|>
self.calc_id = calc_id
self.data_top_dir = os.path.join(tdc_Filenames.get_vis_results_dir(), 'FMCI__%s' % calc_id)
self.particles = self.__default_particles if particles is None else particles
timeinfo = tdc_TimeInfo(calc_id, self.particles[0] + '.h5')
i_ts_max =... | Class for reading particle data from TDC simulations and creating FMCI files | tdc_FMCI_DataFiles_Maker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tdc_FMCI_DataFiles_Maker:
"""Class for reading particle data from TDC simulations and creating FMCI files"""
def __init__(self, calc_id, particles=None, partition=None):
"""Initializes output directory name, particles, i_ts range, partition Actual calculations will be performed by ma... | stack_v2_sparse_classes_36k_train_017067 | 3,303 | no_license | [
{
"docstring": "Initializes output directory name, particles, i_ts range, partition Actual calculations will be performed by make_files(..) method",
"name": "__init__",
"signature": "def __init__(self, calc_id, particles=None, partition=None)"
},
{
"docstring": "Reads data and creates FMCI files... | 2 | stack_v2_sparse_classes_30k_train_013041 | Implement the Python class `tdc_FMCI_DataFiles_Maker` described below.
Class description:
Class for reading particle data from TDC simulations and creating FMCI files
Method signatures and docstrings:
- def __init__(self, calc_id, particles=None, partition=None): Initializes output directory name, particles, i_ts ran... | Implement the Python class `tdc_FMCI_DataFiles_Maker` described below.
Class description:
Class for reading particle data from TDC simulations and creating FMCI files
Method signatures and docstrings:
- def __init__(self, calc_id, particles=None, partition=None): Initializes output directory name, particles, i_ts ran... | 775dc841b1d8538584c8c68a5f75ae997191e685 | <|skeleton|>
class tdc_FMCI_DataFiles_Maker:
"""Class for reading particle data from TDC simulations and creating FMCI files"""
def __init__(self, calc_id, particles=None, partition=None):
"""Initializes output directory name, particles, i_ts range, partition Actual calculations will be performed by ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tdc_FMCI_DataFiles_Maker:
"""Class for reading particle data from TDC simulations and creating FMCI files"""
def __init__(self, calc_id, particles=None, partition=None):
"""Initializes output directory name, particles, i_ts range, partition Actual calculations will be performed by make_files(..) ... | the_stack_v2_python_sparse | x_DataFunctions/FMCI/tdc_fmci_datafiles_maker.py | atimokhin/tdc_vis | train | 0 |
97a04b0c50d19bd88a5e6b7769640588fba16294 | [
"self.kubeconfig = kubeconfig\nself.name = sname\nself.namespace = namespace\nself.data = {}\nself.create_dict()",
"self.data['apiVersion'] = 'v1'\nself.data['kind'] = 'Group'\nself.data['metadata'] = {}\nself.data['metadata']['name'] = self.name\nself.data['users'] = None"
] | <|body_start_0|>
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.data = {}
self.create_dict()
<|end_body_0|>
<|body_start_1|>
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Group'
self.data['metadata'] = {}
self... | Handle route options | GroupConfig | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
<|body_0|>
def create_dict(self):
"""return a service as a dict"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017068 | 1,002 | permissive | [
{
"docstring": "constructor for handling group options",
"name": "__init__",
"signature": "def __init__(self, sname, namespace, kubeconfig)"
},
{
"docstring": "return a service as a dict",
"name": "create_dict",
"signature": "def create_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020373 | Implement the Python class `GroupConfig` described below.
Class description:
Handle route options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig): constructor for handling group options
- def create_dict(self): return a service as a dict | Implement the Python class `GroupConfig` described below.
Class description:
Handle route options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig): constructor for handling group options
- def create_dict(self): return a service as a dict
<|skeleton|>
class GroupConfig:
"""Han... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
<|body_0|>
def create_dict(self):
"""return a service as a dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupConfig:
"""Handle route options"""
def __init__(self, sname, namespace, kubeconfig):
"""constructor for handling group options"""
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.data = {}
self.create_dict()
def creat... | the_stack_v2_python_sparse | ansible/roles/lib_openshift_3.2/build/lib/group.py | openshift/openshift-tools | train | 170 |
d4b714bab87a12cf3b3f95196b6e6636aef41b43 | [
"count = 0\nfor word in words:\n a = list(chars)\n flag = 1\n for s in word:\n if s not in a:\n flag = 0\n break\n a.remove(s)\n if flag == 1:\n count += len(word)\nreturn count",
"count = 0\nfor word in words:\n for s in word:\n if word.count(s) > ... | <|body_start_0|>
count = 0
for word in words:
a = list(chars)
flag = 1
for s in word:
if s not in a:
flag = 0
break
a.remove(s)
if flag == 1:
count += len(word)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
<|body_0|>
def countCharacters2(self, words: List[str], chars: str) -> int... | stack_v2_sparse_classes_36k_train_017069 | 3,028 | no_license | [
{
"docstring": "执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:",
"name": "countCharacters",
"signature": "def countCharacters(self, words: List[str], chars: str) -> int"
},
{
"docstring": "执行用时 :104 ms, 在所有 Python3 提交中击败了9... | 3 | stack_v2_sparse_classes_30k_train_015498 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countCharacters(self, words: List[str], chars: str) -> int: 执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countCharacters(self, words: List[str], chars: str) -> int: 执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :r... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
<|body_0|>
def countCharacters2(self, words: List[str], chars: str) -> int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
count = 0
for word in words:
a = list(chars)
flag = 1
... | the_stack_v2_python_sparse | LeetCode/1160. Find Words That Can Be Formed by Characters.py | yiming1012/MyLeetCode | train | 2 | |
060cf491d95c2562dee4a400e3409fef73b7b275 | [
"self.attempt_num = attempt_num\nself.job_instance_id = job_instance_id\nself.job_start_time_usecs = job_start_time_usecs",
"if dictionary is None:\n return None\nattempt_num = dictionary.get('attemptNum')\njob_instance_id = dictionary.get('jobInstanceId')\njob_start_time_usecs = dictionary.get('jobStartTimeUs... | <|body_start_0|>
self.attempt_num = attempt_num
self.job_instance_id = job_instance_id
self.job_start_time_usecs = job_start_time_usecs
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
attempt_num = dictionary.get('attemptNum')
job_instance_... | Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snapshot. job_start_time_usecs (long|int): Start time of the job instance. | MagnetoInstanceId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagnetoInstanceId:
"""Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snapshot. job_start_time_usecs (long|int): ... | stack_v2_sparse_classes_36k_train_017070 | 1,991 | permissive | [
{
"docstring": "Constructor for the MagnetoInstanceId class",
"name": "__init__",
"signature": "def __init__(self, attempt_num=None, job_instance_id=None, job_start_time_usecs=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionar... | 2 | null | Implement the Python class `MagnetoInstanceId` described below.
Class description:
Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snap... | Implement the Python class `MagnetoInstanceId` described below.
Class description:
Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snap... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MagnetoInstanceId:
"""Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snapshot. job_start_time_usecs (long|int): ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagnetoInstanceId:
"""Implementation of the 'MagnetoInstanceId' model. TODO: type description here. Attributes: attempt_num (long|int): The attempt of the job instance that took the snapshot. job_instance_id (long|int): Instance of the job that took the snapshot. job_start_time_usecs (long|int): Start time of... | the_stack_v2_python_sparse | cohesity_management_sdk/models/magneto_instance_id.py | cohesity/management-sdk-python | train | 24 |
f46183fd5d77db4ad002a875a73fed28c2f8005c | [
"self.posterior = posterior\nmu = np.random.multivariate_normal(start, sigma, size=n)\nif student:\n self.components = [StudentsTComponent(1.0 / n, m, sigma, nu) for m in mu]\nelse:\n self.components = [GaussianComponent(1.0 / n, m, sigma) for m in mu]\nself.pool = pool\nself.quiet = quiet",
"self.kill_coun... | <|body_start_0|>
self.posterior = posterior
mu = np.random.multivariate_normal(start, sigma, size=n)
if student:
self.components = [StudentsTComponent(1.0 / n, m, sigma, nu) for m in mu]
else:
self.components = [GaussianComponent(1.0 / n, m, sigma) for m in mu]
... | A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf | PopulationMonteCarlo | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulationMonteCarlo:
"""A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf"""
def __init__(self, posterior, n, start, sigma, pool=None, quiet=False, stu... | stack_v2_sparse_classes_36k_train_017071 | 7,579 | permissive | [
{
"docstring": "posterior: the posterior function n: number of components to use in the mixture start: estimated mean of the distribution sigma: estimated covariance matrix pool (optional): an MPI or multiprocessing worker pool",
"name": "__init__",
"signature": "def __init__(self, posterior, n, start, ... | 4 | stack_v2_sparse_classes_30k_train_019099 | Implement the Python class `PopulationMonteCarlo` described below.
Class description:
A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf
Method signatures and docstrings:
- def __... | Implement the Python class `PopulationMonteCarlo` described below.
Class description:
A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf
Method signatures and docstrings:
- def __... | ce195564631b148bef0214a27a57470640c69a08 | <|skeleton|>
class PopulationMonteCarlo:
"""A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf"""
def __init__(self, posterior, n, start, sigma, pool=None, quiet=False, stu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PopulationMonteCarlo:
"""A Population Monte Carlo (PMC) sampler, which combines expectation-maximization and importance sampling This code follows the notation and methodolgy in http://arxiv.org/pdf/0903.0837v1.pdf"""
def __init__(self, posterior, n, start, sigma, pool=None, quiet=False, student=False, n... | the_stack_v2_python_sparse | cosmosis/samplers/pmc/pmc.py | ktanidis/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra | train | 1 |
b6be615febf524ca9d8de6a106b7ff25682e95b3 | [
"super().__init__(**kwargs)\nself.error_message = None\nself.error_redirect = 'home'\nself.workflow = None\nself.object = None",
"super().setup(request, *args, **kwargs)\ntry:\n self.workflow = get_session_workflow(request, kwargs.get('wid'), getattr(self, 'wf_s_related', None), getattr(self, 'wf_pf_related', ... | <|body_start_0|>
super().__init__(**kwargs)
self.error_message = None
self.error_redirect = 'home'
self.workflow = None
self.object = None
<|end_body_0|>
<|body_start_1|>
super().setup(request, *args, **kwargs)
try:
self.workflow = get_session_workflo... | View that sets the workflow attribute. | WorkflowView | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowView:
"""View that sets the workflow attribute."""
def __init__(self, **kwargs):
"""Initialise error field/redirect and the workflow attribute."""
<|body_0|>
def setup(self, request, *args, **kwargs):
"""Add workflow attribute to view object. The query us... | stack_v2_sparse_classes_36k_train_017072 | 12,609 | permissive | [
{
"docstring": "Initialise error field/redirect and the workflow attribute.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Add workflow attribute to view object. The query uses the two variables: - wf_s_related: Workflow select related - wf_pf_related: Workf... | 3 | stack_v2_sparse_classes_30k_train_001794 | Implement the Python class `WorkflowView` described below.
Class description:
View that sets the workflow attribute.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialise error field/redirect and the workflow attribute.
- def setup(self, request, *args, **kwargs): Add workflow attribute to view... | Implement the Python class `WorkflowView` described below.
Class description:
View that sets the workflow attribute.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialise error field/redirect and the workflow attribute.
- def setup(self, request, *args, **kwargs): Add workflow attribute to view... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class WorkflowView:
"""View that sets the workflow attribute."""
def __init__(self, **kwargs):
"""Initialise error field/redirect and the workflow attribute."""
<|body_0|>
def setup(self, request, *args, **kwargs):
"""Add workflow attribute to view object. The query us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkflowView:
"""View that sets the workflow attribute."""
def __init__(self, **kwargs):
"""Initialise error field/redirect and the workflow attribute."""
super().__init__(**kwargs)
self.error_message = None
self.error_redirect = 'home'
self.workflow = None
... | the_stack_v2_python_sparse | ontask/core/permissions.py | abelardopardo/ontask_b | train | 43 |
a8ea4ac53461d1b523445d32598efb43865af202 | [
"self.min_loss = float('inf')\nself.max_acc = -float('inf')\nself.min_delta = min_delta\nself.model_name = model_name\nself.path = str(os.path.join(model_path, self.model_name + '.pth'))\nself.count = 0\nself.first_run = True\nself.best_model = None",
"print(f'Loss to beat: {self.min_loss - self.min_delta:.4f}')\... | <|body_start_0|>
self.min_loss = float('inf')
self.max_acc = -float('inf')
self.min_delta = min_delta
self.model_name = model_name
self.path = str(os.path.join(model_path, self.model_name + '.pth'))
self.count = 0
self.first_run = True
self.best_model = No... | EarlyStopping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
def __init__(self, model_path: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- TODO Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing... | stack_v2_sparse_classes_36k_train_017073 | 44,407 | permissive | [
{
"docstring": "Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- TODO Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing the current fold. `min_delta` : `int`, `optional` Smallest number the given metric needs to change in o... | 2 | stack_v2_sparse_classes_30k_train_013245 | Implement the Python class `EarlyStopping` described below.
Class description:
Implement the EarlyStopping class.
Method signatures and docstrings:
- def __init__(self, model_path: str, model_name: str, fold: int, min_delta=0): Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---... | Implement the Python class `EarlyStopping` described below.
Class description:
Implement the EarlyStopping class.
Method signatures and docstrings:
- def __init__(self, model_path: str, model_name: str, fold: int, min_delta=0): Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---... | d0ee019e5a573bf9b8e232786a9051cd54904487 | <|skeleton|>
class EarlyStopping:
def __init__(self, model_path: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- TODO Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
def __init__(self, model_path: str, model_name: str, fold: int, min_delta=0):
"""Class for early stopping, because only plebs rely on set amounts of epochs. Attributes ---------- TODO Parameters ---------- `model_name` : `str` Model name. `fold` : `int` Number representing the current f... | the_stack_v2_python_sparse | build/lib/pytorch_vision_utils/Utilities.py | nclgbd/PyTorch-Utilities | train | 0 | |
2600bba18f39e4e9a14ae4ecb69ded51c385c635 | [
"context = super().get_context_data(**kwargs)\nrights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))\norganization = rights_statement.organization\napplies_to_type_choices = self.get_applies_to_type_choices(organization)\nformset_data = self.get_formset(rights_statement.rights_basis)\nformset = f... | <|body_start_0|>
context = super().get_context_data(**kwargs)
rights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))
organization = rights_statement.organization
applies_to_type_choices = self.get_applies_to_type_choices(organization)
formset_data = self.get_for... | Update Rights Statements. | RightsUpdateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
<|body_0|>
def form_valid(self, form):
"""Sets variables needed in formsets."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017074 | 6,959 | permissive | [
{
"docstring": "Adds formsets to context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Sets variables needed in formsets.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014086 | Implement the Python class `RightsUpdateView` described below.
Class description:
Update Rights Statements.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds formsets to context data.
- def form_valid(self, form): Sets variables needed in formsets. | Implement the Python class `RightsUpdateView` described below.
Class description:
Update Rights Statements.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds formsets to context data.
- def form_valid(self, form): Sets variables needed in formsets.
<|skeleton|>
class RightsUpdateView:
... | 896cff3566746001dd594baa2e85bf3256016efb | <|skeleton|>
class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
<|body_0|>
def form_valid(self, form):
"""Sets variables needed in formsets."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
context = super().get_context_data(**kwargs)
rights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))
organization = rights_statemen... | the_stack_v2_python_sparse | bag_transfer/rights/views.py | RockefellerArchiveCenter/aurora | train | 24 |
db1eb3709b890c0f3c37113b759abf1a792e010f | [
"self.capacity = capacity\nself.list_dict = collections.defaultdict(collections.OrderedDict)\nself.fre_dict = {}\nself.min_fre = 1",
"if key in self.fre_dict:\n fre = self.fre_dict[key]\n val = self.list_dict[fre].pop(key)\n self.list_dict[fre + 1][key] = val\n self.fre_dict[key] = fre + 1\n if len... | <|body_start_0|>
self.capacity = capacity
self.list_dict = collections.defaultdict(collections.OrderedDict)
self.fre_dict = {}
self.min_fre = 1
<|end_body_0|>
<|body_start_1|>
if key in self.fre_dict:
fre = self.fre_dict[key]
val = self.list_dict[fre].pop... | LFUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_017075 | 2,097 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.list_dict = collections.defaultdict(collections.OrderedDict)
self.fre_dict = {}
self.min_fre = 1
def get(self, key):
""":type key: int :rtype: int"""
if ... | the_stack_v2_python_sparse | Python3/0460-LFU-Cache/soln.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
f28c2e1a08415fe1d2528d82fa7b2fa6c3bdf5d6 | [
"self.entities = entities\nself.sources = sources\nself.created_before = created_before\nself.created_after = created_after\nself.modified_before = modified_before\nself.modified_after = modified_after\nself.properties = properties",
"filter_request = {}\nif self.sources:\n filter_request['Types'] = list(map(l... | <|body_start_0|>
self.entities = entities
self.sources = sources
self.created_before = created_before
self.created_after = created_after
self.modified_before = modified_before
self.modified_after = modified_after
self.properties = properties
<|end_body_0|>
<|body... | A filter used in a lineage query. | LineageFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineageFilter:
"""A filter used in a lineage query."""
def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_befor... | stack_v2_sparse_classes_36k_train_017076 | 27,038 | permissive | [
{
"docstring": "Initialize ``LineageFilter`` instance.",
"name": "__init__",
"signature": "def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[dateti... | 2 | stack_v2_sparse_classes_30k_train_017086 | Implement the Python class `LineageFilter` described below.
Class description:
A filter used in a lineage query.
Method signatures and docstrings:
- def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[da... | Implement the Python class `LineageFilter` described below.
Class description:
A filter used in a lineage query.
Method signatures and docstrings:
- def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[da... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class LineageFilter:
"""A filter used in a lineage query."""
def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_befor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineageFilter:
"""A filter used in a lineage query."""
def __init__(self, entities: Optional[List[Union[LineageEntityEnum, str]]]=None, sources: Optional[List[Union[LineageSourceEnum, str]]]=None, created_before: Optional[datetime]=None, created_after: Optional[datetime]=None, modified_before: Optional[d... | the_stack_v2_python_sparse | src/sagemaker/lineage/query.py | aws/sagemaker-python-sdk | train | 2,050 |
6fdbb45f1266e953964fbe6e539a6c4880df45ff | [
"course_key, _ = _get_course_with_access(request, course_key_string)\ntry:\n cohort = cohorts.get_cohort_by_id(course_key, cohort_id)\nexcept CourseUserGroup.DoesNotExist:\n msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format(cohort_id=cohort_id, course_key_string=course_key_string)\n ... | <|body_start_0|>
course_key, _ = _get_course_with_access(request, course_key_string)
try:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
except CourseUserGroup.DoesNotExist:
msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format(cohort_id=cohor... | **Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/cohorts/v1/courses/{course_id}/cohorts/{co... | CohortUsers | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CohortUsers:
"""**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/coh... | stack_v2_sparse_classes_36k_train_017077 | 31,213 | permissive | [
{
"docstring": "Return the course and cohort for the given course_key_string and cohort_id.",
"name": "_get_course_and_cohort",
"signature": "def _get_course_and_cohort(self, request, course_key_string, cohort_id)"
},
{
"docstring": "Lists the users in a specific cohort.",
"name": "get",
... | 4 | null | Implement the Python class `CohortUsers` described below.
Class description:
**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{co... | Implement the Python class `CohortUsers` described below.
Class description:
**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{co... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CohortUsers:
"""**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/coh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CohortUsers:
"""**Use Cases** List users in a cohort Removes an user from a cohort. Add a user to a specific cohort. **Example Requests** GET /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users DELETE /api/cohorts/v1/courses/{course_id}/cohorts/{cohort_id}/users/{username} POST /api/cohorts/v1/cours... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/course_groups/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
818811439bdd70d0f39cb26c89a10d779695ea85 | [
"if not preorder:\n return None\nroot = TreeNode(preorder[0])\nif len(preorder) == 1 or len(inorder) == 1:\n return root\ni = inorder.index(preorder[0])\nroot.left = self.buildTree(preorder[1:i + 1], inorder[:i])\nroot.right = self.buildTree(preorder[i + 1:], inorder[i + 1:])\nreturn root",
"def build(v):\n... | <|body_start_0|>
if not preorder:
return None
root = TreeNode(preorder[0])
if len(preorder) == 1 or len(inorder) == 1:
return root
i = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:i + 1], inorder[:i])
root.right = self.buildTree... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
<|body_0|>
def buildTree(self, preorder, inorder):
"""05/07/2018 10:44 Time complexity: O(n)"""
<|body_1|>
def buildTree(se... | stack_v2_sparse_classes_36k_train_017078 | 4,039 | no_license | [
{
"docstring": "05/06/2018 18:23 Time complexity; O(n^2)",
"name": "buildTree",
"signature": "def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode"
},
{
"docstring": "05/07/2018 10:44 Time complexity: O(n)",
"name": "buildTree",
"signature": "def buildTree(self, preor... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 05/06/2018 18:23 Time complexity; O(n^2)
- def buildTree(self, preorder, inorder): 05/07/2018 10:44 Time... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 05/06/2018 18:23 Time complexity; O(n^2)
- def buildTree(self, preorder, inorder): 05/07/2018 10:44 Time... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
<|body_0|>
def buildTree(self, preorder, inorder):
"""05/07/2018 10:44 Time complexity: O(n)"""
<|body_1|>
def buildTree(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
if not preorder:
return None
root = TreeNode(preorder[0])
if len(preorder) == 1 or len(inorder) == 1:
return root
i... | the_stack_v2_python_sparse | leetcode/solved/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/solution.py | sungminoh/algorithms | train | 0 | |
6712e59568d483626d91a004a089d77daa8a0e74 | [
"request_user = request.user\nprograms = []\nrequested_program_type = normalize_program_type(request.GET.get('type', self.DEFAULT_PROGRAM_TYPE))\nif request_user.is_staff:\n programs = get_programs_by_type(request.site, requested_program_type)\nelse:\n program_dict = {}\n for staff_program in self.get_prog... | <|body_start_0|>
request_user = request.user
programs = []
requested_program_type = normalize_program_type(request.GET.get('type', self.DEFAULT_PROGRAM_TYPE))
if request_user.is_staff:
programs = get_programs_by_type(request.site, requested_program_type)
else:
... | A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. -------------------------------------------------------------------------------------------- | User Type | API Returns | -------------------------------... | UserProgramReadOnlyAccessView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProgramReadOnlyAccessView:
"""A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. -------------------------------------------------------------------------------------------- | ... | stack_v2_sparse_classes_36k_train_017079 | 41,703 | permissive | [
{
"docstring": "How to respond to a GET request to this endpoint",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Return the Program Enrollments linked to the learner within the data model.",
"name": "_get_enrolled_programs_from_model",
"signature": "def _get_enr... | 4 | null | Implement the Python class `UserProgramReadOnlyAccessView` described below.
Class description:
A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. --------------------------------------------------------... | Implement the Python class `UserProgramReadOnlyAccessView` described below.
Class description:
A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. --------------------------------------------------------... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class UserProgramReadOnlyAccessView:
"""A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. -------------------------------------------------------------------------------------------- | ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProgramReadOnlyAccessView:
"""A view for checking the currently logged-in user's program read only access There are three major categories of users this API is differentiating. See the table below. -------------------------------------------------------------------------------------------- | User Type | A... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/program_enrollments/rest_api/v1/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
10f3c7eff353d95ffa12f9b2c373def929c32c3a | [
"question_tokens = set(get_cleaned_seq_tokens(question.text))\ncolumns_queue = queue.PriorityQueue()\nfor i in range(len(interaction.table.columns)):\n column_tokens = self._get_column_tokens(interaction, i)\n score = _get_question_column_similarity(set(column_tokens), question_tokens)\n columns_queue.put(... | <|body_start_0|>
question_tokens = set(get_cleaned_seq_tokens(question.text))
columns_queue = queue.PriorityQueue()
for i in range(len(interaction.table.columns)):
column_tokens = self._get_column_tokens(interaction, i)
score = _get_question_column_similarity(set(column_t... | Extracts columns that contain tokens'strings match a subset of the question's string. | HeuristicExactMatchTokenSelector | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: ... | stack_v2_sparse_classes_36k_train_017080 | 22,320 | permissive | [
{
"docstring": "Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: contains the cells. question: contains the original text of the question. Returns: The set of selected columns' indexes.",
"name": "_select_columns",
"signature": "def _select_columns... | 2 | stack_v2_sparse_classes_30k_val_000869 | Implement the Python class `HeuristicExactMatchTokenSelector` described below.
Class description:
Extracts columns that contain tokens'strings match a subset of the question's string.
Method signatures and docstrings:
- def _select_columns(self, interaction, question): Extracts columns that contain tokens'strings mat... | Implement the Python class `HeuristicExactMatchTokenSelector` described below.
Class description:
Extracts columns that contain tokens'strings match a subset of the question's string.
Method signatures and docstrings:
- def _select_columns(self, interaction, question): Extracts columns that contain tokens'strings mat... | 569a3c31451d941165bd10783f73f494406b3906 | <|skeleton|>
class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: contains the ... | the_stack_v2_python_sparse | tapas/utils/pruning_utils.py | google-research/tapas | train | 1,043 |
3f7f3dfdef9347112e6a925cf4a6e1aef9642d44 | [
"if not number:\n raise ValueError('\"number\" must not be empty.')\ntry:\n return cls.objects.create(phone_number=number)\nexcept IntegrityError:\n return None",
"if not number:\n raise ValueError('\"number\" must not be empty.')\nnumber = cls.objects.filter(phone_number=number).only('id')\nif not nu... | <|body_start_0|>
if not number:
raise ValueError('"number" must not be empty.')
try:
return cls.objects.create(phone_number=number)
except IntegrityError:
return None
<|end_body_0|>
<|body_start_1|>
if not number:
raise ValueError('"number... | BannedPhoneNumbers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BannedPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in th... | stack_v2_sparse_classes_36k_train_017081 | 3,941 | no_license | [
{
"docstring": "Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in the ban. :raises: ValueError - if \"number\" is empty."... | 3 | null | Implement the Python class `BannedPhoneNumbers` described below.
Class description:
Implement the BannedPhoneNumbers class.
Method signatures and docstrings:
- def add(cls, number): Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: Banned... | Implement the Python class `BannedPhoneNumbers` described below.
Class description:
Implement the BannedPhoneNumbers class.
Method signatures and docstrings:
- def add(cls, number): Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: Banned... | c060941b16c36d258989206f9c2143b5179b4acd | <|skeleton|>
class BannedPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BannedPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in the ban. :raises... | the_stack_v2_python_sparse | core/managing/ban/models.py | HaySayCheese/mappino | train | 0 | |
beff2901dadeea48c8cffca7be08657d240ca19e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn GroupLifecyclePolicy()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'alternateNotificationEmails': lambda n: setattr(self, 'alternate_notification_emails', n.get_str_value()), '... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return GroupLifecyclePolicy()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'alternateNotificationEma... | GroupLifecyclePolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupLifecyclePolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupLifecyclePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k_train_017082 | 2,916 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: GroupLifecyclePolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `GroupLifecyclePolicy` described below.
Class description:
Implement the GroupLifecyclePolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupLifecyclePolicy: Creates a new instance of the appropriate class based o... | Implement the Python class `GroupLifecyclePolicy` described below.
Class description:
Implement the GroupLifecyclePolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupLifecyclePolicy: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class GroupLifecyclePolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupLifecyclePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupLifecyclePolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupLifecyclePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/group_lifecycle_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fd94796047c557b42d455180121d18b4c96ee72f | [
"from scoop.content.models.link import Link\nidentifier = self.value\ncontents = Link.objects.filter(uuid=identifier)\ncontent = contents[0] if contents.exists() else None\nreturn {'link': content}",
"base = super(LinkInline, self).get_template_name()[0]\npath = 'content/{}'.format(base)\nreturn path"
] | <|body_start_0|>
from scoop.content.models.link import Link
identifier = self.value
contents = Link.objects.filter(uuid=identifier)
content = contents[0] if contents.exists() else None
return {'link': content}
<|end_body_0|>
<|body_start_1|>
base = super(LinkInline, self... | Inline d'insertion de liens Format : {{link uuid}} | LinkInline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_017083 | 6,816 | no_license | [
{
"docstring": "Renvoyer le contexte de rendu de l'inline",
"name": "get_context",
"signature": "def get_context(self)"
},
{
"docstring": "Renvoyer le chemin du template",
"name": "get_template_name",
"signature": "def get_template_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001016 | Implement the Python class `LinkInline` described below.
Class description:
Inline d'insertion de liens Format : {{link uuid}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_template_name(self): Renvoyer le chemin du template | Implement the Python class `LinkInline` described below.
Class description:
Inline d'insertion de liens Format : {{link uuid}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_template_name(self): Renvoyer le chemin du template
<|skeleton|>
class LinkInli... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""Renvoyer le chemin du template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkInline:
"""Inline d'insertion de liens Format : {{link uuid}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
from scoop.content.models.link import Link
identifier = self.value
contents = Link.objects.filter(uuid=identifier)
content = ... | the_stack_v2_python_sparse | scoop/content/util/inlines.py | artscoop/scoop | train | 0 |
80c0e24423aa62f932ec85bb6c172dfac5c9244b | [
"map = {'(': -3, '{': -2, '[': -1, ']': 1, '}': 2, ')': 3}\nif s == '':\n return True\nif len(s) % 2 != 0:\n return False\nstack = []\nfor e in s:\n n = len(stack)\n if map[e] < 0:\n stack.append(e)\n continue\n if n > 0 and map[stack[n - 1]] + map[e] == 0:\n stack.pop()\n ... | <|body_start_0|>
map = {'(': -3, '{': -2, '[': -1, ']': 1, '}': 2, ')': 3}
if s == '':
return True
if len(s) % 2 != 0:
return False
stack = []
for e in s:
n = len(stack)
if map[e] < 0:
stack.append(e)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid2(self, s):
"""([)]"""
<|body_1|>
def isValid3(self, s):
"""这也行!!!!! :type s: str :rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017084 | 2,041 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
},
{
"docstring": "([)]",
"name": "isValid2",
"signature": "def isValid2(self, s)"
},
{
"docstring": "这也行!!!!! :type s: str :rtype: bool",
"name": "isValid3",
"signature": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s): :type s: str :rtype: bool
- def isValid2(self, s): ([)]
- def isValid3(self, s): 这也行!!!!! :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s): :type s: str :rtype: bool
- def isValid2(self, s): ([)]
- def isValid3(self, s): 这也行!!!!! :type s: str :rtype: bool
<|skeleton|>
class Solution:
def i... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid2(self, s):
"""([)]"""
<|body_1|>
def isValid3(self, s):
"""这也行!!!!! :type s: str :rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
map = {'(': -3, '{': -2, '[': -1, ']': 1, '}': 2, ')': 3}
if s == '':
return True
if len(s) % 2 != 0:
return False
stack = []
for e in s:
n = len(stack)
... | the_stack_v2_python_sparse | src/Valid Parentheses.py | jsdiuf/leetcode | train | 1 | |
2eeeccff248300037b941dc0e7bc60c2ae8485fa | [
"colors = Counter(nums)\ni = 0\nwhile i < colors[0]:\n nums[i] = 0\n i += 1\nj = 0\nwhile j < colors[1]:\n nums[i] = 1\n i += 1\n j += 1\nk = 0\nwhile k < colors[2]:\n nums[i] = 2\n i += 1\n k += 1",
"left, mid, right = (0, 0, len(nums) - 1)\nwhile left <= right and nums[left] == 0:\n l... | <|body_start_0|>
colors = Counter(nums)
i = 0
while i < colors[0]:
nums[i] = 0
i += 1
j = 0
while j < colors[1]:
nums[i] = 1
i += 1
j += 1
k = 0
while k < colors[2]:
nums[i] = 2
i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
"""Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space complexity: O(1), n is len(nums)."""
<|body_0|>
def sortColors(self, nums):
"""D... | stack_v2_sparse_classes_36k_train_017085 | 2,241 | no_license | [
{
"docstring": "Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space complexity: O(1), n is len(nums).",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": "Doesn't return ... | 2 | stack_v2_sparse_classes_30k_test_000106 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space comp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space comp... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def sortColors(self, nums):
"""Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space complexity: O(1), n is len(nums)."""
<|body_0|>
def sortColors(self, nums):
"""D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
"""Doesn't return anything. Modifies array nums in-place. Algorithm is based on counting colors(0, 1, 2) in array nums. Time complexity: O(n). Space complexity: O(1), n is len(nums)."""
colors = Counter(nums)
i = 0
while i < colors[0]:
... | the_stack_v2_python_sparse | Sorting/sort_colors.py | vladn90/Algorithms | train | 0 | |
4f12c36b522c54aef8a85629786764558f838904 | [
"super(Transformer, self).__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(units=target_vocab)",
"encoder_output = self.encoder(inputs, training, encod... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(units=target_vocab)
<|end_body_0|>
<... | class Transformer | Transformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Parameters ---------- encoder - the encoder layer decoder - the decoder layer linear - a final Dense layer with target_vocab units Re... | stack_v2_sparse_classes_36k_train_017086 | 2,054 | permissive | [
{
"docstring": "Parameters ---------- encoder - the encoder layer decoder - the decoder layer linear - a final Dense layer with target_vocab units Returns ------- None.",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop... | 2 | null | Implement the Python class `Transformer` described below.
Class description:
class Transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Parameters ---------- encoder - the encoder layer decoder - the decoder laye... | Implement the Python class `Transformer` described below.
Class description:
class Transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Parameters ---------- encoder - the encoder layer decoder - the decoder laye... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Parameters ---------- encoder - the encoder layer decoder - the decoder layer linear - a final Dense layer with target_vocab units Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Parameters ---------- encoder - the encoder layer decoder - the decoder layer linear - a final Dense layer with target_vocab units Returns -------... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
9e3970de0244f850b4d1af087fda1e8911910e86 | [
"self.form_headers = settings.FORM_RESULT\nself.json_headers = settings.JSON_RESULT\nself.account = settings.ACCOUNT\nself.password = settings.PASSWORD\nself.conn_sum = settings.CONN_NUMBER\nself.rec_url = settings.REC_URL\nself.conn_url = settings.CONN_URL\nself.vis_url = settings.VIS_URL\nself.video_url = setting... | <|body_start_0|>
self.form_headers = settings.FORM_RESULT
self.json_headers = settings.JSON_RESULT
self.account = settings.ACCOUNT
self.password = settings.PASSWORD
self.conn_sum = settings.CONN_NUMBER
self.rec_url = settings.REC_URL
self.conn_url = settings.CONN_... | 初始化一些全局设置 | CloudMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudMixin:
"""初始化一些全局设置"""
def __init__(self, *args, **kwargs):
"""初始化以后调用云平台接口,获取token,user_id :param dev_id:"""
<|body_0|>
def random_str(self, random_length=6):
"""生成6位随机数 :param random_length: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_017087 | 23,637 | no_license | [
{
"docstring": "初始化以后调用云平台接口,获取token,user_id :param dev_id:",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "生成6位随机数 :param random_length: :return:",
"name": "random_str",
"signature": "def random_str(self, random_length=6)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003373 | Implement the Python class `CloudMixin` described below.
Class description:
初始化一些全局设置
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化以后调用云平台接口,获取token,user_id :param dev_id:
- def random_str(self, random_length=6): 生成6位随机数 :param random_length: :return: | Implement the Python class `CloudMixin` described below.
Class description:
初始化一些全局设置
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化以后调用云平台接口,获取token,user_id :param dev_id:
- def random_str(self, random_length=6): 生成6位随机数 :param random_length: :return:
<|skeleton|>
class CloudMixin:
... | b140a01ab7af55e057bfecb2b444faaf1c3392cb | <|skeleton|>
class CloudMixin:
"""初始化一些全局设置"""
def __init__(self, *args, **kwargs):
"""初始化以后调用云平台接口,获取token,user_id :param dev_id:"""
<|body_0|>
def random_str(self, random_length=6):
"""生成6位随机数 :param random_length: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudMixin:
"""初始化一些全局设置"""
def __init__(self, *args, **kwargs):
"""初始化以后调用云平台接口,获取token,user_id :param dev_id:"""
self.form_headers = settings.FORM_RESULT
self.json_headers = settings.JSON_RESULT
self.account = settings.ACCOUNT
self.password = settings.PASSWORD
... | the_stack_v2_python_sparse | utils/clouds/ob_video.py | wengxuehao/szswj | train | 1 |
9649de1fa39eeba6ff22ee66fe7f8285b650c110 | [
"if not args_lateral:\n args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nif not args_longitudinal:\n args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}\nself.node = node\nself._lon_controller = PIDLongitudinalController(**args_longitudinal)\nself._lat_controller = PIDLateralController(**args_lateral... | <|body_start_0|>
if not args_lateral:
args_lateral = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
if not args_longitudinal:
args_longitudinal = {'K_P': 1.0, 'K_D': 0.0, 'K_I': 0.0}
self.node = node
self._lon_controller = PIDLongitudinalController(**args_longitudinal)
... | VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side | VehiclePIDController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_36k_train_017088 | 6,324 | permissive | [
{
"docstring": ":param vehicle: actor to apply to local planner logic onto :param args_lateral: dictionary of arguments to set the lateral PID controller using the following semantics: K_P -- Proportional term K_D -- Differential term K_I -- Integral term :param args_longitudinal: dictionary of arguments to set... | 2 | stack_v2_sparse_classes_30k_train_010825 | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | Implement the Python class `VehiclePIDController` described below.
Class description:
VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side
Method signatures and docstrings:
- def __init__(self, node, args_lateral=None, ar... | e9063d97ff5a724f76adbb1b852dc71da1dcfeec | <|skeleton|>
class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VehiclePIDController:
"""VehiclePIDController is the combination of two PID controllers (lateral and longitudinal) to perform the low level control a vehicle from client side"""
def __init__(self, node, args_lateral=None, args_longitudinal=None):
""":param vehicle: actor to apply to local planner... | the_stack_v2_python_sparse | carla_ad_agent/src/carla_ad_agent/vehicle_pid_controller.py | carla-simulator/ros-bridge | train | 448 |
388db401080746b28967731f35c4da6269a8552a | [
"user_id = payload['user_id']\njobs = await join_blueprints_with(model=mJob, db=self.db, user_id=user_id)\njob_schema = JobSchema(many=True)\njob_schema.context = {'user': user_id}\ndata, errors = job_schema.dump(jobs)\nif errors:\n return json_response({'error': errors}, status=400)\nreturn json_response({'jobs... | <|body_start_0|>
user_id = payload['user_id']
jobs = await join_blueprints_with(model=mJob, db=self.db, user_id=user_id)
job_schema = JobSchema(many=True)
job_schema.context = {'user': user_id}
data, errors = job_schema.dump(jobs)
if errors:
return json_respon... | List, get and create Jobs. | Jobs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Jobs:
"""List, get and create Jobs."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of Jobs for the current user"""
<|body_0|>
async def post(self, payload: Mapping[str, Any]):
"""Create a new job."""
<|body_1|>
async def delete(sel... | stack_v2_sparse_classes_36k_train_017089 | 2,966 | permissive | [
{
"docstring": "Get a list of Jobs for the current user",
"name": "get",
"signature": "async def get(self, payload: Mapping[str, Any])"
},
{
"docstring": "Create a new job.",
"name": "post",
"signature": "async def post(self, payload: Mapping[str, Any])"
},
{
"docstring": "Delete... | 3 | stack_v2_sparse_classes_30k_train_004814 | Implement the Python class `Jobs` described below.
Class description:
List, get and create Jobs.
Method signatures and docstrings:
- async def get(self, payload: Mapping[str, Any]): Get a list of Jobs for the current user
- async def post(self, payload: Mapping[str, Any]): Create a new job.
- async def delete(self, p... | Implement the Python class `Jobs` described below.
Class description:
List, get and create Jobs.
Method signatures and docstrings:
- async def get(self, payload: Mapping[str, Any]): Get a list of Jobs for the current user
- async def post(self, payload: Mapping[str, Any]): Create a new job.
- async def delete(self, p... | e94889ce784f4399ca74f78be3bc42a5cd880d70 | <|skeleton|>
class Jobs:
"""List, get and create Jobs."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of Jobs for the current user"""
<|body_0|>
async def post(self, payload: Mapping[str, Any]):
"""Create a new job."""
<|body_1|>
async def delete(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Jobs:
"""List, get and create Jobs."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of Jobs for the current user"""
user_id = payload['user_id']
jobs = await join_blueprints_with(model=mJob, db=self.db, user_id=user_id)
job_schema = JobSchema(many=True)
... | the_stack_v2_python_sparse | jobs/views.py | cassinyio/cassiny-spawner | train | 1 |
b7a5ac742168bbf987523aa9a53e13370a995bdd | [
"if not object_ids:\n return {}\nobject_params = GetObjectsParameters(include_directory_object_references=True, object_ids=object_ids)\nprincipal_dics = {object_id: DirectoryObject() for object_id in object_ids}\naad_objects = graph_client.objects.get_objects_by_object_ids(object_params)\ntry:\n for aad_objec... | <|body_start_0|>
if not object_ids:
return {}
object_params = GetObjectsParameters(include_directory_object_references=True, object_ids=object_ids)
principal_dics = {object_id: DirectoryObject() for object_id in object_ids}
aad_objects = graph_client.objects.get_objects_by_ob... | GraphHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphHelper:
def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False):
"""Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. ... | stack_v2_sparse_classes_36k_train_017090 | 23,452 | permissive | [
{
"docstring": "Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_on_graph_call_error: A boolean indicate whether an error should be raised if the underlying Microsof... | 2 | stack_v2_sparse_classes_30k_train_018475 | Implement the Python class `GraphHelper` described below.
Class description:
Implement the GraphHelper class.
Method signatures and docstrings:
- def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False): Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client... | Implement the Python class `GraphHelper` described below.
Class description:
Implement the GraphHelper class.
Method signatures and docstrings:
- def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False): Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client... | 27563cf4571040f923124e1acb2463f11e372225 | <|skeleton|>
class GraphHelper:
def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False):
"""Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphHelper:
def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False):
"""Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_o... | the_stack_v2_python_sparse | tools/c7n_azure/c7n_azure/utils.py | cloud-custodian/cloud-custodian | train | 3,327 | |
612e22707e7b39a39551d31dd330cfaaea681298 | [
"program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')\noutputs, result = Computer(program, inputs=[]).run()\nassert program == outputs",
"program = parse_program('1102,34915192,34915192,7,4,7,99,0')\noutputs, result = Computer(program, inputs=[]).run()\nassert len(str(outputs[0])) ... | <|body_start_0|>
program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')
outputs, result = Computer(program, inputs=[]).run()
assert program == outputs
<|end_body_0|>
<|body_start_1|>
program = parse_program('1102,34915192,34915192,7,4,7,99,0')
outpu... | TestProblem09 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
<|body_0|>
def test_part1_example2(self):
"""1102,34915192,34915192,7,4,7,99,0 should output a 16-dig... | stack_v2_sparse_classes_36k_train_017091 | 5,550 | no_license | [
{
"docstring": "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.",
"name": "test_part1_example1",
"signature": "def test_part1_example1(self)"
},
{
"docstring": "1102,34915192,34915192,7,4,7,99,0 should output a 16-digit number.",
... | 4 | stack_v2_sparse_classes_30k_train_012586 | Implement the Python class `TestProblem09` described below.
Class description:
Implement the TestProblem09 class.
Method signatures and docstrings:
- def test_part1_example1(self): 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.
- def test_part1_exampl... | Implement the Python class `TestProblem09` described below.
Class description:
Implement the TestProblem09 class.
Method signatures and docstrings:
- def test_part1_example1(self): 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.
- def test_part1_exampl... | cd8d6c090496246d17b75dfc9f70175379aebeb8 | <|skeleton|>
class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
<|body_0|>
def test_part1_example2(self):
"""1102,34915192,34915192,7,4,7,99,0 should output a 16-dig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')
outputs, result = Computer(program,... | the_stack_v2_python_sparse | computer/test_computer.py | mattnworb/advent-of-code-2019 | train | 0 | |
d0bf64745420685046ac8bc55b805b155478ef29 | [
"if not isinstance(data, np.ndarray):\n return False\ndtypes = (np.object_, np.unicode_, np.str_)\nreturn issubclass(data.dtype.type, dtypes)",
"self.record_size = np.atleast_2d(self.data).shape\nself.data = self.original_data.ravel(order='F')\nself.empty = 'yes' if self.data.size == 0 else 'no'"
] | <|body_start_0|>
if not isinstance(data, np.ndarray):
return False
dtypes = (np.object_, np.unicode_, np.str_)
return issubclass(data.dtype.type, dtypes)
<|end_body_0|>
<|body_start_1|>
self.record_size = np.atleast_2d(self.data).shape
self.data = self.original_data.... | Inserter for arrays of objects. | ArrayInserter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayInserter:
"""Inserter for arrays of objects."""
def can_insert(data):
"""This can insert arrays of objects or string-like things."""
<|body_0|>
def prepare_data(self):
"""Records RecordSize and Empty metadata."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017092 | 2,050 | permissive | [
{
"docstring": "This can insert arrays of objects or string-like things.",
"name": "can_insert",
"signature": "def can_insert(data)"
},
{
"docstring": "Records RecordSize and Empty metadata.",
"name": "prepare_data",
"signature": "def prepare_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021649 | Implement the Python class `ArrayInserter` described below.
Class description:
Inserter for arrays of objects.
Method signatures and docstrings:
- def can_insert(data): This can insert arrays of objects or string-like things.
- def prepare_data(self): Records RecordSize and Empty metadata. | Implement the Python class `ArrayInserter` described below.
Class description:
Inserter for arrays of objects.
Method signatures and docstrings:
- def can_insert(data): This can insert arrays of objects or string-like things.
- def prepare_data(self): Records RecordSize and Empty metadata.
<|skeleton|>
class ArrayIn... | 5923798f61c80771d69ff7500446b711921159a7 | <|skeleton|>
class ArrayInserter:
"""Inserter for arrays of objects."""
def can_insert(data):
"""This can insert arrays of objects or string-like things."""
<|body_0|>
def prepare_data(self):
"""Records RecordSize and Empty metadata."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArrayInserter:
"""Inserter for arrays of objects."""
def can_insert(data):
"""This can insert arrays of objects or string-like things."""
if not isinstance(data, np.ndarray):
return False
dtypes = (np.object_, np.unicode_, np.str_)
return issubclass(data.dtype.... | the_stack_v2_python_sparse | sdafile/cell_inserter.py | enthought/sandia-data-archive | train | 0 |
d9f1f36da91d219762d554c28747e89364847ee9 | [
"if dtype:\n pyKeOps_Warning('keyword argument dtype in Genred is deprecated ; argument is ignored.')\nif cuda_type:\n pyKeOps_Warning('keyword argument cuda_type in Genred is deprecated ; argument is ignored.')\nself.reduction_op = reduction_op\nreduction_op_internal, formula2 = preprocess(reduction_op, form... | <|body_start_0|>
if dtype:
pyKeOps_Warning('keyword argument dtype in Genred is deprecated ; argument is ignored.')
if cuda_type:
pyKeOps_Warning('keyword argument cuda_type in Genred is deprecated ; argument is ignored.')
self.reduction_op = reduction_op
reductio... | Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tutorials/index>`. Taking as input a handful of strings and integers that sp... | Genred | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Genred:
"""Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tutorials/index>`. Taking as input a handf... | stack_v2_sparse_classes_36k_train_017093 | 18,211 | permissive | [
{
"docstring": "Instantiate a new generic operation. Note: :class:`Genred` relies on C++ or CUDA kernels that are compiled on-the-fly, and stored in a :ref:`cache directory <part.cache>` as shared libraries (\".so\" files) for later use. Args: formula (string): The scalar- or vector-valued expression that shoul... | 2 | null | Implement the Python class `Genred` described below.
Class description:
Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tut... | Implement the Python class `Genred` described below.
Class description:
Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tut... | 52ed22a7fbbcf4bd02dbdf5dc2b00bf79cceddf5 | <|skeleton|>
class Genred:
"""Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tutorials/index>`. Taking as input a handf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Genred:
"""Creates a new generic operation. This is KeOps' main function, whose usage is documented in the :doc:`user-guide <../../Genred>`, the :doc:`gallery of examples <../../../_auto_examples/index>` and the :doc:`high-level tutorials <../../../_auto_tutorials/index>`. Taking as input a handful of strings... | the_stack_v2_python_sparse | pykeops/pykeops/numpy/generic/generic_red.py | getkeops/keops | train | 910 |
5f48f665c7656c9250960f1e59a7158d85b2149a | [
"number = int(request.form['number'])\nstudent = StudentModel.objects(number=number).first()\npw = request.form['pw']\nif not student:\n return Response('', 204)\npw = hexlify(pbkdf2_hmac(hash_name='sha256', password=pw.encode(), salt=current_app.secret_key.encode(), iterations=100000)).decode('utf-8')\nstudent.... | <|body_start_0|>
number = int(request.form['number'])
student = StudentModel.objects(number=number).first()
pw = request.form['pw']
if not student:
return Response('', 204)
pw = hexlify(pbkdf2_hmac(hash_name='sha256', password=pw.encode(), salt=current_app.secret_key.... | AccountControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountControl:
def post(self):
"""학생 계정 비밀번호 변경"""
<|body_0|>
def delete(self):
"""관리자 계정 삭제"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
number = int(request.form['number'])
student = StudentModel.objects(number=number).first()
... | stack_v2_sparse_classes_36k_train_017094 | 1,726 | permissive | [
{
"docstring": "학생 계정 비밀번호 변경",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "관리자 계정 삭제",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017532 | Implement the Python class `AccountControl` described below.
Class description:
Implement the AccountControl class.
Method signatures and docstrings:
- def post(self): 학생 계정 비밀번호 변경
- def delete(self): 관리자 계정 삭제 | Implement the Python class `AccountControl` described below.
Class description:
Implement the AccountControl class.
Method signatures and docstrings:
- def post(self): 학생 계정 비밀번호 변경
- def delete(self): 관리자 계정 삭제
<|skeleton|>
class AccountControl:
def post(self):
"""학생 계정 비밀번호 변경"""
<|body_0|>
... | de585fe904a2bf15f9fc74219eae176151a0f8ca | <|skeleton|>
class AccountControl:
def post(self):
"""학생 계정 비밀번호 변경"""
<|body_0|>
def delete(self):
"""관리자 계정 삭제"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountControl:
def post(self):
"""학생 계정 비밀번호 변경"""
number = int(request.form['number'])
student = StudentModel.objects(number=number).first()
pw = request.form['pw']
if not student:
return Response('', 204)
pw = hexlify(pbkdf2_hmac(hash_name='sha256... | the_stack_v2_python_sparse | Server/app/views/v1/admin/account/account_control.py | miraedbswo/DMS-Backend | train | 2 | |
9258406609f33d56b963b00ee0e03dfa0389e9ca | [
"super().__init__(model_dir, *args, **kwargs)\nfrom modelscope.models.multi_modal.mplug import MPlug\nself.model = MPlug.from_pretrained(model_dir)\nself.tokenizer = self.model.tokenizer",
"task = Config.from_file(osp.join(self.model_dir, ModelFile.CONFIGURATION)).task\nif not self.training and 'question' in inpu... | <|body_start_0|>
super().__init__(model_dir, *args, **kwargs)
from modelscope.models.multi_modal.mplug import MPlug
self.model = MPlug.from_pretrained(model_dir)
self.tokenizer = self.model.tokenizer
<|end_body_0|>
<|body_start_1|>
task = Config.from_file(osp.join(self.model_dir... | MPlugForAllTasks | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPlugForAllTasks:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path."""
<|body_0|>
def forward(self, input: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""return the result... | stack_v2_sparse_classes_36k_train_017095 | 3,065 | permissive | [
{
"docstring": "initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path.",
"name": "__init__",
"signature": "def __init__(self, model_dir: str, *args, **kwargs)"
},
{
"docstring": "return the result by the model Args: input (Dict[str, Tensor]): the preprocesse... | 2 | null | Implement the Python class `MPlugForAllTasks` described below.
Class description:
Implement the MPlugForAllTasks class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path.
- def forward(se... | Implement the Python class `MPlugForAllTasks` described below.
Class description:
Implement the MPlugForAllTasks class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path.
- def forward(se... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class MPlugForAllTasks:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path."""
<|body_0|>
def forward(self, input: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""return the result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPlugForAllTasks:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the mplug model from the `model_dir` path. Args: model_dir (str): the model path."""
super().__init__(model_dir, *args, **kwargs)
from modelscope.models.multi_modal.mplug import MPlug
self.mode... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/multi_modal/mplug_for_all_tasks.py | alldatacenter/alldata | train | 774 | |
318a685996e4a58cca1608159a2299c75c8dca77 | [
"book = BookInfo.objects.latest('id')\nserializer = self.get_serializer(book)\nreturn Response(serializer.data)",
"book = self.get_object()\nbread = request.data.get('bread')\nbook.bread = bread\nbook.save()\nserializer = self.get_serializer(book)\nreturn Response(serializer.data)"
] | <|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = self.get_serializer(book)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
book = self.get_object()
bread = request.data.get('bread')
book.bread = bread
book.save()
seriali... | 视图集 | BookInfoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
<|body_0|>
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book = BookInfo.objects.latest('id')
serializer = self.... | stack_v2_sparse_classes_36k_train_017096 | 2,085 | no_license | [
{
"docstring": "获取最新发布的图书信息",
"name": "latest",
"signature": "def latest(self, request)"
},
{
"docstring": "修改指定图书的阅读量(只修改阅读量)",
"name": "read",
"signature": "def read(self, request, pk)"
}
] | 2 | null | Implement the Python class `BookInfoViewSet` described below.
Class description:
视图集
Method signatures and docstrings:
- def latest(self, request): 获取最新发布的图书信息
- def read(self, request, pk): 修改指定图书的阅读量(只修改阅读量) | Implement the Python class `BookInfoViewSet` described below.
Class description:
视图集
Method signatures and docstrings:
- def latest(self, request): 获取最新发布的图书信息
- def read(self, request, pk): 修改指定图书的阅读量(只修改阅读量)
<|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""... | f8ec0bec399253e481e16443ba9a3e45e61486f4 | <|skeleton|>
class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
<|body_0|>
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookInfoViewSet:
"""视图集"""
def latest(self, request):
"""获取最新发布的图书信息"""
book = BookInfo.objects.latest('id')
serializer = self.get_serializer(book)
return Response(serializer.data)
def read(self, request, pk):
"""修改指定图书的阅读量(只修改阅读量)"""
book = self.get_o... | the_stack_v2_python_sparse | drf_demo/booktest/views-12-在视图集中添加额外action处理函数.py | cz495969281/2019_- | train | 0 |
6ae8024b3cab5c8aa89048c81122c143f4d1f38c | [
"self.model = model\nself.epoch_type = epoch_type\nself.batch_iterator = batch_iterator\nself.logger = logger\nself.batch_count = 0\nself.results: epoch.Results = None\nself.graph_ids = set()\nsuper(EpochThread, self).__init__(f'{epoch_type.name.capitalize()} epoch {model.epoch_num}', 0, batch_iterator.graph_count,... | <|body_start_0|>
self.model = model
self.epoch_type = epoch_type
self.batch_iterator = batch_iterator
self.logger = logger
self.batch_count = 0
self.results: epoch.Results = None
self.graph_ids = set()
super(EpochThread, self).__init__(f'{epoch_type.name.c... | A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter. | EpochThread | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpochThread:
"""A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter."""
def __init__(self, model: ClassifierBase, epoch_type: epoch.Type, batch_iterator: batches.BatchIterator, logger: logging.Logg... | stack_v2_sparse_classes_36k_train_017097 | 15,969 | permissive | [
{
"docstring": "Constructor. Args: model: A model instance. epoch_type: The type of epoch to run. batch_iterator: A batch iterator. logger: A logger.",
"name": "__init__",
"signature": "def __init__(self, model: ClassifierBase, epoch_type: epoch.Type, batch_iterator: batches.BatchIterator, logger: loggi... | 2 | null | Implement the Python class `EpochThread` described below.
Class description:
A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter.
Method signatures and docstrings:
- def __init__(self, model: ClassifierBase, epoch_type: epo... | Implement the Python class `EpochThread` described below.
Class description:
A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter.
Method signatures and docstrings:
- def __init__(self, model: ClassifierBase, epoch_type: epo... | cd99d2c5362acd0b24ee224492bb3e8c4d4736fb | <|skeleton|>
class EpochThread:
"""A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter."""
def __init__(self, model: ClassifierBase, epoch_type: epoch.Type, batch_iterator: batches.BatchIterator, logger: logging.Logg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EpochThread:
"""A thread which runs a single epoch of a model. After running this thread, the results of the epoch may be accessed through the 'results' parameter."""
def __init__(self, model: ClassifierBase, epoch_type: epoch.Type, batch_iterator: batches.BatchIterator, logger: logging.Logger):
... | the_stack_v2_python_sparse | deeplearning/ml4pl/models/classifier_base.py | Zacharias030/ProGraML | train | 0 |
d5604cf5a3efe2ddaaf470ec84e89351bce40812 | [
"super(MultiHeadAttention, self).__init__()\nself.num_head = num_head\nself.num_dim = num_dim\nself.num_dim_k = num_dim_k\nself.num_dim_v = num_dim_v\nself.w_q = nn.Parameter(torch.FloatTensor(num_head, num_dim, num_dim_k))\nself.w_k = nn.Parameter(torch.FloatTensor(num_head, num_dim, num_dim_k))\nself.w_v = nn.Par... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
self.num_head = num_head
self.num_dim = num_dim
self.num_dim_k = num_dim_k
self.num_dim_v = num_dim_v
self.w_q = nn.Parameter(torch.FloatTensor(num_head, num_dim, num_dim_k))
self.w_k = nn.Parameter(torch... | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
def __init__(self, num_head, num_dim, num_dim_k, num_dim_v, dropout_rate=0.1):
"""num_head: the number of head num_dim: the number of dimension of each query word and key num_dim_k: the number of dimension query and key will mapping to num_dim_v: the number of dimensi... | stack_v2_sparse_classes_36k_train_017098 | 4,134 | no_license | [
{
"docstring": "num_head: the number of head num_dim: the number of dimension of each query word and key num_dim_k: the number of dimension query and key will mapping to num_dim_v: the number of dimension value will mapping to",
"name": "__init__",
"signature": "def __init__(self, num_head, num_dim, num... | 2 | null | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, num_head, num_dim, num_dim_k, num_dim_v, dropout_rate=0.1): num_head: the number of head num_dim: the number of dimension of each query wor... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implement the MultiHeadAttention class.
Method signatures and docstrings:
- def __init__(self, num_head, num_dim, num_dim_k, num_dim_v, dropout_rate=0.1): num_head: the number of head num_dim: the number of dimension of each query wor... | be85ee0c1fa915ae08ffb857643f9429a7749c0e | <|skeleton|>
class MultiHeadAttention:
def __init__(self, num_head, num_dim, num_dim_k, num_dim_v, dropout_rate=0.1):
"""num_head: the number of head num_dim: the number of dimension of each query word and key num_dim_k: the number of dimension query and key will mapping to num_dim_v: the number of dimensi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
def __init__(self, num_head, num_dim, num_dim_k, num_dim_v, dropout_rate=0.1):
"""num_head: the number of head num_dim: the number of dimension of each query word and key num_dim_k: the number of dimension query and key will mapping to num_dim_v: the number of dimension value will ... | the_stack_v2_python_sparse | models/Attention.py | HuangYiran/MasterArbeit | train | 1 | |
3c26419e5d29474b3dff3181b455a9518d5c97ad | [
"storage = get_storage()\nauth0_id = get_auth0_id_of_user(email)\nuser_id = storage.read_user_id(auth0_id)\nreturn super().post(user_id, role_id)",
"storage = get_storage()\nauth0_id = get_auth0_id_of_user(email)\ntry:\n user_id = storage.read_user_id(auth0_id)\nexcept StorageAuthError:\n return ('', 204)\n... | <|body_start_0|>
storage = get_storage()
auth0_id = get_auth0_id_of_user(email)
user_id = storage.read_user_id(auth0_id)
return super().post(user_id, role_id)
<|end_body_0|>
<|body_start_1|>
storage = get_storage()
auth0_id = get_auth0_id_of_user(email)
try:
... | UserRolesManagementByEmailView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRolesManagementByEmailView:
def post(self, email, role_id):
"""--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref... | stack_v2_sparse_classes_36k_train_017099 | 12,608 | permissive | [
{
"docstring": "--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/responses/404-NotFound'",
"name": "post",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_013786 | Implement the Python class `UserRolesManagementByEmailView` described below.
Class description:
Implement the UserRolesManagementByEmailView class.
Method signatures and docstrings:
- def post(self, email, role_id): --- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Rol... | Implement the Python class `UserRolesManagementByEmailView` described below.
Class description:
Implement the UserRolesManagementByEmailView class.
Method signatures and docstrings:
- def post(self, email, role_id): --- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Rol... | 280800c73eb7cfd49029462b352887e78f1ff91b | <|skeleton|>
class UserRolesManagementByEmailView:
def post(self, email, role_id):
"""--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRolesManagementByEmailView:
def post(self, email, role_id):
"""--- summary: Add a Role to a User by email. parameters: - email - role_id tags: - Users-By-Email - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/component... | the_stack_v2_python_sparse | sfa_api/users.py | SolarArbiter/solarforecastarbiter-api | train | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.