blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa388f465c2a3ee1b64a1361a0ef7b038d367547 | [
"value = proposal['value']\nif value is None:\n return value\nif self.min and self.min > value:\n value = max(value, self.min)\nif self.max and self.max < value:\n value = min(value, self.max)\nreturn value",
"min = proposal['value']\nif min is None:\n return min\nif self.max and min > self.max:\n ... | <|body_start_0|>
value = proposal['value']
if value is None:
return value
if self.min and self.min > value:
value = max(value, self.min)
if self.max and self.max < value:
value = min(value, self.max)
return value
<|end_body_0|>
<|body_start_1|... | Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The time step to use for the picker, in seco... | TimePicker | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The ti... | stack_v2_sparse_classes_10k_train_004600 | 2,779 | permissive | [
{
"docstring": "Cap and floor value",
"name": "_validate_value",
"signature": "def _validate_value(self, proposal)"
},
{
"docstring": "Enforce min <= value <= max",
"name": "_validate_min",
"signature": "def _validate_min(self, proposal)"
},
{
"docstring": "Enforce min <= value <... | 3 | stack_v2_sparse_classes_30k_train_003211 | Implement the Python class `TimePicker` described below.
Class description:
Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowe... | Implement the Python class `TimePicker` described below.
Class description:
Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowe... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The ti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The time step to us... | the_stack_v2_python_sparse | contrib/python/ipywidgets/py3/ipywidgets/widgets/widget_time.py | catboost/catboost | train | 8,012 |
e87a8683d4300f34018575e8d42abaf0fb780b5c | [
"self.path = path\nself.external_data_dir = external_data_dir\nself.ignore_external_data = util.default(ignore_external_data, False)",
"G_LOGGER.info(f'Loading model: {self.path}')\nauto_load_ext_data = self.external_data_dir is None and (not self.ignore_external_data)\ntry:\n model = onnx.load(self.path, load... | <|body_start_0|>
self.path = path
self.external_data_dir = external_data_dir
self.ignore_external_data = util.default(ignore_external_data, False)
<|end_body_0|>
<|body_start_1|>
G_LOGGER.info(f'Loading model: {self.path}')
auto_load_ext_data = self.external_data_dir is None and... | Functor that loads an ONNX model from a file. | OnnxFromPath | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where ext... | stack_v2_sparse_classes_10k_train_004601 | 37,448 | permissive | [
{
"docstring": "Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where external data for the model is stored. ignore_external_data (bool): Whether to ignore any external data and just load the model structure without any weights. Th... | 2 | null | Implement the Python class `OnnxFromPath` described below.
Class description:
Functor that loads an ONNX model from a file.
Method signatures and docstrings:
- def __init__(self, path, external_data_dir=None, ignore_external_data=None): Loads an ONNX model from a file. Args: path (str): The path from which to load th... | Implement the Python class `OnnxFromPath` described below.
Class description:
Functor that loads an ONNX model from a file.
Method signatures and docstrings:
- def __init__(self, path, external_data_dir=None, ignore_external_data=None): Loads an ONNX model from a file. Args: path (str): The path from which to load th... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where ext... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where external data fo... | the_stack_v2_python_sparse | tools/Polygraphy/polygraphy/backend/onnx/loader.py | NVIDIA/TensorRT | train | 8,026 |
9eeefcb361a656a4846f3c3f5ce24fb47606c40a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | StyleFactorServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
<|body_0|>
def GetMomentum(self, request, ... | stack_v2_sparse_classes_10k_train_004602 | 4,758 | no_license | [
{
"docstring": "语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数",
"name": "GetSize",
"signature": "def GetSize(self, request, context)"
},
{
"docstring": "语法: get_momentum(ts_... | 4 | stack_v2_sparse_classes_30k_train_002113 | Implement the Python class `StyleFactorServicer` described below.
Class description:
Implement the StyleFactorServicer class.
Method signatures and docstrings:
- def GetSize(self, request, context): 语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'... | Implement the Python class `StyleFactorServicer` described below.
Class description:
Implement the StyleFactorServicer class.
Method signatures and docstrings:
- def GetSize(self, request, context): 语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'... | 663697ce5b3e591e1eddb8d308a1522214916fe5 | <|skeleton|>
class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
<|body_0|>
def GetMomentum(self, request, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StyleFactorServicer:
def GetSize(self, request, context):
"""语法: get_size(ts_code: str, fields: str) 描述: 获取指定股票的市值因子 前置条件: ts_code为股票代码加交易所代号,如000001.SZ表示平安银行; fields限定为'circ_mv'和'total_mv',分别代表流通市值和总市值 后置条件: 返回对应股票的流通市值/总市值的自然对数"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
conte... | the_stack_v2_python_sparse | rpc/protoc/style_factor_pb2_grpc.py | webclinic017/soft_fin | train | 0 | |
9d2be85fcbc878abfcef49e9a6ef17ad071ae8a4 | [
"from dials.array_family import flex\ng = handle['entry/data_processing']\nrl = flex.reflection_table(int(g.attrs['num_reflections']))\nfor key in g:\n item = g[key]\n name = item.attrs['flex_type']\n if name == 'shoebox':\n flex_type = getattr(flex, name)\n data = item['data']\n mask ... | <|body_start_0|>
from dials.array_family import flex
g = handle['entry/data_processing']
rl = flex.reflection_table(int(g.attrs['num_reflections']))
for key in g:
item = g[key]
name = item.attrs['flex_type']
if name == 'shoebox':
flex_t... | Decoder for the reflection data. | ReflectionListDecoder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflectionListDecoder:
"""Decoder for the reflection data."""
def decode(self, handle):
"""Decode the reflection data."""
<|body_0|>
def decode_column(self, flex_type, data):
"""Decode a column for various flex types."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_10k_train_004603 | 5,824 | permissive | [
{
"docstring": "Decode the reflection data.",
"name": "decode",
"signature": "def decode(self, handle)"
},
{
"docstring": "Decode a column for various flex types.",
"name": "decode_column",
"signature": "def decode_column(self, flex_type, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001177 | Implement the Python class `ReflectionListDecoder` described below.
Class description:
Decoder for the reflection data.
Method signatures and docstrings:
- def decode(self, handle): Decode the reflection data.
- def decode_column(self, flex_type, data): Decode a column for various flex types. | Implement the Python class `ReflectionListDecoder` described below.
Class description:
Decoder for the reflection data.
Method signatures and docstrings:
- def decode(self, handle): Decode the reflection data.
- def decode_column(self, flex_type, data): Decode a column for various flex types.
<|skeleton|>
class Refl... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class ReflectionListDecoder:
"""Decoder for the reflection data."""
def decode(self, handle):
"""Decode the reflection data."""
<|body_0|>
def decode_column(self, flex_type, data):
"""Decode a column for various flex types."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReflectionListDecoder:
"""Decoder for the reflection data."""
def decode(self, handle):
"""Decode the reflection data."""
from dials.array_family import flex
g = handle['entry/data_processing']
rl = flex.reflection_table(int(g.attrs['num_reflections']))
for key in ... | the_stack_v2_python_sparse | src/dials/util/nexus_old.py | dials/dials | train | 71 |
a73fba01c2da0f3d27a47fbd2591e312b3063919 | [
"super(Test_relax_fit, self).__init__(methodName)\nself.interpreter = Interpreter(show_script=False, raise_relax_error=True)\nself.interpreter.populate_self()\nself.interpreter.on(verbose=False)\nself.relax_fit_fns = self.interpreter.relax_fit",
"for data in DATA_TYPES:\n if data[0] == 'float' or data[0] == 'b... | <|body_start_0|>
super(Test_relax_fit, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise_relax_error=True)
self.interpreter.populate_self()
self.interpreter.on(verbose=False)
self.relax_fit_fns = self.interpreter.relax_fit
<|end_body_0|>
<|body_s... | Unit tests for the functions of the 'prompt.relax_fit' module. | Test_relax_fit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_time_argfail_time(self):
"""The time arg test of the relax_f... | stack_v2_sparse_classes_10k_train_004604 | 3,846 | no_license | [
{
"docstring": "Set up the test case class for the system tests.",
"name": "__init__",
"signature": "def __init__(self, methodName=None)"
},
{
"docstring": "The time arg test of the relax_fit.relax_time() user function.",
"name": "test_relax_time_argfail_time",
"signature": "def test_rel... | 4 | null | Implement the Python class `Test_relax_fit` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_fit' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_time_argfail_time(self): The time ar... | Implement the Python class `Test_relax_fit` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_fit' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_time_argfail_time(self): The time ar... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_time_argfail_time(self):
"""The time arg test of the relax_f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_relax_fit:
"""Unit tests for the functions of the 'prompt.relax_fit' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
super(Test_relax_fit, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise... | the_stack_v2_python_sparse | test_suite/unit_tests/_prompt/test_relax_fit.py | jlec/relax | train | 4 |
c6e1b2e3f9b1b14f4881ee9baa0e1999835e5ac2 | [
"units = Unit('hour')\nwidth = 5\nweights_instance = ChooseDefaultWeightsTriangular(width, units=units)\nexpected_width = 5\nexpected_unit = units\nself.assertEqual(weights_instance.width, expected_width)\nself.assertEqual(weights_instance.parameters_units, expected_unit)",
"units = 'hour'\nwidth = 5\nweights_ins... | <|body_start_0|>
units = Unit('hour')
width = 5
weights_instance = ChooseDefaultWeightsTriangular(width, units=units)
expected_width = 5
expected_unit = units
self.assertEqual(weights_instance.width, expected_width)
self.assertEqual(weights_instance.parameters_uni... | Tests for the __init__ method in ChooseDefaultWeightsTriangular class | Test___init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
<|body_0|>
def test_string_input(self):
"""Test the case where a string is... | stack_v2_sparse_classes_10k_train_004605 | 13,166 | permissive | [
{
"docstring": "Test the case where an instance of cf_units.Unit is passed in",
"name": "test_cf_unit_input",
"signature": "def test_cf_unit_input(self)"
},
{
"docstring": "Test the case where a string is passed and gets converted to a Unit instance",
"name": "test_string_input",
"signat... | 2 | null | Implement the Python class `Test___init__` described below.
Class description:
Tests for the __init__ method in ChooseDefaultWeightsTriangular class
Method signatures and docstrings:
- def test_cf_unit_input(self): Test the case where an instance of cf_units.Unit is passed in
- def test_string_input(self): Test the c... | Implement the Python class `Test___init__` described below.
Class description:
Tests for the __init__ method in ChooseDefaultWeightsTriangular class
Method signatures and docstrings:
- def test_cf_unit_input(self): Test the case where an instance of cf_units.Unit is passed in
- def test_string_input(self): Test the c... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
<|body_0|>
def test_string_input(self):
"""Test the case where a string is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test___init__:
"""Tests for the __init__ method in ChooseDefaultWeightsTriangular class"""
def test_cf_unit_input(self):
"""Test the case where an instance of cf_units.Unit is passed in"""
units = Unit('hour')
width = 5
weights_instance = ChooseDefaultWeightsTriangular(wid... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py | metoppv/improver | train | 101 |
7d62f4e02a6ea5530ca06b8f316cc604a4ed8b5b | [
"if blob.get('remaining', 0) == 1:\n self.rebuild = True\nif update:\n self.kwargs['rebuild'] = self.rebuild\n self.rebuild = False\naccept_prob = max(0.5, blob['accept']) / self.kwargs['walks']\ndelay = self.nlive // 10 - 1\nn_target = getattr(_SamplingContainer, 'naccept', 60)\nself.walks = (self.walks *... | <|body_start_0|>
if blob.get('remaining', 0) == 1:
self.rebuild = True
if update:
self.kwargs['rebuild'] = self.rebuild
self.rebuild = False
accept_prob = max(0.5, blob['accept']) / self.kwargs['walks']
delay = self.nlive // 10 - 1
n_target = g... | Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :code:`kwargs` passed to the evolve method. Not... | LivePointSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :co... | stack_v2_sparse_classes_10k_train_004606 | 25,054 | permissive | [
{
"docstring": "Update the proposal parameters based on the number of accepted steps and MCMC chain length. There are a number of logical checks performed: - if the ACT tracking rwalk method is being used and any parallel process has an empty cache, set the :code:`rebuild` flag to force the cache to rebuild at ... | 2 | stack_v2_sparse_classes_30k_train_007332 | Implement the Python class `LivePointSampler` described below.
Class description:
Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`... | Implement the Python class `LivePointSampler` described below.
Class description:
Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`... | 9c1dda6cc1510692ce4ac75c608de5fae53e971c | <|skeleton|>
class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :code:`kwargs` p... | the_stack_v2_python_sparse | bilby/core/sampler/dynesty_utils.py | khunsang/bilby | train | 0 |
b54f21a78a77347bb51bd99ca33454d928d67af0 | [
"self.cfg_path = cfg_key.split('.')\nself.field = field\nself.translator = translator",
"for key in self.cfg_path[:-1]:\n cfg = cast(ReadOnlyOrderedDict, cfg.get(key))\ndata = cfg.get(self.cfg_path[-1])\nfield.data = self.translator.load(data)",
"for key in self.cfg_path[:-1]:\n cfg = cast(AttrOrderedDict... | <|body_start_0|>
self.cfg_path = cfg_key.split('.')
self.field = field
self.translator = translator
<|end_body_0|>
<|body_start_1|>
for key in self.cfg_path[:-1]:
cfg = cast(ReadOnlyOrderedDict, cfg.get(key))
data = cfg.get(self.cfg_path[-1])
field.data = sel... | Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification. | Setting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optiona... | stack_v2_sparse_classes_10k_train_004607 | 8,067 | no_license | [
{
"docstring": "Creates a setting. Optionally, defines a nontrivial translation between internal and public values.",
"name": "__init__",
"signature": "def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator())"
},
{
"docstring": "Sets the field's value to ... | 3 | stack_v2_sparse_classes_30k_train_003812 | Implement the Python class `Setting` described below.
Class description:
Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification.
Method signatures and docstrings:
- def __init__(self, cfg_key: str, field: Field, translator: SettingTr... | Implement the Python class `Setting` described below.
Class description:
Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification.
Method signatures and docstrings:
- def __init__(self, cfg_key: str, field: Field, translator: SettingTr... | 875482355693c0787716c9b4930942e3e2e712f4 | <|skeleton|>
class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optiona... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Setting:
"""Represents a relation between a node in a lexicon config and a field in a public-facing form that exposes it to the editor for modification."""
def __init__(self, cfg_key: str, field: Field, translator: SettingTranslator=SettingTranslator()):
"""Creates a setting. Optionally, defines ... | the_stack_v2_python_sparse | amanuensis/server/session/settings.py | Jaculabilis/Amanuensis | train | 0 |
43491ccb78ad5d926715538405e405a91ea56563 | [
"app = SequencingExperimentGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_experiment_genomic_file', kf_id))\nreturn SequencingExperimentGenomicFileSchema().jsonify(app)",
"app = SequencingExperimentGenomicFile.query.get(kf_id)\nif app is None:\n abort(... | <|body_start_0|>
app = SequencingExperimentGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.format('sequencing_experiment_genomic_file', kf_id))
return SequencingExperimentGenomicFileSchema().jsonify(app)
<|end_body_0|>
<|body_start_1|>
app = ... | SequencingExperimentGenomicFile API | SequencingExperimentGenomicFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
<|body_0|>
def patch(self, kf_... | stack_v2_sparse_classes_10k_train_004608 | 5,985 | permissive | [
{
"docstring": "Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing sequencing_experiment_genomic_file. Allows partial upd... | 3 | stack_v2_sparse_classes_30k_train_006463 | Implement the Python class `SequencingExperimentGenomicFileAPI` described below.
Class description:
SequencingExperimentGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentG... | Implement the Python class `SequencingExperimentGenomicFileAPI` described below.
Class description:
SequencingExperimentGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentG... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
<|body_0|>
def patch(self, kf_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SequencingExperimentGenomicFileAPI:
"""SequencingExperimentGenomicFile API"""
def get(self, kf_id):
"""Get a sequencing_experiment_genomic_file by id --- template: path: get_by_id.yml properties: resource: SequencingExperimentGenomicFile"""
app = SequencingExperimentGenomicFile.query.get(... | the_stack_v2_python_sparse | dataservice/api/sequencing_experiment_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
effb0514c1d90620f1ed8944e7e8ba35c287f066 | [
"self.user = 'Test User1337'\nself.subject = 'TDT4120'\nself.test_sub = 'TST4' + str(random.randint(0, 2000))",
"user_methods.add_user(self.user, self.subject)\nwith Capturing() as output:\n user_methods.add_user(self.user, self.subject)\nif len(output) > 0:\n self.assertEqual('User already exists', str(out... | <|body_start_0|>
self.user = 'Test User1337'
self.subject = 'TDT4120'
self.test_sub = 'TST4' + str(random.randint(0, 2000))
<|end_body_0|>
<|body_start_1|>
user_methods.add_user(self.user, self.subject)
with Capturing() as output:
user_methods.add_user(self.user, sel... | UserMethodTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
<|body_0|>
def test_user_methods(self):
"""Tests the various methods in user_methods.py as described onwards"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_004609 | 28,630 | no_license | [
{
"docstring": "Sets the test values which are sent to the database :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the various methods in user_methods.py as described onwards",
"name": "test_user_methods",
"signature": "def test_user_methods(self)"
... | 2 | stack_v2_sparse_classes_30k_train_003732 | Implement the Python class `UserMethodTests` described below.
Class description:
Implement the UserMethodTests class.
Method signatures and docstrings:
- def setUp(self): Sets the test values which are sent to the database :return:
- def test_user_methods(self): Tests the various methods in user_methods.py as describ... | Implement the Python class `UserMethodTests` described below.
Class description:
Implement the UserMethodTests class.
Method signatures and docstrings:
- def setUp(self): Sets the test values which are sent to the database :return:
- def test_user_methods(self): Tests the various methods in user_methods.py as describ... | 32bc79ce99ca81cfc6e36435cee3e95dcaf27035 | <|skeleton|>
class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
<|body_0|>
def test_user_methods(self):
"""Tests the various methods in user_methods.py as described onwards"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserMethodTests:
def setUp(self):
"""Sets the test values which are sent to the database :return:"""
self.user = 'Test User1337'
self.subject = 'TDT4120'
self.test_sub = 'TST4' + str(random.randint(0, 2000))
def test_user_methods(self):
"""Tests the various methods... | the_stack_v2_python_sparse | testing_methods.py | Pontius1007/Pekka-Paradise | train | 1 | |
70123cdfe89c079010d8ba51781a0fb58470ab36 | [
"if not os.path.isfile(DATABASE_FILE):\n sys.exit(DATABASE_FILE + ' does not exist.')\nroot = tk.Tk()\nroot.title('IMSIL Input Parameter Editor')\nroot.resizable(False, False)\nself.nb = ttk.Notebook(root, width=900, height=600)\nself.nb.grid(row=0, column=0, sticky='NESW')\nsqlite_master_table = SqliteMaster(DA... | <|body_start_0|>
if not os.path.isfile(DATABASE_FILE):
sys.exit(DATABASE_FILE + ' does not exist.')
root = tk.Tk()
root.title('IMSIL Input Parameter Editor')
root.resizable(False, False)
self.nb = ttk.Notebook(root, width=900, height=600)
self.nb.grid(row=0, c... | The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table. | ImsilInputParameterEditor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImsilInputParameterEditor:
"""The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table."""
def __init__(self, type_of_simulation, input_file_path):
"""In the initialization of the IMSIL Input Parameter Editor a notebook is adde... | stack_v2_sparse_classes_10k_train_004610 | 10,644 | no_license | [
{
"docstring": "In the initialization of the IMSIL Input Parameter Editor a notebook is added to the window. The SqliteMaster class is used to determinate the table names in the database. For each table name a new tab is added to the notebook. Each tab contains a Frame of the class DbFrame. If a path to an inpu... | 3 | stack_v2_sparse_classes_30k_train_000796 | Implement the Python class `ImsilInputParameterEditor` described below.
Class description:
The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table.
Method signatures and docstrings:
- def __init__(self, type_of_simulation, input_file_path): In the initializati... | Implement the Python class `ImsilInputParameterEditor` described below.
Class description:
The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table.
Method signatures and docstrings:
- def __init__(self, type_of_simulation, input_file_path): In the initializati... | 1f4f626e5d4999d4d6ae351944ef508a1e8a4967 | <|skeleton|>
class ImsilInputParameterEditor:
"""The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table."""
def __init__(self, type_of_simulation, input_file_path):
"""In the initialization of the IMSIL Input Parameter Editor a notebook is adde... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImsilInputParameterEditor:
"""The IMSIL Input Parameter Editor consists of a notebook with tabs, where each tab corresponds to a database table."""
def __init__(self, type_of_simulation, input_file_path):
"""In the initialization of the IMSIL Input Parameter Editor a notebook is added to the wind... | the_stack_v2_python_sparse | input_file_generator/main.py | hobler/imsil-gui | train | 1 |
e43b33087eb346d2f5693e879f6276d4787e9565 | [
"N = len(nums)\nA = nums\nleft = [0] * (N + 1)\nfor i in range(1, N + 1):\n left[i] = left[i - 1] + A[i - 1]\n\ndef check(val, numsplit):\n i, v, c = (0, 0, 0)\n while i < N + 1:\n c += 1\n j = bisect.bisect_right(left, v + val, i)\n if i == j:\n return False\n i = j\... | <|body_start_0|>
N = len(nums)
A = nums
left = [0] * (N + 1)
for i in range(1, N + 1):
left[i] = left[i - 1] + A[i - 1]
def check(val, numsplit):
i, v, c = (0, 0, 0)
while i < N + 1:
c += 1
j = bisect.bisect_rig... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_0|>
def splitArray2(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(nums)
... | stack_v2_sparse_classes_10k_train_004611 | 6,363 | permissive | [
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray",
"signature": "def splitArray(self, nums, m)"
},
{
"docstring": ":type nums: List[int] :type m: int :rtype: int",
"name": "splitArray2",
"signature": "def splitArray2(self, nums, m)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int
- def splitArray2(self, nums, m): :type nums: List[int] :type m: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums, m): :type nums: List[int] :type m: int :rtype: int
- def splitArray2(self, nums, m): :type nums: List[int] :type m: int :rtype: int
<|skeleton|>
class... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_0|>
def splitArray2(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def splitArray(self, nums, m):
""":type nums: List[int] :type m: int :rtype: int"""
N = len(nums)
A = nums
left = [0] * (N + 1)
for i in range(1, N + 1):
left[i] = left[i - 1] + A[i - 1]
def check(val, numsplit):
i, v, c = (0, ... | the_stack_v2_python_sparse | leetcode/hard/Split_Array_Largest_Sum.py | shhuan/algorithms | train | 0 | |
02fbfaea4130980ae66479416096ab1480c88f49 | [
"self.cur_idx = 0\nself.next_idx = -1\nself.seats = [False] * N\nself.max_dis = [-1] * N\nself.N = N\nself.count = 0",
"if self.count == 0 or self.next_idx == -1:\n self.next_idx = self.N - 1\n self.seats[self.cur_idx] = True\n for i in range(self.N):\n self.max_dis[i] = i\n self.count += 1\n ... | <|body_start_0|>
self.cur_idx = 0
self.next_idx = -1
self.seats = [False] * N
self.max_dis = [-1] * N
self.N = N
self.count = 0
<|end_body_0|>
<|body_start_1|>
if self.count == 0 or self.next_idx == -1:
self.next_idx = self.N - 1
self.seat... | ExamRoom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.cur_idx = 0
... | stack_v2_sparse_classes_10k_train_004612 | 2,951 | no_license | [
{
"docstring": ":type N: int",
"name": "__init__",
"signature": "def __init__(self, N)"
},
{
"docstring": ":rtype: int",
"name": "seat",
"signature": "def seat(self)"
},
{
"docstring": ":type p: int :rtype: void",
"name": "leave",
"signature": "def leave(self, p)"
}
] | 3 | stack_v2_sparse_classes_30k_train_005913 | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void
<|skeleton|>
class ExamRoom:
def __init__(self, N):
... | c08fdd1556b6dbbdda8ad6210aa0eaa97074ae3b | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExamRoom:
def __init__(self, N):
""":type N: int"""
self.cur_idx = 0
self.next_idx = -1
self.seats = [False] * N
self.max_dis = [-1] * N
self.N = N
self.count = 0
def seat(self):
""":rtype: int"""
if self.count == 0 or self.next_idx ... | the_stack_v2_python_sparse | python/misc/problem3.py | sumitkrm/lang-1 | train | 0 | |
08c3cbab67bb9c6a75f5dbc4f0bca708f0ab3cf2 | [
"self.file_itr = None\nself.path = path\nif os.path.isdir(self.path):\n self.file_itr = glob.glob(self.path + '*')\nself.transform_filename_to_tensor = transform_filename_to_tensor",
"if self.file_itr is not None:\n return map(self.transform_filename_to_tensor, self.file_itr)\nelse:\n return self.transfo... | <|body_start_0|>
self.file_itr = None
self.path = path
if os.path.isdir(self.path):
self.file_itr = glob.glob(self.path + '*')
self.transform_filename_to_tensor = transform_filename_to_tensor
<|end_body_0|>
<|body_start_1|>
if self.file_itr is not None:
r... | An auxiliary class for iterating through a dataset. | CustomIterableDataset | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomIterableDataset:
"""An auxiliary class for iterating through a dataset."""
def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None:
"""Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file.... | stack_v2_sparse_classes_10k_train_004613 | 1,919 | permissive | [
{
"docstring": "Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file. path (str): Path to dataset files. This can be either a path to a directory or a file where input examples are stored.",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_005164 | Implement the Python class `CustomIterableDataset` described below.
Class description:
An auxiliary class for iterating through a dataset.
Method signatures and docstrings:
- def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: Args: transform_filename_to_tensor (Callable): Function to read ... | Implement the Python class `CustomIterableDataset` described below.
Class description:
An auxiliary class for iterating through a dataset.
Method signatures and docstrings:
- def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: Args: transform_filename_to_tensor (Callable): Function to read ... | 945c582cc0b08885c4e2bfecb020abdfac0122f3 | <|skeleton|>
class CustomIterableDataset:
"""An auxiliary class for iterating through a dataset."""
def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None:
"""Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomIterableDataset:
"""An auxiliary class for iterating through a dataset."""
def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None:
"""Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file. path (str): ... | the_stack_v2_python_sparse | captum/concept/_utils/data_iterator.py | pytorch/captum | train | 4,230 |
7ce2c670676ecf81843da0a2677a1db85b021ceb | [
"super().__init__()\nself.hidden_size = hidden_size\nself.k = k\nself.bridge_size = bridge_size\nself.attn_scale = np.sqrt(np.sqrt(self.bridge_size))\nself.W1 = torch.nn.Linear(hidden_size, bridge_size, bias=False)\nself.W2 = torch.nn.Linear(bridge_size, k, bias=False)\nself.act = torch.nn.ReLU()",
"attention_sco... | <|body_start_0|>
super().__init__()
self.hidden_size = hidden_size
self.k = k
self.bridge_size = bridge_size
self.attn_scale = np.sqrt(np.sqrt(self.bridge_size))
self.W1 = torch.nn.Linear(hidden_size, bridge_size, bias=False)
self.W2 = torch.nn.Linear(bridge_size,... | A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf | AttentionBridge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidde... | stack_v2_sparse_classes_10k_train_004614 | 12,242 | permissive | [
{
"docstring": "hidden_size - size of input hidden state k - number of attention heads bridge_size - size of internal feed forward weights (i.e., attention head size)",
"name": "__init__",
"signature": "def __init__(self, hidden_size, k, bridge_size)"
},
{
"docstring": "Project hidden [B x N x H... | 2 | null | Implement the Python class `AttentionBridge` described below.
Class description:
A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf
Method signatures and docstrings:
- def __init__(self, hidden... | Implement the Python class `AttentionBridge` described below.
Class description:
A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf
Method signatures and docstrings:
- def __init__(self, hidden... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidde... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidden state k - n... | the_stack_v2_python_sparse | nemo/collections/nlp/modules/common/transformer/transformer_modules.py | NVIDIA/NeMo | train | 7,957 |
27b5e1bb865c16e4fd297a102855c9e5fda50491 | [
"self.event_message = event_message\nself.percent_finished = percent_finished\nself.remaining_work_count = remaining_work_count\nself.timestamp_seconds = timestamp_seconds",
"if dictionary is None:\n return None\nevent_message = dictionary.get('eventMessage')\npercent_finished = dictionary.get('percentFinished... | <|body_start_0|>
self.event_message = event_message
self.percent_finished = percent_finished
self.remaining_work_count = remaining_work_count
self.timestamp_seconds = timestamp_seconds
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
event_m... | Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of the task attached to this event. remaining_work_count (long|int): Specifies th... | TaskEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskEvent:
"""Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of the task attached to this event. remainin... | stack_v2_sparse_classes_10k_train_004615 | 2,430 | permissive | [
{
"docstring": "Constructor for the TaskEvent class",
"name": "__init__",
"signature": "def __init__(self, event_message=None, percent_finished=None, remaining_work_count=None, timestamp_seconds=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dicti... | 2 | stack_v2_sparse_classes_30k_train_000643 | Implement the Python class `TaskEvent` described below.
Class description:
Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of th... | Implement the Python class `TaskEvent` described below.
Class description:
Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class TaskEvent:
"""Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of the task attached to this event. remainin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TaskEvent:
"""Implementation of the 'TaskEvent' model. Specifies events that clients can attach to a task. Attributes: event_message (string): Specifies the message associated with an event. percent_finished (float): Specifies the completion percentage of the task attached to this event. remaining_work_count ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/task_event.py | cohesity/management-sdk-python | train | 24 |
1f4264f0bdf99b3b1df879ca6dcbcab7b483eefc | [
"ret = list(s)\nwhile 1:\n n = len(ret)\n tmp = list()\n i = 0\n is_last_removed = False\n while i < n - 1:\n if ret[i] == ret[i + 1].swapcase():\n i += 2\n if i == n:\n is_last_removed = True\n else:\n tmp.append(ret[i])\n i +=... | <|body_start_0|>
ret = list(s)
while 1:
n = len(ret)
tmp = list()
i = 0
is_last_removed = False
while i < n - 1:
if ret[i] == ret[i + 1].swapcase():
i += 2
if i == n:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
... | stack_v2_sparse_classes_10k_train_004616 | 2,621 | no_license | [
{
"docstring": ":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code.",
"name": "makeGood2",
"signature": "def... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeGood2(self, s): :type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeGood2(self, s): :type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def makeGood2(self, s):
""":type s: str :rtype: str thought: keep removing adjacent 2 chars until the length does not change. easy - medium 20 - 30 min. corner case of how to handle the last char. 04/03/2022 11:41 Accepted 46 ms 13.6 MB python use stack is much easier code."""
ret = ... | the_stack_v2_python_sparse | N1544_MakeTheStringGreat.py | zerghua/leetcode-python | train | 2 | |
257ebe84ec1b6ef1e5815858fde1fdf29237cd99 | [
"count = dict(Counter(arr))\nval = list(count.values())\nval.sort()\ntmp = list(set(val))\ntmp.sort()\nreturn tmp == val",
"tmp = {}\nfor i in range(len(arr)):\n if arr[i] not in tmp:\n tmp[arr[i]] = 1\n else:\n tmp[arr[i]] += 1\ntmp2 = {}\nfor i in tmp:\n if tmp[i] in tmp2:\n return... | <|body_start_0|>
count = dict(Counter(arr))
val = list(count.values())
val.sort()
tmp = list(set(val))
tmp.sort()
return tmp == val
<|end_body_0|>
<|body_start_1|>
tmp = {}
for i in range(len(arr)):
if arr[i] not in tmp:
tmp[ar... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
<|body_0|>
def uniqueOccurrences2(self, arr: List[int]) -> bool:
"""两个hash。 :param arr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_004617 | 1,094 | no_license | [
{
"docstring": "先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:",
"name": "uniqueOccurrences",
"signature": "def uniqueOccurrences(self, arr: List[int]) -> bool"
},
{
"docstring": "两个hash。 :param arr: :return:",
"name": "uniqueOccurrences2",
"signature": "def uniqueOccurrences2(self, arr: ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueOccurrences(self, arr: List[int]) -> bool: 先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:
- def uniqueOccurrences2(self, arr: List[int]) -> bool: 两个hash。 :param arr: :re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueOccurrences(self, arr: List[int]) -> bool: 先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:
- def uniqueOccurrences2(self, arr: List[int]) -> bool: 两个hash。 :param arr: :re... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
<|body_0|>
def uniqueOccurrences2(self, arr: List[int]) -> bool:
"""两个hash。 :param arr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
"""先统计个数,然后去重,看剩下的是否还与原个数一样 :param arr: :return:"""
count = dict(Counter(arr))
val = list(count.values())
val.sort()
tmp = list(set(val))
tmp.sort()
return tmp == val
def uniqueOccurrenc... | the_stack_v2_python_sparse | 独一无二的出现次数.py | cjrzs/MyLeetCode | train | 8 | |
6c952ce6ef498b3213542d60cb26c72a2df90e6d | [
"self.x = x\nself.fs = fs\nself.N = len(self.x)\nself.K = K",
"X = np.zeros(self.N, dtype=np.complex)\nE = np.zeros(self.N)\nX_K = np.zeros(self.K, dtype=np.complex)\nindex = np.zeros(self.K)\nfor k in range(self.N):\n for n in range(self.N):\n X[k] = X[k] + 1 / np.sqrt(self.N) * self.x[n] * np.exp(-1j ... | <|body_start_0|>
self.x = x
self.fs = fs
self.N = len(self.x)
self.K = K
<|end_body_0|>
<|body_start_1|>
X = np.zeros(self.N, dtype=np.complex)
E = np.zeros(self.N)
X_K = np.zeros(self.K, dtype=np.complex)
index = np.zeros(self.K)
for k in range(s... | idft Inverse Discrete Fourier transform. | dft_K_q16 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dft_K_q16:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, x, fs, K):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT."""
... | stack_v2_sparse_classes_10k_train_004618 | 25,417 | no_license | [
{
"docstring": ":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT.",
"name": "__init__",
"signature": "def __init__(self, x, fs, K)"
},
{
"docstring": "\\\\\\\\\\\\ ... | 2 | stack_v2_sparse_classes_30k_train_002722 | Implement the Python class `dft_K_q16` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, x, fs, K): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the num... | Implement the Python class `dft_K_q16` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, x, fs, K): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the num... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class dft_K_q16:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, x, fs, K):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class dft_K_q16:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, x, fs, K):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency :param K: Input positive integer that determines the number of coeffients used to calculate the iDFT."""
self.x = x
... | the_stack_v2_python_sparse | Inverse Discrete Fourier Transform/iDFT_main.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
3f001039742ae63e79e25bbb0459c1be586de6ba | [
"self.state_size = state_size\nself.action_size = action_size\nself.action_high = action_high\nself.action_low = action_low\nself.layer_sizes = layer_sizes\nself.batch_norm_options = batch_norm_options\nself.dropout_options = dropout_options\nself.learning_rate = learning_rate\nself.logger = logger\nself.build_mode... | <|body_start_0|>
self.state_size = state_size
self.action_size = action_size
self.action_high = action_high
self.action_low = action_low
self.layer_sizes = layer_sizes
self.batch_norm_options = batch_norm_options
self.dropout_options = dropout_options
self... | Standard QNetwork implementation : Actor(Policy) Model | DQNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQNetwork:
"""Standard QNetwork implementation : Actor(Policy) Model"""
def __init__(self, state_size, action_size, action_high=1.0, action_low=0.0, layer_sizes=(64, 64), batch_norm_options=(True, True), dropout_options=(0, 0), learning_rate=0.0001, logger=None):
"""Initialise the Ne... | stack_v2_sparse_classes_10k_train_004619 | 3,237 | no_license | [
{
"docstring": "Initialise the Network Model with given number of layes defined with given size. Parameters ========== :param state_size : size of the state space. :type state_size : int :param action_size : size of the action space. :type action_size : int :param action_high : Upper bound of the action space. ... | 2 | stack_v2_sparse_classes_30k_train_006273 | Implement the Python class `DQNetwork` described below.
Class description:
Standard QNetwork implementation : Actor(Policy) Model
Method signatures and docstrings:
- def __init__(self, state_size, action_size, action_high=1.0, action_low=0.0, layer_sizes=(64, 64), batch_norm_options=(True, True), dropout_options=(0, ... | Implement the Python class `DQNetwork` described below.
Class description:
Standard QNetwork implementation : Actor(Policy) Model
Method signatures and docstrings:
- def __init__(self, state_size, action_size, action_high=1.0, action_low=0.0, layer_sizes=(64, 64), batch_norm_options=(True, True), dropout_options=(0, ... | 4f16a275121fc631420eb2a9708eafec5b91d494 | <|skeleton|>
class DQNetwork:
"""Standard QNetwork implementation : Actor(Policy) Model"""
def __init__(self, state_size, action_size, action_high=1.0, action_low=0.0, layer_sizes=(64, 64), batch_norm_options=(True, True), dropout_options=(0, 0), learning_rate=0.0001, logger=None):
"""Initialise the Ne... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DQNetwork:
"""Standard QNetwork implementation : Actor(Policy) Model"""
def __init__(self, state_size, action_size, action_high=1.0, action_low=0.0, layer_sizes=(64, 64), batch_norm_options=(True, True), dropout_options=(0, 0), learning_rate=0.0001, logger=None):
"""Initialise the Network Model w... | the_stack_v2_python_sparse | DQN-DDQN/Deep-Q-Network/model/DQNetwork.py | YikangGui/Reinforcement-Learning-Algorithms-Zoo | train | 0 |
72e31d633b11055db9dbb8a030d45ec3dd004408 | [
"super(Response, self).__init__(None, True)\nself.name = str(name)\nself.description = str(description)",
"try:\n if 'name' in kwargs:\n self.name = str(kwargs['name'])\n if 'description' in kwargs:\n self.description = str(kwargs['description'])\nexcept Exception as e:\n raise e"
] | <|body_start_0|>
super(Response, self).__init__(None, True)
self.name = str(name)
self.description = str(description)
<|end_body_0|>
<|body_start_1|>
try:
if 'name' in kwargs:
self.name = str(kwargs['name'])
if 'description' in kwargs:
... | Response | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Response:
def __init__(self, name, description=''):
"""Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the response"""
<|body_0|>
def edit(self, **kwargs):
"""Allow edition of name and des... | stack_v2_sparse_classes_10k_train_004620 | 4,739 | no_license | [
{
"docstring": "Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the response",
"name": "__init__",
"signature": "def __init__(self, name, description='')"
},
{
"docstring": "Allow edition of name and description.",
... | 2 | stack_v2_sparse_classes_30k_train_005274 | Implement the Python class `Response` described below.
Class description:
Implement the Response class.
Method signatures and docstrings:
- def __init__(self, name, description=''): Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the respo... | Implement the Python class `Response` described below.
Class description:
Implement the Response class.
Method signatures and docstrings:
- def __init__(self, name, description=''): Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the respo... | 1429b795366b2fd326f9144ba4190ac87bff6dac | <|skeleton|>
class Response:
def __init__(self, name, description=''):
"""Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the response"""
<|body_0|>
def edit(self, **kwargs):
"""Allow edition of name and des... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Response:
def __init__(self, name, description=''):
"""Initiate parent class Response. Attributes ---------- name : str the name of the response description : str the description of the response"""
super(Response, self).__init__(None, True)
self.name = str(name)
self.descriptio... | the_stack_v2_python_sparse | curVersion/optkit/workflow/response.py | zhangyuchao23/MT_optimizer | train | 0 | |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES)\nif org is None:\n response, status = ({'message': 'The requested organization could not be found.'}, http_status.HTTP_404_NOT_FOUND)\nelse:\n response, status = (org.as_dict(), http_status.HTTP_200_OK)\nreturn (response, status)",
"r... | <|body_start_0|>
org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES)
if org is None:
response, status = ({'message': 'The requested organization could not be found.'}, http_status.HTTP_404_NOT_FOUND)
else:
response, status = (org.as_dict(), http_statu... | Resource for managing a single org. | Org | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Org:
"""Resource for managing a single org."""
def get(org_id):
"""Get the org specified by the provided id."""
<|body_0|>
def put(org_id):
"""Update the org specified by the provided id with the request body."""
<|body_1|>
def delete(org_id):
... | stack_v2_sparse_classes_10k_train_004621 | 30,185 | permissive | [
{
"docstring": "Get the org specified by the provided id.",
"name": "get",
"signature": "def get(org_id)"
},
{
"docstring": "Update the org specified by the provided id with the request body.",
"name": "put",
"signature": "def put(org_id)"
},
{
"docstring": "Inactivates the org i... | 4 | null | Implement the Python class `Org` described below.
Class description:
Resource for managing a single org.
Method signatures and docstrings:
- def get(org_id): Get the org specified by the provided id.
- def put(org_id): Update the org specified by the provided id with the request body.
- def delete(org_id): Inactivate... | Implement the Python class `Org` described below.
Class description:
Resource for managing a single org.
Method signatures and docstrings:
- def get(org_id): Get the org specified by the provided id.
- def put(org_id): Update the org specified by the provided id with the request body.
- def delete(org_id): Inactivate... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class Org:
"""Resource for managing a single org."""
def get(org_id):
"""Get the org specified by the provided id."""
<|body_0|>
def put(org_id):
"""Update the org specified by the provided id with the request body."""
<|body_1|>
def delete(org_id):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Org:
"""Resource for managing a single org."""
def get(org_id):
"""Get the org specified by the provided id."""
org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES)
if org is None:
response, status = ({'message': 'The requested organization could no... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
402ecd186a749ac08e36f2967067feb7d659e4a6 | [
"self.login.loginFunc()\nself.driver.implicitly_wait(30)\nself.findElement(*self.files1_loc).click()\nself.findElement(*self.shareBtn_loc).click()\nsleep(0.5)\nself.findElement(*self.shareInput_loc).send_keys('userdemo')\nsleep(1)\nself.findElement(*self.shareSelect_loc).click()\nself.driver.implicitly_wait(10)\nsh... | <|body_start_0|>
self.login.loginFunc()
self.driver.implicitly_wait(30)
self.findElement(*self.files1_loc).click()
self.findElement(*self.shareBtn_loc).click()
sleep(0.5)
self.findElement(*self.shareInput_loc).send_keys('userdemo')
sleep(1)
self.findElemen... | 共享功能测试 | ShareTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShareTest:
"""共享功能测试"""
def test_01shareuser(self):
"""分享文件给用户"""
<|body_0|>
def test_02sharegroup(self):
"""分享给用户组"""
<|body_1|>
def test_03sharedepartment(self):
"""分享文件给部门"""
<|body_2|>
def test_04treeshare(self):
"""树... | stack_v2_sparse_classes_10k_train_004622 | 7,193 | no_license | [
{
"docstring": "分享文件给用户",
"name": "test_01shareuser",
"signature": "def test_01shareuser(self)"
},
{
"docstring": "分享给用户组",
"name": "test_02sharegroup",
"signature": "def test_02sharegroup(self)"
},
{
"docstring": "分享文件给部门",
"name": "test_03sharedepartment",
"signature": ... | 6 | stack_v2_sparse_classes_30k_train_001466 | Implement the Python class `ShareTest` described below.
Class description:
共享功能测试
Method signatures and docstrings:
- def test_01shareuser(self): 分享文件给用户
- def test_02sharegroup(self): 分享给用户组
- def test_03sharedepartment(self): 分享文件给部门
- def test_04treeshare(self): 树形分享给内部用户
- def test_05sharecancel(self): 取消分享
- def... | Implement the Python class `ShareTest` described below.
Class description:
共享功能测试
Method signatures and docstrings:
- def test_01shareuser(self): 分享文件给用户
- def test_02sharegroup(self): 分享给用户组
- def test_03sharedepartment(self): 分享文件给部门
- def test_04treeshare(self): 树形分享给内部用户
- def test_05sharecancel(self): 取消分享
- def... | e7e6ad0187fb13e798aad230682c46125df26be9 | <|skeleton|>
class ShareTest:
"""共享功能测试"""
def test_01shareuser(self):
"""分享文件给用户"""
<|body_0|>
def test_02sharegroup(self):
"""分享给用户组"""
<|body_1|>
def test_03sharedepartment(self):
"""分享文件给部门"""
<|body_2|>
def test_04treeshare(self):
"""树... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShareTest:
"""共享功能测试"""
def test_01shareuser(self):
"""分享文件给用户"""
self.login.loginFunc()
self.driver.implicitly_wait(30)
self.findElement(*self.files1_loc).click()
self.findElement(*self.shareBtn_loc).click()
sleep(0.5)
self.findElement(*self.shareI... | the_stack_v2_python_sparse | retail/test_case/i_share_sta.py | huenping/Security_WP_retail | train | 2 |
c5fb848c63bea4cfe0e1da7984780e4f83828bb8 | [
"self.primary_language = primary_language\nself.secondary_language = secondary_language\nself.xml_signature = xml_signature\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nprimary_language = dictionary.get('PrimaryLanguage')\nsecondary_language = dictionary.get('Sec... | <|body_start_0|>
self.primary_language = primary_language
self.secondary_language = secondary_language
self.xml_signature = xml_signature
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
pri... | Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_signature (string): Xml package signa... | TemplateWithIdPreview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op... | stack_v2_sparse_classes_10k_train_004623 | 2,616 | permissive | [
{
"docstring": "Constructor for the TemplateWithIdPreview class",
"name": "__init__",
"signature": "def __init__(self, primary_language=None, secondary_language=None, xml_signature=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | stack_v2_sparse_classes_30k_train_003210 | Implement the Python class `TemplateWithIdPreview` described below.
Class description:
Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second... | Implement the Python class `TemplateWithIdPreview` described below.
Class description:
Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_s... | the_stack_v2_python_sparse | idfy_rest_client/models/template_with_id_preview.py | dealflowteam/Idfy | train | 0 |
ffb09266bc0cf30b21fe712589080e8dc9ae66f3 | [
"stack, res = ([], 0)\nfor i in range(len(height)):\n while stack and height[stack[-1]] < height[i]:\n bottom = stack[-1]\n stack.pop()\n res += 0 if not stack else (min(height[i], height[stack[-1]]) - height[bottom]) * (i - stack[-1] - 1)\n stack.append(i)\nreturn res",
"if not height:... | <|body_start_0|>
stack, res = ([], 0)
for i in range(len(height)):
while stack and height[stack[-1]] < height[i]:
bottom = stack[-1]
stack.pop()
res += 0 if not stack else (min(height[i], height[stack[-1]]) - height[bottom]) * (i - stack[-1] - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trapWith2Pointers(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack, res = ([], 0)
for i in ... | stack_v2_sparse_classes_10k_train_004624 | 1,412 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trapWith2Pointers",
"signature": "def trapWith2Pointers(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000362 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trapWith2Pointers(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trapWith2Pointers(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def trap... | 622b20dd4faa8fb94e77f935579a4ddc91793545 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trapWith2Pointers(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
stack, res = ([], 0)
for i in range(len(height)):
while stack and height[stack[-1]] < height[i]:
bottom = stack[-1]
stack.pop()
res += 0 if not stack ... | the_stack_v2_python_sparse | trapWater.py | guangyw/leetcode_python | train | 0 | |
3bb8a88a44f85f67263e33c347de5260be8c87ca | [
"super(SampleModifier, self).__init__(modifier_dict)\nself.modifier_dict = modifier_dict\nself.default = default\nself.samples: List[str] = list(self.modifier_dict.keys())",
"if sample in self.samples:\n return self.modifier_dict[sample]\nelif self.default is not None:\n return self.default\nelse:\n rais... | <|body_start_0|>
super(SampleModifier, self).__init__(modifier_dict)
self.modifier_dict = modifier_dict
self.default = default
self.samples: List[str] = list(self.modifier_dict.keys())
<|end_body_0|>
<|body_start_1|>
if sample in self.samples:
return self.modifier_di... | SampleModifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter ... | stack_v2_sparse_classes_10k_train_004625 | 3,538 | permissive | [
{
"docstring": "A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter should be modified based on the sample. default: If set, the default is used for all sample not specified in the modifier dict. Defa... | 2 | stack_v2_sparse_classes_30k_train_000705 | Implement the Python class `SampleModifier` described below.
Class description:
Implement the SampleModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Sample Modifier is a Modifier, that modifies the configurat... | Implement the Python class `SampleModifier` described below.
Class description:
Implement the SampleModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Sample Modifier is a Modifier, that modifies the configurat... | 229fac41ec8fb34fc4ae9584b1ea428ef95b914e | <|skeleton|>
class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter should be modi... | the_stack_v2_python_sparse | code_generation/modifiers.py | KIT-CMS/CROWN | train | 6 | |
2a4ce08fa1df750db7bae3280b585a4edea41da7 | [
"_id = request.form.get('id', request.args.get('id', None))\nif _id is None:\n return {'success': False, 'message': 'id must be supplied', 'result': None}\ncontainer = mozart_es.get_by_id(index=CONTAINERS_INDEX, id=_id, ignore=404)\nif container['found'] is False:\n return ({'success': False, 'message': 'cont... | <|body_start_0|>
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return {'success': False, 'message': 'id must be supplied', 'result': None}
container = mozart_es.get_by_id(index=CONTAINERS_INDEX, id=_id, ignore=404)
if container['found'] is False:
... | Container Rest APIs (GET, POST, DELETE) | Containers | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
<|body_0|>
def post(self):
"""Add a container specification to Mozart"""
<|body_1|>
def delete(self):
"""Remove container based ... | stack_v2_sparse_classes_10k_train_004626 | 13,931 | permissive | [
{
"docstring": "Get information on container by ID",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a container specification to Mozart",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Remove container based on ID",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_005690 | Implement the Python class `Containers` described below.
Class description:
Container Rest APIs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Get information on container by ID
- def post(self): Add a container specification to Mozart
- def delete(self): Remove container based on ID | Implement the Python class `Containers` described below.
Class description:
Container Rest APIs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Get information on container by ID
- def post(self): Add a container specification to Mozart
- def delete(self): Remove container based on ID
<|skelet... | c238340fafd96a9b92d92e544d0892a354c1ca32 | <|skeleton|>
class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
<|body_0|>
def post(self):
"""Add a container specification to Mozart"""
<|body_1|>
def delete(self):
"""Remove container based ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return {'success': False, 'message': 'id must be supplied', 'result': None}
... | the_stack_v2_python_sparse | mozart/services/api_v02/specs.py | hysds/mozart | train | 1 |
794b80ae10425635e439c54840b72901b7ec5117 | [
"from jizhipy.Basic import Time\nkey = ['PIXTYPE', 'DATECREA', 'ORDERING', 'NSIDE', 'COORDSYS']\nvalue = ['HEALPIX', Time(1), ordering.upper(), nside, coordsys.upper()]\ncomment = ['HEALPIX pixelisation', 'Creation date of this file', 'Pixel ordering scheme, RING or NESTED', 'Healpix resolution parameter', 'Coordin... | <|body_start_0|>
from jizhipy.Basic import Time
key = ['PIXTYPE', 'DATECREA', 'ORDERING', 'NSIDE', 'COORDSYS']
value = ['HEALPIX', Time(1), ordering.upper(), nside, coordsys.upper()]
comment = ['HEALPIX pixelisation', 'Creation date of this file', 'Pixel ordering scheme, RING or NESTED',... | Healpix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Healpix:
def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None):
"""nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map ... | stack_v2_sparse_classes_10k_train_004627 | 16,919 | no_license | [
{
"docstring": "nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map in arcmin return: [key, value, comment]",
"name": "HealpixHeader",
"signature": "def HealpixHeader(self, nside, o... | 2 | stack_v2_sparse_classes_30k_train_007240 | Implement the Python class `Healpix` described below.
Class description:
Implement the Healpix class.
Method signatures and docstrings:
- def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq:... | Implement the Python class `Healpix` described below.
Class description:
Implement the Healpix class.
Method signatures and docstrings:
- def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None): nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq:... | b49777105a76b5ae03555a9f93f116454c8245a9 | <|skeleton|>
class Healpix:
def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None):
"""nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Healpix:
def HealpixHeader(self, nside, ordering, coordsys, freq=None, unit=None, epoch=None, beamsize=None):
"""nside: 2**n ordering: 'RING', 'NESTED' coordsys: 'EQUATORIAL', 'GALACTIC' freq: in MHz unit: Unit of the healpix map pixel value beamsize: Observation FWHM of the healpix map in arcmin retu... | the_stack_v2_python_sparse | Astro/Healpix.py | jizhi/jizhipy | train | 1 | |
2256c3809d3279306e2c4e56d5dc511abdd05162 | [
"super(NormLayer, self).__init__()\nself.n_channels = n_channels\nself.scale = scale\nself.epsilon = epsilon\nself.weights = nn.Parameter(torch.Tensor(self.n_channels))\nself.weights.data *= 0.0\nself.weights.data += self.scale",
"norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.epsilon\nx = x / norm * self... | <|body_start_0|>
super(NormLayer, self).__init__()
self.n_channels = n_channels
self.scale = scale
self.epsilon = epsilon
self.weights = nn.Parameter(torch.Tensor(self.n_channels))
self.weights.data *= 0.0
self.weights.data += self.scale
<|end_body_0|>
<|body_sta... | Implementation of the L2 Norm Layer used in the S3FD paper. | NormLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used... | stack_v2_sparse_classes_10k_train_004628 | 6,948 | no_license | [
{
"docstring": "Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used for the weighted L2-norm, by default 1.0. epsilon : float, optional Parameter that prevents division by zero, by default 1e-10. Returns ------- None"... | 2 | stack_v2_sparse_classes_30k_train_000867 | Implement the Python class `NormLayer` described below.
Class description:
Implementation of the L2 Norm Layer used in the S3FD paper.
Method signatures and docstrings:
- def __init__(self, n_channels, scale=1.0, epsilon=1e-10): Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channe... | Implement the Python class `NormLayer` described below.
Class description:
Implementation of the L2 Norm Layer used in the S3FD paper.
Method signatures and docstrings:
- def __init__(self, n_channels, scale=1.0, epsilon=1e-10): Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channe... | a7c30481822ecb945e3ff6ad184d104361a40ed1 | <|skeleton|>
class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NormLayer:
"""Implementation of the L2 Norm Layer used in the S3FD paper."""
def __init__(self, n_channels, scale=1.0, epsilon=1e-10):
"""Instantiates a L2 Norm layer. Parameters ---------- n_channels : int The number of channels in the input. scale : float, optional The scaling used for the weig... | the_stack_v2_python_sparse | cheapfake/FAN/detectors/SF3DNet.py | hu-simon/cheapfake | train | 0 |
b92d2293ceab5e38c594bc117870c95af48b82ec | [
"super().__init__()\nself.size = size\nself.padding_idx = padding_idx\nself.smoothing = smoothing\nself.confidence = 1.0 - smoothing\nself.normalize_length = normalize_length\nself.criterion = nn.KLDivLoss(reduction='none')",
"B, T, D = x.shape\nassert D == self.size\nx = x.reshape((-1, self.size))\ntarget = targ... | <|body_start_0|>
super().__init__()
self.size = size
self.padding_idx = padding_idx
self.smoothing = smoothing
self.confidence = 1.0 - smoothing
self.normalize_length = normalize_length
self.criterion = nn.KLDivLoss(reduction='none')
<|end_body_0|>
<|body_start_1... | Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothing=0.1 [0,1,2] -> [ [0.9, 0.05, 0.... | LabelSmoothingLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ... | stack_v2_sparse_classes_10k_train_004629 | 6,854 | permissive | [
{
"docstring": "Label-smoothing loss. Args: size (int): the number of class padding_idx (int): padding class id which will be ignored for loss smoothing (float): smoothing rate (0.0 means the conventional CE) normalize_length (bool): True, normalize loss by sequence length; False, normalize loss by batch size. ... | 2 | null | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class LabelSmoothingLoss:
"""Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothin... | the_stack_v2_python_sparse | paddlespeech/s2t/modules/loss.py | anniyanvr/DeepSpeech-1 | train | 0 |
72bf3ca78c47c383c695c4644f4b366813895f9d | [
"if bool(vocab_path) == bool(spm_model_path):\n raise ValueError('Exactly 1 of `vocab_path` or `spm_model_path` must be specified, not both.')\nself.vocab_path = vocab_path\nself.do_lower_case = do_lower_case\nself.spm_model_path = spm_model_path\nself.generate_document_ids = generate_document_ids",
"def file_... | <|body_start_0|>
if bool(vocab_path) == bool(spm_model_path):
raise ValueError('Exactly 1 of `vocab_path` or `spm_model_path` must be specified, not both.')
self.vocab_path = vocab_path
self.do_lower_case = do_lower_case
self.spm_model_path = spm_model_path
self.gener... | PTransform for reading text files into tokenized documents. | ReadFilesToTokenizedDocuments | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadFilesToTokenizedDocuments:
"""PTransform for reading text files into tokenized documents."""
def __init__(self, vocab_path=None, do_lower_case=True, spm_model_path=None, generate_document_ids=False):
"""Initialization. Args: vocab_path: Path to the BERT vocabulary file to use wit... | stack_v2_sparse_classes_10k_train_004630 | 24,441 | permissive | [
{
"docstring": "Initialization. Args: vocab_path: Path to the BERT vocabulary file to use with the BERT tokenizer. Leave as None or set to empty string if using `spm_model_path` instead. do_lower_case: Whether to lowercase all text for BERT tokenization (default True). Must match assumption in `vocab_path`. Ign... | 2 | stack_v2_sparse_classes_30k_train_004870 | Implement the Python class `ReadFilesToTokenizedDocuments` described below.
Class description:
PTransform for reading text files into tokenized documents.
Method signatures and docstrings:
- def __init__(self, vocab_path=None, do_lower_case=True, spm_model_path=None, generate_document_ids=False): Initialization. Args... | Implement the Python class `ReadFilesToTokenizedDocuments` described below.
Class description:
PTransform for reading text files into tokenized documents.
Method signatures and docstrings:
- def __init__(self, vocab_path=None, do_lower_case=True, spm_model_path=None, generate_document_ids=False): Initialization. Args... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ReadFilesToTokenizedDocuments:
"""PTransform for reading text files into tokenized documents."""
def __init__(self, vocab_path=None, do_lower_case=True, spm_model_path=None, generate_document_ids=False):
"""Initialization. Args: vocab_path: Path to the BERT vocabulary file to use wit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReadFilesToTokenizedDocuments:
"""PTransform for reading text files into tokenized documents."""
def __init__(self, vocab_path=None, do_lower_case=True, spm_model_path=None, generate_document_ids=False):
"""Initialization. Args: vocab_path: Path to the BERT vocabulary file to use with the BERT to... | the_stack_v2_python_sparse | readtwice/data_utils/beam_utils.py | Jimmy-INL/google-research | train | 1 |
c445f16c9535c0bdf82a7983e7ac196b2e9b2ac0 | [
"n, m = (len(text1), len(text2))\ndp = [[0] * (m + 1) for _ in range(n + 1)]\nfor i in range(n):\n for j in range(m):\n dp[i + 1][j + 1] = max(dp[i][j] + int(text1[i] == text2[j]), dp[i][j + 1], dp[i + 1][j])\nreturn dp[-1][-1]",
"n, m = (len(text1), len(text2))\nif n < m:\n n, m = (m, n)\n text2,... | <|body_start_0|>
n, m = (len(text1), len(text2))
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
dp[i + 1][j + 1] = max(dp[i][j] + int(text1[i] == text2[j]), dp[i][j + 1], dp[i + 1][j])
return dp[-1][-1]
<|end_body_0|>
<|body_... | [1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""[1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)"""
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j-1],dp[i][j] = dp[i-1][j-1] + 1,否则dp[i][j] = dp[i-1][j-1]... | stack_v2_sparse_classes_10k_train_004631 | 1,910 | no_license | [
{
"docstring": "思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j-1],dp[i][j] = dp[i-1][j-1] + 1,否则dp[i][j] = dp[i-1][j-1]",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1: str, text2: str) -> int"
},
{
"docstring": "压缩一下dp数组,用一维数组即可,想象成一... | 2 | null | Implement the Python class `Solution` described below.
Class description:
[1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: 思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j... | Implement the Python class `Solution` described below.
Class description:
[1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1: str, text2: str) -> int: 思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class Solution:
"""[1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)"""
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j-1],dp[i][j] = dp[i-1][j-1] + 1,否则dp[i][j] = dp[i-1][j-1]... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""[1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)"""
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""思路:动态规划,dp[i][j]表示text[:i]与text[:j]的lcs 如果text1[i-1] == text2[j-1],dp[i][j] = dp[i-1][j-1] + 1,否则dp[i][j] = dp[i-1][j-1]"""
n... | the_stack_v2_python_sparse | leetcode/901-1200/1143.py | Rivarrl/leetcode_python | train | 3 |
e7ad6610a556b0cbb2715f8394a45880309113cf | [
"self.baud = baud\nself.timeout = timeout\nself.pid = pid\nself.port = '/dev/youbot/gripper'",
"try:\n self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)\nexcept Exception as a:\n rospy.logerr(a)\n rospy.logerr('Please check the port {}'.format(self.port))",
"self.board.flushInput()... | <|body_start_0|>
self.baud = baud
self.timeout = timeout
self.pid = pid
self.port = '/dev/youbot/gripper'
<|end_body_0|>
<|body_start_1|>
try:
self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)
except Exception as a:
rospy.loge... | SerialInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_10k_train_004632 | 2,489 | no_license | [
{
"docstring": "This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the microcontroller @param timeout -- timeout after which... | 4 | stack_v2_sparse_classes_30k_train_006662 | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | 8129cd48351159508cae3438a8b8b3d776c771ca | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the... | the_stack_v2_python_sparse | mir_manipulation/mir_gripper_controller/ros/scripts/serial_interface.py | b-it-bots/mas_industrial_robotics | train | 25 | |
16465b38ee303d2cc803fbcc06584a3357ac0c66 | [
"memo = {}\n\ndef dp(k, n):\n if (k, n) not in memo:\n if not n:\n ans = 0\n elif k == 1:\n ans = n\n else:\n low, high = (1, n)\n while low + 1 < high:\n temp = (low + high) // 2\n t1 = dp(k - 1, temp - 1)\n ... | <|body_start_0|>
memo = {}
def dp(k, n):
if (k, n) not in memo:
if not n:
ans = 0
elif k == 1:
ans = n
else:
low, high = (1, n)
while low + 1 < high:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
<|body_0|>
def super_egg_drop_v2(cls, k: int, n: int) -> int:
"""O(kn), O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
memo = {}
def dp(k, n):
... | stack_v2_sparse_classes_10k_train_004633 | 3,072 | no_license | [
{
"docstring": "O(kn*logn), O(kn)",
"name": "super_egg_drop",
"signature": "def super_egg_drop(cls, k: int, n: int) -> int"
},
{
"docstring": "O(kn), O(n)",
"name": "super_egg_drop_v2",
"signature": "def super_egg_drop_v2(cls, k: int, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_000415 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def super_egg_drop(cls, k: int, n: int) -> int: O(kn*logn), O(kn)
- def super_egg_drop_v2(cls, k: int, n: int) -> int: O(kn), O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def super_egg_drop(cls, k: int, n: int) -> int: O(kn*logn), O(kn)
- def super_egg_drop_v2(cls, k: int, n: int) -> int: O(kn), O(n)
<|skeleton|>
class Solution:
def super_eg... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
<|body_0|>
def super_egg_drop_v2(cls, k: int, n: int) -> int:
"""O(kn), O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
memo = {}
def dp(k, n):
if (k, n) not in memo:
if not n:
ans = 0
elif k == 1:
ans = n
else:
... | the_stack_v2_python_sparse | 02-算法思想/数学/887.鸡蛋掉落(H).py | jh-lau/leetcode_in_python | train | 0 | |
d01e533c15be3ffa5d7717e6909ec649a258309c | [
"self.__ops = ops\nself.__nops = len(ops)\nfor iop in range(self.__nops):\n if not isinstance(self.__ops[iop], operator):\n raise Exception('Elements of ops list must be of type operator')\nif self.__nops != len(dims):\n raise Exception('Number of dimensions (%d) must equal number of operators (%d)' % ... | <|body_start_0|>
self.__ops = ops
self.__nops = len(ops)
for iop in range(self.__nops):
if not isinstance(self.__ops[iop], operator):
raise Exception('Elements of ops list must be of type operator')
if self.__nops != len(dims):
raise Exception('Num... | A chain operator | chainop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class chainop:
"""A chain operator"""
def __init__(self, ops, dims):
"""chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},.... | stack_v2_sparse_classes_10k_train_004634 | 13,837 | no_license | [
{
"docstring": "chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},...] Note that the operators will be applied in the order they come in the list... | 4 | stack_v2_sparse_classes_30k_train_003634 | Implement the Python class `chainop` described below.
Class description:
A chain operator
Method signatures and docstrings:
- def __init__(self, ops, dims): chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of th... | Implement the Python class `chainop` described below.
Class description:
A chain operator
Method signatures and docstrings:
- def __init__(self, ops, dims): chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of th... | 32a303eddd13385d8778b8bb3b4fbbfbe78bea51 | <|skeleton|>
class chainop:
"""A chain operator"""
def __init__(self, ops, dims):
"""chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class chainop:
"""A chain operator"""
def __init__(self, ops, dims):
"""chainop constructor Parameters: ops - a list of operators to be chained dims - a list of dictionaries that contain the dimensions of the inputs and outputs of the arrays For example dims = [{'nrows': 10, 'ncols': 10},...] Note that... | the_stack_v2_python_sparse | opt/linopt/combops.py | ke0m/scaas | train | 2 |
e083f14572016be6f50ad39511fe4df16569b19b | [
"def isPalindrome(i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i = i + 1\n j = j - 1\n return True\ni = 0\nj = len(s) - 1\nwhile i < j:\n if s[i] != s[j]:\n return isPalindrome(i + 1, j) or isPalindrome(i, j - 1)\n i += 1\n j -= 1\nreturn True",
"... | <|body_start_0|>
def isPalindrome(i, j):
while i < j:
if s[i] != s[j]:
return False
i = i + 1
j = j - 1
return True
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
"""leetcode最快实例 :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_004635 | 1,167 | no_license | [
{
"docstring": "给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
},
{
"docstring": "leetcode最快实例 :param s: :return:",
"name": "validPalindrome1",
"signature": "def ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): 给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool
- def validPalindrome1(self, s): leetcode最快实例 :p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): 给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool
- def validPalindrome1(self, s): leetcode最快实例 :p... | b2228230c90d7c91b0a40399fa631520c290b61d | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
"""leetcode最快实例 :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
def isPalindrome(i, j):
while i < j:
if s[i] != s[j]:
return False
i = i + 1
... | the_stack_v2_python_sparse | 字符串/判断回文字符串2_680.py | Xiaoctw/LeetCode1_python | train | 0 | |
6269d8d4f5120b1c608477a7e1a9793cc79edd40 | [
"layout_section_slug = request.GET.get('layout_section_slug', None)\nlayout_template_slug = request.GET.get('layout_template_slug', None)\nplugin_relation_default = request.GET.getlist('plugin_relation_default[]')\nplugin_relation_default_placeholder = request.GET.getlist('plugin_relation_default_placeholder[]')\ni... | <|body_start_0|>
layout_section_slug = request.GET.get('layout_section_slug', None)
layout_template_slug = request.GET.get('layout_template_slug', None)
plugin_relation_default = request.GET.getlist('plugin_relation_default[]')
plugin_relation_default_placeholder = request.GET.getlist('p... | Manage the layout of a placeholder. | LayoutListView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
<|body_0|>
def post(self, request):
"""Change the page layout"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004636 | 5,299 | permissive | [
{
"docstring": "Change and preview the layout of a placeholder",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Change the page layout",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002774 | Implement the Python class `LayoutListView` described below.
Class description:
Manage the layout of a placeholder.
Method signatures and docstrings:
- def get(self, request): Change and preview the layout of a placeholder
- def post(self, request): Change the page layout | Implement the Python class `LayoutListView` described below.
Class description:
Manage the layout of a placeholder.
Method signatures and docstrings:
- def get(self, request): Change and preview the layout of a placeholder
- def post(self, request): Change the page layout
<|skeleton|>
class LayoutListView:
"""Ma... | 00947315b5bca4977f1de40ddb951f843c345532 | <|skeleton|>
class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
<|body_0|>
def post(self, request):
"""Change the page layout"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
layout_section_slug = request.GET.get('layout_section_slug', None)
layout_template_slug = request.GET.get('layout_template_slug', None)
pl... | the_stack_v2_python_sparse | ionyweb/administration/views/manifest.py | ionyse/ionyweb | train | 4 |
a5948168972f42dccf896a7f81528cbd5a4f3ae9 | [
"self.gov = request.args.get('gov', '')\nself.dep = request.args.get('govtype', '')\nself.relation = request.args.get('dep', '')\nself.govtype = request.args.get('deptype', 'word')\nself.deptype = request.args.get('relation', 'word')\ntry:\n self.phrases = json.loads(str(request.args['phrases']))\n self.metad... | <|body_start_0|>
self.gov = request.args.get('gov', '')
self.dep = request.args.get('govtype', '')
self.relation = request.args.get('dep', '')
self.govtype = request.args.get('deptype', 'word')
self.deptype = request.args.get('relation', 'word')
try:
self.phra... | Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype (str): relation (str): phrases (JSON): Required. metadata (JSON): Required. searches ... | GetAssociatedWords | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAssociatedWords:
"""Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype (str): relation (str): phrases (JSON): ... | stack_v2_sparse_classes_10k_train_004637 | 3,365 | no_license | [
{
"docstring": "Initialize variables necessary for the GetAssociatedUsers view.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a JSON response to the request.",
"name": "dispatch_request",
"signature": "def dispatch_request(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_002550 | Implement the Python class `GetAssociatedWords` described below.
Class description:
Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype ... | Implement the Python class `GetAssociatedWords` described below.
Class description:
Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype ... | 93b90e6a8592a26c6efa09ea5f5aa4fab044f9d7 | <|skeleton|>
class GetAssociatedWords:
"""Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype (str): relation (str): phrases (JSON): ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetAssociatedWords:
"""Return adjectives, nouns, and verbs with high TF-IDF scores that tend to occur within 10 sentences of the given word. The expected url arguments are documented below. Keyword Arguments: phrases (str): govtype (str): dep (str): deptype (str): relation (str): phrases (JSON): Required. met... | the_stack_v2_python_sparse | app/wordseer/views/getassociatedwords.py | xiaobaozi34/wordseer | train | 0 |
3ba5bd285b047b66afcbf116c1e1beb32b00dc53 | [
"try:\n return runJasperReportEditor(prj_filename)\nexcept:\n log_func.fatal(u'Error opening JasperReport project file <%s>' % prj_filename)\nreturn False",
"try:\n if default_prj_filename is None:\n default_prj_filename = DEFAULT_REPORT_LANDSCAPE_FILENAME\n if new_prj_filename is None:\n ... | <|body_start_0|>
try:
return runJasperReportEditor(prj_filename)
except:
log_func.fatal(u'Error opening JasperReport project file <%s>' % prj_filename)
return False
<|end_body_0|>
<|body_start_1|>
try:
if default_prj_filename is None:
... | JasperReport report generator manager. | iqJasperReportManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqJasperReportManager:
"""JasperReport report generator manager."""
def openProject(self, prj_filename):
"""Open project file. :param prj_filename: The full name of the project file. :return: True/False"""
<|body_0|>
def createProject(self, default_prj_filename=None, new... | stack_v2_sparse_classes_10k_train_004638 | 5,611 | no_license | [
{
"docstring": "Open project file. :param prj_filename: The full name of the project file. :return: True/False",
"name": "openProject",
"signature": "def openProject(self, prj_filename)"
},
{
"docstring": "Create a new project file. :param default_prj_filename: The default project file name. :pa... | 3 | null | Implement the Python class `iqJasperReportManager` described below.
Class description:
JasperReport report generator manager.
Method signatures and docstrings:
- def openProject(self, prj_filename): Open project file. :param prj_filename: The full name of the project file. :return: True/False
- def createProject(self... | Implement the Python class `iqJasperReportManager` described below.
Class description:
JasperReport report generator manager.
Method signatures and docstrings:
- def openProject(self, prj_filename): Open project file. :param prj_filename: The full name of the project file. :return: True/False
- def createProject(self... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqJasperReportManager:
"""JasperReport report generator manager."""
def openProject(self, prj_filename):
"""Open project file. :param prj_filename: The full name of the project file. :return: True/False"""
<|body_0|>
def createProject(self, default_prj_filename=None, new... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class iqJasperReportManager:
"""JasperReport report generator manager."""
def openProject(self, prj_filename):
"""Open project file. :param prj_filename: The full name of the project file. :return: True/False"""
try:
return runJasperReportEditor(prj_filename)
except:
... | the_stack_v2_python_sparse | iq/editor/jasper_report/jasperreport_manager.py | XHermitOne/iq_framework | train | 1 |
c12917949c5cb349cdd7d91554b4297b4bb23946 | [
"if not date == None:\n date = '%sT%sZ' % (date, time)\nreturn date",
"if not datetime == None and 'T' in datetime:\n datetime = datetime.split('T')[0]\nreturn datetime"
] | <|body_start_0|>
if not date == None:
date = '%sT%sZ' % (date, time)
return date
<|end_body_0|>
<|body_start_1|>
if not datetime == None and 'T' in datetime:
datetime = datetime.split('T')[0]
return datetime
<|end_body_1|>
| StringExtensions | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns... | stack_v2_sparse_classes_10k_train_004639 | 1,907 | permissive | [
{
"docstring": "Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns: A string representation of a datetime in the following format YYYY-MM-DDTHH:mm:SSZ"... | 2 | null | Implement the Python class `StringExtensions` described below.
Class description:
Implement the StringExtensions class.
Method signatures and docstrings:
- def convertDateStrToDateTimeStr(date, time='00:00:00'): Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Ar... | Implement the Python class `StringExtensions` described below.
Class description:
Implement the StringExtensions class.
Method signatures and docstrings:
- def convertDateStrToDateTimeStr(date, time='00:00:00'): Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Ar... | b596df09c52511e2e0c0987f6245aa4607190dd0 | <|skeleton|>
class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StringExtensions:
def convertDateStrToDateTimeStr(date, time='00:00:00'):
"""Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ) Args: date: the date as a string to be converted time: the time as a string to be added to the date Returns: A string rep... | the_stack_v2_python_sparse | starthinker/task/traffic/class_extensions.py | google/starthinker | train | 167 | |
efe9295488035c5fd21f274cc9bf5e793431fcc7 | [
"size = len(s)\nif size == 0:\n return ''\nlongest_palindrome = 1\nlongest_palindrome_str = s[0]\nfor i in range(size):\n palindrome_odd, odd_len = self.__center_spread(s, size, i, i)\n palindrome_even, even_len = self.__center_spread(s, size, i, i + 1)\n cur_max_sub = palindrome_odd if odd_len >= even_... | <|body_start_0|>
size = len(s)
if size == 0:
return ''
longest_palindrome = 1
longest_palindrome_str = s[0]
for i in range(size):
palindrome_odd, odd_len = self.__center_spread(s, size, i, i)
palindrome_even, even_len = self.__center_spread(s, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
<|body_0|>
def __center_spread(self, s, size, left, right):
"""left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_004640 | 2,093 | no_license | [
{
"docstring": "中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s: str) -> str"
},
{
"docstring": "left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数",
"name": "__center_spread",
"signature": "def __ce... | 3 | stack_v2_sparse_classes_30k_train_002005 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: 中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)
- def __center_spread(self, s, size, left, right): left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left +... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: 中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)
- def __center_spread(self, s, size, left, right): left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left +... | 3f4284330f9771037ca59e2e6a94122e51e58540 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
<|body_0|>
def __center_spread(self, s, size, left, right):
"""left = right的时候,此时回文中心是一条线,回文串的长度是奇数 right = left + 1的时候,此时回文中心是任意一个字符,回文串的长度是偶数"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s: str) -> str:
"""中心扩散的思路 时间复杂度:O(N^2) 空间复杂度:O(1)"""
size = len(s)
if size == 0:
return ''
longest_palindrome = 1
longest_palindrome_str = s[0]
for i in range(size):
palindrome_odd, odd_len = self.__... | the_stack_v2_python_sparse | Leetcode/5.最长回文子串.py | myf-algorithm/Leetcode | train | 1 | |
259ba1afdb2d891da10d4b1f7cbd8dcbe2ff843f | [
"self.args = args\nself.gcp_env = gcp_env\nself.alembic_args = alembic_args\nself.output = ''",
"if not self.gcp_env.activate_sql_proxy(user='alembic', project=self.gcp_env.project):\n return 1\nclr = self.gcp_env.terminal_colors\n_logger.info('\\nAlembic Process Information:')\n_logger.info('=' * 90)\n_logger... | <|body_start_0|>
self.args = args
self.gcp_env = gcp_env
self.alembic_args = alembic_args
self.output = ''
<|end_body_0|>
<|body_start_1|>
if not self.gcp_env.activate_sql_proxy(user='alembic', project=self.gcp_env.project):
return 1
clr = self.gcp_env.termin... | A thin wrapper around the Alembic executable. | AlembicManagerClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlembicManagerClass:
"""A thin wrapper around the Alembic executable."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list):
""":param args: command line arguments. :param gcp_env: gcp environment information, see: gcp_initialize()."""
<|body_0|>
d... | stack_v2_sparse_classes_10k_train_004641 | 3,948 | permissive | [
{
"docstring": ":param args: command line arguments. :param gcp_env: gcp environment information, see: gcp_initialize().",
"name": "__init__",
"signature": "def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list)"
},
{
"docstring": "Main program process :return: Exit code value... | 2 | null | Implement the Python class `AlembicManagerClass` described below.
Class description:
A thin wrapper around the Alembic executable.
Method signatures and docstrings:
- def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list): :param args: command line arguments. :param gcp_env: gcp environment informa... | Implement the Python class `AlembicManagerClass` described below.
Class description:
A thin wrapper around the Alembic executable.
Method signatures and docstrings:
- def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list): :param args: command line arguments. :param gcp_env: gcp environment informa... | 461ae46aeda21d54de8a91aa5ef677676d5db541 | <|skeleton|>
class AlembicManagerClass:
"""A thin wrapper around the Alembic executable."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list):
""":param args: command line arguments. :param gcp_env: gcp environment information, see: gcp_initialize()."""
<|body_0|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlembicManagerClass:
"""A thin wrapper around the Alembic executable."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, alembic_args: list):
""":param args: command line arguments. :param gcp_env: gcp environment information, see: gcp_initialize()."""
self.args = args
self.... | the_stack_v2_python_sparse | rdr_service/tools/tool_libs/alembic.py | all-of-us/raw-data-repository | train | 46 |
a1a395007d8647610334b0fa4c1d0a8bbcd872c0 | [
"self.name = name\nself.version = version\nself.propertiesFileContent = propertiesFileContent\nself.ipAddress = ipAddress\nself.osh = None\nself.nodes = []\nself.packages = []\nself.quorumServer = quorumServer",
"if self.name:\n self.osh = ObjectStateHolder('serviceguardcluster')\n self.osh.setAttribute('da... | <|body_start_0|>
self.name = name
self.version = version
self.propertiesFileContent = propertiesFileContent
self.ipAddress = ipAddress
self.osh = None
self.nodes = []
self.packages = []
self.quorumServer = quorumServer
<|end_body_0|>
<|body_start_1|>
... | Data Object represents Service Guard Cluster | Cluster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
"""Data Object represents Service Guard Cluster"""
def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None):
"""@types: str, str, str, str, QuorumServer"""
<|body_0|>
def build(self):
"""Creates serviceguardcluster OSH @retu... | stack_v2_sparse_classes_10k_train_004642 | 23,160 | no_license | [
{
"docstring": "@types: str, str, str, str, QuorumServer",
"name": "__init__",
"signature": "def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None)"
},
{
"docstring": "Creates serviceguardcluster OSH @returns: instance of serviceguardcluster OSH",
"name": "bui... | 2 | stack_v2_sparse_classes_30k_train_001159 | Implement the Python class `Cluster` described below.
Class description:
Data Object represents Service Guard Cluster
Method signatures and docstrings:
- def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None): @types: str, str, str, str, QuorumServer
- def build(self): Creates serviceg... | Implement the Python class `Cluster` described below.
Class description:
Data Object represents Service Guard Cluster
Method signatures and docstrings:
- def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None): @types: str, str, str, str, QuorumServer
- def build(self): Creates serviceg... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class Cluster:
"""Data Object represents Service Guard Cluster"""
def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None):
"""@types: str, str, str, str, QuorumServer"""
<|body_0|>
def build(self):
"""Creates serviceguardcluster OSH @retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Cluster:
"""Data Object represents Service Guard Cluster"""
def __init__(self, name, version, ipAddress, propertiesFileContent, quorumServer=None):
"""@types: str, str, str, str, QuorumServer"""
self.name = name
self.version = version
self.propertiesFileContent = propertie... | the_stack_v2_python_sparse | reference/ucmdb/discovery/service_guard.py | madmonkyang/cda-record | train | 0 |
488451854a3c0df8eaf4c34fbf79defc064719fc | [
"self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir)\nself.task = 'fact'\nself.dim = 'consistency'",
"n_data = len(data)\neval_scores = [{} for _ in range(n_data)]\nsrc_list, output_l... | <|body_start_0|>
self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir)
self.task = 'fact'
self.dim = 'consistency'
<|end_body_0|>
<|body_start_1|>
n_data = le... | FactEvaluator | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for factual consistency detection"""
<|body_0|>
def evaluate(self, data, category):
"""Get the factual consistency score (only 1 dimension for... | stack_v2_sparse_classes_10k_train_004643 | 14,573 | permissive | [
{
"docstring": "Set up evaluator for factual consistency detection",
"name": "__init__",
"signature": "def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None)"
},
{
"docstring": "Get the factual consistency score (only 1 dimension for this task) category: The cat... | 2 | stack_v2_sparse_classes_30k_train_002220 | Implement the Python class `FactEvaluator` described below.
Class description:
Implement the FactEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for factual consistency detection
- def evaluate(self, data, ... | Implement the Python class `FactEvaluator` described below.
Class description:
Implement the FactEvaluator class.
Method signatures and docstrings:
- def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for factual consistency detection
- def evaluate(self, data, ... | c7b60f75470f067d1342705708810a660eabd684 | <|skeleton|>
class FactEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for factual consistency detection"""
<|body_0|>
def evaluate(self, data, category):
"""Get the factual consistency score (only 1 dimension for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FactEvaluator:
def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None):
"""Set up evaluator for factual consistency detection"""
self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_leng... | the_stack_v2_python_sparse | applications/Chat/evaluate/unieval/evaluator.py | hpcaitech/ColossalAI | train | 32,044 | |
d7a41b5046a12fd68c7bcc4ec4525c6cbe068f45 | [
"symbol, name = command\nuser_level = self.ROLES.get(symbol, 1)\nraw.role = user_level\nraw.target = None\nresponse = await self.api.add_command(name, raw.split(maximum=3)[-1].json, user_level=user_level)\ndata = await response.json()\nif data['meta'].get('created'):\n return 'Added command !{}.'.format(name)\nr... | <|body_start_0|>
symbol, name = command
user_level = self.ROLES.get(symbol, 1)
raw.role = user_level
raw.target = None
response = await self.api.add_command(name, raw.split(maximum=3)[-1].json, user_level=user_level)
data = await response.json()
if data['meta'].ge... | Manage commands. | Meta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
<|body_0|>
async def remove(self, name: '?command'):
"""Remove a command."""
<|body_1|>
async def list_commands(self)... | stack_v2_sparse_classes_10k_train_004644 | 3,086 | permissive | [
{
"docstring": "Add a command.",
"name": "add",
"signature": "async def add(self, command: '!?([+$]?)([\\\\w-]{1,32})', *response, raw: 'packet')"
},
{
"docstring": "Remove a command.",
"name": "remove",
"signature": "async def remove(self, name: '?command')"
},
{
"docstring": "L... | 6 | stack_v2_sparse_classes_30k_train_002609 | Implement the Python class `Meta` described below.
Class description:
Manage commands.
Method signatures and docstrings:
- async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'): Add a command.
- async def remove(self, name: '?command'): Remove a command.
- async def list_commands(self): Li... | Implement the Python class `Meta` described below.
Class description:
Manage commands.
Method signatures and docstrings:
- async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'): Add a command.
- async def remove(self, name: '?command'): Remove a command.
- async def list_commands(self): Li... | 6d035bf74bdc8f7fb3ee1e79f8d443f5b17e7ea5 | <|skeleton|>
class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
<|body_0|>
async def remove(self, name: '?command'):
"""Remove a command."""
<|body_1|>
async def list_commands(self)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
symbol, name = command
user_level = self.ROLES.get(symbol, 1)
raw.role = user_level
raw.target = None
response = await self.... | the_stack_v2_python_sparse | cactusbot/commands/magic/command.py | CactusDev/CactusBot | train | 18 |
f7c0618e8b1af213f6594ad1a6496f5de699e589 | [
"self.ascending_height_points = np.array([5.0, 10.0, 20.0])\nself.ascending_cube = _set_up_height_cube(self.ascending_height_points)\nself.descending_height_points = np.array([20.0, 10.0, 5.0])\nself.descending_cube = _set_up_height_cube(self.descending_height_points, ascending=False)\nself.plugin_positive = Integr... | <|body_start_0|>
self.ascending_height_points = np.array([5.0, 10.0, 20.0])
self.ascending_cube = _set_up_height_cube(self.ascending_height_points)
self.descending_height_points = np.array([20.0, 10.0, 5.0])
self.descending_cube = _set_up_height_cube(self.descending_height_points, ascend... | Test the ensure_monotonic_increase_in_chosen_direction method. | Test_ensure_monotonic_increase_in_chosen_direction | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_ensure_monotonic_increase_in_chosen_direction:
"""Test the ensure_monotonic_increase_in_chosen_direction method."""
def setUp(self):
"""Set up the cube."""
<|body_0|>
def test_ascending_coordinate_positive(self):
"""Test that for a monotonically ascending co... | stack_v2_sparse_classes_10k_train_004645 | 25,011 | permissive | [
{
"docstring": "Set up the cube.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that for a monotonically ascending coordinate, where the chosen direction is positive, the resulting coordinate still increases monotonically in the positive direction.",
"name": "test_... | 5 | null | Implement the Python class `Test_ensure_monotonic_increase_in_chosen_direction` described below.
Class description:
Test the ensure_monotonic_increase_in_chosen_direction method.
Method signatures and docstrings:
- def setUp(self): Set up the cube.
- def test_ascending_coordinate_positive(self): Test that for a monot... | Implement the Python class `Test_ensure_monotonic_increase_in_chosen_direction` described below.
Class description:
Test the ensure_monotonic_increase_in_chosen_direction method.
Method signatures and docstrings:
- def setUp(self): Set up the cube.
- def test_ascending_coordinate_positive(self): Test that for a monot... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_ensure_monotonic_increase_in_chosen_direction:
"""Test the ensure_monotonic_increase_in_chosen_direction method."""
def setUp(self):
"""Set up the cube."""
<|body_0|>
def test_ascending_coordinate_positive(self):
"""Test that for a monotonically ascending co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_ensure_monotonic_increase_in_chosen_direction:
"""Test the ensure_monotonic_increase_in_chosen_direction method."""
def setUp(self):
"""Set up the cube."""
self.ascending_height_points = np.array([5.0, 10.0, 20.0])
self.ascending_cube = _set_up_height_cube(self.ascending_heig... | the_stack_v2_python_sparse | improver_tests/utilities/test_mathematical_operations.py | metoppv/improver | train | 101 |
008acc477c6de384db81166439581d21a3140acd | [
"def rserialize(root, string):\n \"\"\" a recursive helper function for the serialize() function.\"\"\"\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return s... | <|body_start_0|>
def rserialize(root, string):
""" a recursive helper function for the serialize() function."""
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = rserialize(root.left, string)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_004646 | 17,936 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def rserialize(root, string):
""" a recursive helper function for the serialize() function."""
if root is None:
string += 'None,'
else... | the_stack_v2_python_sparse | leetcode_python/Tree/serialize-and-deserialize-binary-tree.py | yennanliu/CS_basics | train | 64 | |
bea655b1a9dc4075e504d6de139d02d093366659 | [
"LOG.debug('Initializing a polling monitor...')\nsuper(PollingMonitor, self).__init__(monitor_plugins)\nself.polling_timers = []",
"LOG.debug('Starting a polling monitor...')\ntry:\n for plugin in self.monitor_plugins:\n self.polling_timers.append(self.tg.add_timer(plugin.get_polling_interval(), self.ca... | <|body_start_0|>
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
<|end_body_0|>
<|body_start_1|>
LOG.debug('Starting a polling monitor...')
try:
for plugin in self.monitor_plugins:
... | A polling based monitor. | PollingMonitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_10k_train_004647 | 2,095 | permissive | [
{
"docstring": "Initialize a polling monitor.",
"name": "__init__",
"signature": "def __init__(self, monitor_plugins)"
},
{
"docstring": "Start polling.",
"name": "start_monitoring",
"signature": "def start_monitoring(self)"
},
{
"docstring": "Stop polling.",
"name": "stop_mo... | 3 | stack_v2_sparse_classes_30k_train_006778 | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling. | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling.
<|skeleton|>
class Po... | 5ecdc85538f8172eb63b13441dc08b166851befe | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
def start_monitoring(s... | the_stack_v2_python_sparse | blazar/monitor/polling_monitor.py | ChameleonCloud/blazar | train | 1 |
ce49af528a5ce92e32f7814b34783ac3e845c0b0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AudioRoutingGroup()",
"from .entity import Entity\nfrom .routing_mode import RoutingMode\nfrom .entity import Entity\nfrom .routing_mode import RoutingMode\nfields: Dict[str, Callable[[Any], None]] = {'receivers': lambda n: setattr(sel... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AudioRoutingGroup()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .routing_mode import RoutingMode
from .entity import Entity
from .routing_mode import ... | AudioRoutingGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_10k_train_004648 | 2,660 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AudioRoutingGroup",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | null | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Audi... | the_stack_v2_python_sparse | msgraph/generated/models/audio_routing_group.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3ea614c150c99296cac7392f5825d260e1d2273a | [
"self.__include_deps_supply = include_deps_supply\nif closure:\n self.__transform_pre = GraphAlgorithms.transitive_closure\nelse:\n self.__transform_pre = lambda x: x\nif sort:\n self.__transform_post = sorted\nelse:\n self.__transform_post = lambda x: x",
"args_set = set(args)\nedge_list = self.__tra... | <|body_start_0|>
self.__include_deps_supply = include_deps_supply
if closure:
self.__transform_pre = GraphAlgorithms.transitive_closure
else:
self.__transform_pre = lambda x: x
if sort:
self.__transform_post = sorted
else:
self.__tr... | FileIncludeDepsListerFacade | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_10k_train_004649 | 2,930 | permissive | [
{
"docstring": "@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param sort: if True, return output sorted by filenames @type sort: Boolean",
"name": "... | 2 | stack_v2_sparse_classes_30k_val_000072 | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | d58680ef7d6bdc8ef518860d5d13a5acc0d01758 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param so... | the_stack_v2_python_sparse | cpp/incl_deps/include_deps_util.py | btc-ag/revengtools | train | 2 | |
f0f24b75e753ba1a7c545f926ca085fd5158b3c6 | [
"if self.website_published:\n self.write({'website_published': False})\nelse:\n self.write({'website_published': True})",
"if self.filter_id:\n domain = safe_eval(self.filter_id.domain)\n domain += ['|', ('website_id', '=', None), ('website_id', '=', self.slider_id.website_id.id), ('website_published'... | <|body_start_0|>
if self.website_published:
self.write({'website_published': False})
else:
self.write({'website_published': True})
<|end_body_0|>
<|body_start_1|>
if self.filter_id:
domain = safe_eval(self.filter_id.domain)
domain += ['|', ('websi... | SliderFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
<|body_0|>
def _onchange_filter_id(self):
"""If selected Filter has no any product the raise the warning and remove that filter :return:"""
<... | stack_v2_sparse_classes_10k_train_004650 | 1,733 | no_license | [
{
"docstring": "Set slider filter published and unpublished on website :return:",
"name": "website_publish_button",
"signature": "def website_publish_button(self)"
},
{
"docstring": "If selected Filter has no any product the raise the warning and remove that filter :return:",
"name": "_oncha... | 2 | stack_v2_sparse_classes_30k_train_006316 | Implement the Python class `SliderFilter` described below.
Class description:
Implement the SliderFilter class.
Method signatures and docstrings:
- def website_publish_button(self): Set slider filter published and unpublished on website :return:
- def _onchange_filter_id(self): If selected Filter has no any product t... | Implement the Python class `SliderFilter` described below.
Class description:
Implement the SliderFilter class.
Method signatures and docstrings:
- def website_publish_button(self): Set slider filter published and unpublished on website :return:
- def _onchange_filter_id(self): If selected Filter has no any product t... | 148dd95d991a348ebbaff9396759a7dd1fe6e101 | <|skeleton|>
class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
<|body_0|>
def _onchange_filter_id(self):
"""If selected Filter has no any product the raise the warning and remove that filter :return:"""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
if self.website_published:
self.write({'website_published': False})
else:
self.write({'website_published': True})
def _onchange_filter_id(s... | the_stack_v2_python_sparse | custom/addons/emipro_theme_base/model/slider_filter.py | marionumza/saas | train | 0 | |
a1bde53129f20def892088324f5f051d8b5b0018 | [
"super().__init__(websession, API_URL)\nself._oauth_session = oauth_session\nself._client_id = client_id\nself._client_secret = client_secret",
"if not self._oauth_session.valid_token:\n await self._oauth_session.async_ensure_token_valid()\nreturn cast(str, self._oauth_session.token['access_token'])",
"token... | <|body_start_0|>
super().__init__(websession, API_URL)
self._oauth_session = oauth_session
self._client_id = client_id
self._client_secret = client_secret
<|end_body_0|>
<|body_start_1|>
if not self._oauth_session.valid_token:
await self._oauth_session.async_ensure_t... | Provide Google Nest Device Access authentication tied to an OAuth2 based config entry. | AsyncConfigEntryAuth | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Ne... | stack_v2_sparse_classes_10k_train_004651 | 4,887 | permissive | [
{
"docstring": "Initialize Google Nest Device Access auth.",
"name": "__init__",
"signature": "def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None"
},
{
"docstring": "Return a valid access token for SDM ... | 3 | null | Implement the Python class `AsyncConfigEntryAuth` described below.
Class description:
Provide Google Nest Device Access authentication tied to an OAuth2 based config entry.
Method signatures and docstrings:
- def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_i... | Implement the Python class `AsyncConfigEntryAuth` described below.
Class description:
Provide Google Nest Device Access authentication tied to an OAuth2 based config entry.
Method signatures and docstrings:
- def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_i... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Ne... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Nest Device Acc... | the_stack_v2_python_sparse | homeassistant/components/nest/api.py | home-assistant/core | train | 35,501 |
6831b0fbb7a6dadcaef55a6df4497df57ec91df1 | [
"if head == None or head.next == None:\n return head\ncur = self.reverseList_recursive(head.next)\nhead.next.next = head\nhead.next = None\nreturn cur",
"pre = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\nreturn pre"
] | <|body_start_0|>
if head == None or head.next == None:
return head
cur = self.reverseList_recursive(head.next)
head.next.next = head
head.next = None
return cur
<|end_body_0|>
<|body_start_1|>
pre = None
cur = head
while cur:
tmp =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList_recursive(self, head: ListNode) -> ListNode:
"""递归解法 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList_iterate(self, head: ListNode) -> ListNode:
"""迭代解法 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k_train_004652 | 2,567 | no_license | [
{
"docstring": "递归解法 :type head: ListNode :rtype: ListNode",
"name": "reverseList_recursive",
"signature": "def reverseList_recursive(self, head: ListNode) -> ListNode"
},
{
"docstring": "迭代解法 :type head: ListNode :rtype: ListNode",
"name": "reverseList_iterate",
"signature": "def revers... | 2 | stack_v2_sparse_classes_30k_train_000124 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_recursive(self, head: ListNode) -> ListNode: 递归解法 :type head: ListNode :rtype: ListNode
- def reverseList_iterate(self, head: ListNode) -> ListNode: 迭代解法 :type he... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_recursive(self, head: ListNode) -> ListNode: 递归解法 :type head: ListNode :rtype: ListNode
- def reverseList_iterate(self, head: ListNode) -> ListNode: 迭代解法 :type he... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def reverseList_recursive(self, head: ListNode) -> ListNode:
"""递归解法 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList_iterate(self, head: ListNode) -> ListNode:
"""迭代解法 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList_recursive(self, head: ListNode) -> ListNode:
"""递归解法 :type head: ListNode :rtype: ListNode"""
if head == None or head.next == None:
return head
cur = self.reverseList_recursive(head.next)
head.next.next = head
head.next = None
... | the_stack_v2_python_sparse | 字节跳动测试开发工程师面试准备/reverseList.py | MaoningGuan/LeetCode | train | 3 | |
36bd06ee5a4e59df390b374e4e4d2e7584a4b56c | [
"super(PILCOAlgorithm, self).__init__(model, observed, extra_graphs=extra_graphs)\nself.cost_function = cost_function\nself.policy = policy\nself.initial_state_generator = initial_state_generator\nself.n_time_steps = n_time_steps\nself.num_samples = num_samples\nself.dtype = dtype if dtype is not None else get_defa... | <|body_start_0|>
super(PILCOAlgorithm, self).__init__(model, observed, extra_graphs=extra_graphs)
self.cost_function = cost_function
self.policy = policy
self.initial_state_generator = initial_state_generator
self.n_time_steps = n_time_steps
self.num_samples = num_samples... | Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of samples used in estimating the variational ... | PILCOAlgorithm | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of s... | stack_v2_sparse_classes_10k_train_004653 | 4,512 | permissive | [
{
"docstring": ":param model: The model to use to generate the next state from a state/action pair. :param observed: Observed variables for the model. :param cost_function: The cost function to evaluate state/action pairs on. :param policy: The policy function to determine what action to take next from a partic... | 2 | stack_v2_sparse_classes_30k_train_000937 | Implement the Python class `PILCOAlgorithm` described below.
Class description:
Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variab... | Implement the Python class `PILCOAlgorithm` described below.
Class description:
Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variab... | af6223e9636b055d029d136dd7ae023b210b4560 | <|skeleton|>
class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of samples used i... | the_stack_v2_python_sparse | mxfusion/inference/pilco_alg.py | amzn/MXFusion | train | 109 |
cb91ea3b58f15fbb5019b2210a4bbd5533639cf7 | [
"n = len(nums)\nif n < 3:\n return False\nflag_num = 2 ** 31\nmin_value = nums[0]\nfor i in range(1, n):\n if nums[i] > flag_num:\n return True\n if nums[i] > min_value:\n flag_num = min(nums[i], flag_num)\n min_value = min(min_value, nums[i])\nreturn False",
"if len(nums) < 3:\n retu... | <|body_start_0|>
n = len(nums)
if n < 3:
return False
flag_num = 2 ** 31
min_value = nums[0]
for i in range(1, n):
if nums[i] > flag_num:
return True
if nums[i] > min_value:
flag_num = min(nums[i], flag_num)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
<|body_0|>
def increasingTriplet2(self, nums: List[int]) -> bool:
"""20221011 Runti... | stack_v2_sparse_classes_10k_train_004654 | 1,941 | permissive | [
{
"docstring": "2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums: List[int]) -> bool"
},
{
"docstring": "20221011 Runtime: 897 ms, faster than 64.93% Mem... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums: List[int]) -> bool: 2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:
- def incr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums: List[int]) -> bool: 2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:
- def incr... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
<|body_0|>
def increasingTriplet2(self, nums: List[int]) -> bool:
"""20221011 Runti... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""2021/8/28 76 / 76 test cases passed. Status: Accepted Runtime: 695 ms Memory Usage: 25.5 MB :param nums: :return:"""
n = len(nums)
if n < 3:
return False
flag_num = 2 ** 31
min_value = nums[0... | the_stack_v2_python_sparse | src/334-IncreasingTripletSubsequence.py | Jiezhi/myleetcode | train | 1 | |
068f2d0dde5b13031c7c69a1be098f7f96b208c0 | [
"used_words = set()\nsuggests = []\nfor text, weight in info_tuple:\n if text:\n words = es.indices.analyze(index=index, analyzer='ik_max_word', params={'filter': ['lowercase']}, body=text)\n analyzed_words = set([r['token'] for r in words['tokens'] if len(r['token']) > 1])\n new_words = ana... | <|body_start_0|>
used_words = set()
suggests = []
for text, weight in info_tuple:
if text:
words = es.indices.analyze(index=index, analyzer='ik_max_word', params={'filter': ['lowercase']}, body=text)
analyzed_words = set([r['token'] for r in words['tok... | 将数据写入到es中 | ElasticSearchPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
<|body_0|>
def process_item(self, item, spider):
"""将item转换为es的数据格式 :param item: :param spider: :return:"""
<|b... | stack_v2_sparse_classes_10k_train_004655 | 4,853 | no_license | [
{
"docstring": "根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:",
"name": "gen_suggests",
"signature": "def gen_suggests(self, index, info_tuple)"
},
{
"docstring": "将item转换为es的数据格式 :param item: :param spider: :return:",
"name": "process_item",
"signature": "def process_item(self... | 2 | stack_v2_sparse_classes_30k_test_000196 | Implement the Python class `ElasticSearchPipeline` described below.
Class description:
将数据写入到es中
Method signatures and docstrings:
- def gen_suggests(self, index, info_tuple): 根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:
- def process_item(self, item, spider): 将item转换为es的数据格式 :param item: :param spider: :r... | Implement the Python class `ElasticSearchPipeline` described below.
Class description:
将数据写入到es中
Method signatures and docstrings:
- def gen_suggests(self, index, info_tuple): 根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:
- def process_item(self, item, spider): 将item转换为es的数据格式 :param item: :param spider: :r... | 926002c7d66db2456fea94f1b50fdbf364d66836 | <|skeleton|>
class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
<|body_0|>
def process_item(self, item, spider):
"""将item转换为es的数据格式 :param item: :param spider: :return:"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElasticSearchPipeline:
"""将数据写入到es中"""
def gen_suggests(self, index, info_tuple):
"""根据字符串生成搜索建议数组 :param index: :param info_tuple: :return:"""
used_words = set()
suggests = []
for text, weight in info_tuple:
if text:
words = es.indices.analyze(... | the_stack_v2_python_sparse | ArticleSpider/ArticleSpider/pipelines.py | JayZhou5299/search_engine | train | 1 |
2170a6771d53b47cd8e37244b64a00f93f8f27b9 | [
"def filter(d, max):\n \"\"\" filters dataset by max_len \"\"\"\n return tf.math.less(d, max)\nself.batch_size = batch_size\ntrain = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(train)\nself.data_train = train.map(sel... | <|body_start_0|>
def filter(d, max):
""" filters dataset by max_len """
return tf.math.less(d, max)
self.batch_size = batch_size
train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.tokenizer_pt, self.tokenizer_en = self.tokeniz... | loads and preps a dataset for machine translation | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_... | stack_v2_sparse_classes_10k_train_004656 | 5,014 | no_license | [
{
"docstring": "batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt to_en tf.dat... | 4 | null | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sente... | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sente... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self, batch_size, max_len):
"""batch_size is the batch size for training/validation max_len is the maximum number of tokens allowed per example sentence data_train, which contains the ted_hrlr_translate/pt_to en tf.data... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/3-dataset.py | icculp/holbertonschool-machine_learning | train | 0 |
4a65127aa2c7e14766a2aafc7c85c90b26793c55 | [
"super(BehaviorAttackRanged, self).__init__(_move_cost)\nself.strength = _strength\nself.range = _range",
"zap_x, zap_y = _level_view.ent_coords(_target_eid)\nadv_x, adv_y = _user.get_coords()\nin_los = Z_ALGS.check_los(zap_x, zap_y, adv_x, adv_y, self.range + 1, _level_view.cell_is_transparent)\nin_rng = Z_ALGS.... | <|body_start_0|>
super(BehaviorAttackRanged, self).__init__(_move_cost)
self.strength = _strength
self.range = _range
<|end_body_0|>
<|body_start_1|>
zap_x, zap_y = _level_view.ent_coords(_target_eid)
adv_x, adv_y = _user.get_coords()
in_los = Z_ALGS.check_los(zap_x, zap... | BehaviorAttackRanged | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BehaviorAttackRanged:
def __init__(self, _move_cost=1, _strength=1, _range=5):
""":type _move_cost: int :type _strength: int :type _range: int"""
<|body_0|>
def _special_can_execute(self, _target_eid, _level_view, _user):
""":type _target_eid: int :type _level_view: ... | stack_v2_sparse_classes_10k_train_004657 | 1,805 | no_license | [
{
"docstring": ":type _move_cost: int :type _strength: int :type _range: int",
"name": "__init__",
"signature": "def __init__(self, _move_cost=1, _strength=1, _range=5)"
},
{
"docstring": ":type _target_eid: int :type _level_view: level.LevelView.LevelView :type _user: entity.actor.Adversary.Adv... | 3 | stack_v2_sparse_classes_30k_train_002233 | Implement the Python class `BehaviorAttackRanged` described below.
Class description:
Implement the BehaviorAttackRanged class.
Method signatures and docstrings:
- def __init__(self, _move_cost=1, _strength=1, _range=5): :type _move_cost: int :type _strength: int :type _range: int
- def _special_can_execute(self, _ta... | Implement the Python class `BehaviorAttackRanged` described below.
Class description:
Implement the BehaviorAttackRanged class.
Method signatures and docstrings:
- def __init__(self, _move_cost=1, _strength=1, _range=5): :type _move_cost: int :type _strength: int :type _range: int
- def _special_can_execute(self, _ta... | 0342700b0edfeedd8e3a8c1fea9bd790d2b8a042 | <|skeleton|>
class BehaviorAttackRanged:
def __init__(self, _move_cost=1, _strength=1, _range=5):
""":type _move_cost: int :type _strength: int :type _range: int"""
<|body_0|>
def _special_can_execute(self, _target_eid, _level_view, _user):
""":type _target_eid: int :type _level_view: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BehaviorAttackRanged:
def __init__(self, _move_cost=1, _strength=1, _range=5):
""":type _move_cost: int :type _strength: int :type _range: int"""
super(BehaviorAttackRanged, self).__init__(_move_cost)
self.strength = _strength
self.range = _range
def _special_can_execute(s... | the_stack_v2_python_sparse | Python_Zappy/entity/actor/behaviors/BehaviorAttackRanged.py | MoyTW/Zappy | train | 0 | |
421631a880fc00fba21195c44ad4f7274292df31 | [
"attrs = super().validate(attrs)\nerrors = {}\ncombiner = DataCombiner(self.instance, attrs)\nvalidators = (self._validate_related_trade_agreements,)\nfor validator in validators:\n errors.update(validator(combiner))\nif errors:\n raise serializers.ValidationError(errors)\nreturn attrs",
"errors = {}\nrelat... | <|body_start_0|>
attrs = super().validate(attrs)
errors = {}
combiner = DataCombiner(self.instance, attrs)
validators = (self._validate_related_trade_agreements,)
for validator in validators:
errors.update(validator(combiner))
if errors:
raise seri... | Event serialiser for V4 endpoint. | EventSerializerV4 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventSerializerV4:
"""Event serialiser for V4 endpoint."""
def validate(self, attrs):
"""Performs cross-field validation."""
<|body_0|>
def _validate_related_trade_agreements(self, combiner):
"""Validates trade agreement state for consistency with has_related_tra... | stack_v2_sparse_classes_10k_train_004658 | 7,153 | permissive | [
{
"docstring": "Performs cross-field validation.",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Validates trade agreement state for consistency with has_related_trade_agreements",
"name": "_validate_related_trade_agreements",
"signature": "def _validate... | 2 | null | Implement the Python class `EventSerializerV4` described below.
Class description:
Event serialiser for V4 endpoint.
Method signatures and docstrings:
- def validate(self, attrs): Performs cross-field validation.
- def _validate_related_trade_agreements(self, combiner): Validates trade agreement state for consistency... | Implement the Python class `EventSerializerV4` described below.
Class description:
Event serialiser for V4 endpoint.
Method signatures and docstrings:
- def validate(self, attrs): Performs cross-field validation.
- def _validate_related_trade_agreements(self, combiner): Validates trade agreement state for consistency... | a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e | <|skeleton|>
class EventSerializerV4:
"""Event serialiser for V4 endpoint."""
def validate(self, attrs):
"""Performs cross-field validation."""
<|body_0|>
def _validate_related_trade_agreements(self, combiner):
"""Validates trade agreement state for consistency with has_related_tra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventSerializerV4:
"""Event serialiser for V4 endpoint."""
def validate(self, attrs):
"""Performs cross-field validation."""
attrs = super().validate(attrs)
errors = {}
combiner = DataCombiner(self.instance, attrs)
validators = (self._validate_related_trade_agreeme... | the_stack_v2_python_sparse | datahub/event/serializers.py | cgsunkel/data-hub-api | train | 0 |
f5de3d01daea97ef24139abb88537b7e0c1b30ad | [
"self.enable_lambda_based_gc = enable_lambda_based_gc\nself.lambda_function_version = lambda_function_version\nself.tier_type = tier_type\nself.worm_enabled = worm_enabled",
"if dictionary is None:\n return None\nenable_lambda_based_gc = dictionary.get('enableLambdaBasedGc')\nlambda_function_version = dictiona... | <|body_start_0|>
self.enable_lambda_based_gc = enable_lambda_based_gc
self.lambda_function_version = lambda_function_version
self.tier_type = tier_type
self.worm_enabled = worm_enabled
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
enable_... | Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure function based GC. An Azure function needs to be deployed in the customer's Azure environment. lambda_function_version (int): ... | ClusterConfigProto_Vault_CloudProperties_AzureProperties | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterConfigProto_Vault_CloudProperties_AzureProperties:
"""Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure function based GC. An Azure function needs... | stack_v2_sparse_classes_10k_train_004659 | 2,887 | permissive | [
{
"docstring": "Constructor for the ClusterConfigProto_Vault_CloudProperties_AzureProperties class",
"name": "__init__",
"signature": "def __init__(self, enable_lambda_based_gc=None, lambda_function_version=None, tier_type=None, worm_enabled=None)"
},
{
"docstring": "Creates an instance of this ... | 2 | null | Implement the Python class `ClusterConfigProto_Vault_CloudProperties_AzureProperties` described below.
Class description:
Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure fun... | Implement the Python class `ClusterConfigProto_Vault_CloudProperties_AzureProperties` described below.
Class description:
Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure fun... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterConfigProto_Vault_CloudProperties_AzureProperties:
"""Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure function based GC. An Azure function needs... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterConfigProto_Vault_CloudProperties_AzureProperties:
"""Implementation of the 'ClusterConfigProto_Vault_CloudProperties_AzureProperties' model. TODO: type description here. Attributes: enable_lambda_based_gc (bool): Whether this vault supports Azure function based GC. An Azure function needs to be deploy... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_config_proto_vault_cloud_properties_azure_properties.py | cohesity/management-sdk-python | train | 24 |
eb767c0c3070853da34a3068ba2d6c216799f2b2 | [
"self.key = key\nself.actions_allowed = actions_allowed\nself.how_often = how_often\n'\\n Dictionary of {domain: datetime}\\n When a domain exceeds its allowed actions, an entry is put here to\\n note the timestamp when the domain should be allowed to perform\\n actions again. This is me... | <|body_start_0|>
self.key = key
self.actions_allowed = actions_allowed
self.how_often = how_often
'\n Dictionary of {domain: datetime}\n When a domain exceeds its allowed actions, an entry is put here to\n note the timestamp when the domain should be allowed to perfo... | A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <delay action> | DomainRateLimiter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainRateLimiter:
"""A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <delay action>"""
def __init__(self, ke... | stack_v2_sparse_classes_10k_train_004660 | 4,174 | permissive | [
{
"docstring": "key - the beginning of the redis key that will be used to rate limit on; the actual key that is used will be key + domain actions_allowed - see rate_limit() how_often - see rate_limit()",
"name": "__init__",
"signature": "def __init__(self, key, actions_allowed, how_often)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_002614 | Implement the Python class `DomainRateLimiter` described below.
Class description:
A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <dela... | Implement the Python class `DomainRateLimiter` described below.
Class description:
A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <dela... | 1c70ce416564efa496fb4ef6e9130c188aea0f40 | <|skeleton|>
class DomainRateLimiter:
"""A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <delay action>"""
def __init__(self, ke... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DomainRateLimiter:
"""A util for rate limiting by domain. For example, to allow a domain to only send 100 SMS every 60 seconds: limiter = DomainRateLimiter('send-sms-for-', 100, 60) ... if limiter.can_perform_action('my-domain'): <perform action> else: <delay action>"""
def __init__(self, key, actions_al... | the_stack_v2_python_sparse | corehq/ex-submodules/dimagi/utils/rate_limit.py | dungeonmaster51/commcare-hq | train | 1 |
9021a0a10da337fe392bc249c7fe8b26c4c04a62 | [
"instance = Brand.objects.all()\nserializer = BrandsSimpleSerializer(instance, many=True)\nreturn Response(serializer.data)",
"if pk:\n instance = GoodsCategory.objects.filter(parent_id=pk)\nelse:\n instance = GoodsCategory.objects.filter(parent=None)\nserializer = GoodsCategoriesSerializer(instance, many=T... | <|body_start_0|>
instance = Brand.objects.all()
serializer = BrandsSimpleSerializer(instance, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
if pk:
instance = GoodsCategory.objects.filter(parent_id=pk)
else:
instance = GoodsCa... | SPU视图集 | SPUSViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
<|body_0|>
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回父类, 再次请求返回二级和三级"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
instance = Brand.objects.all()
... | stack_v2_sparse_classes_10k_train_004661 | 2,399 | permissive | [
{
"docstring": "返回简单的商品品牌",
"name": "brands_simple",
"signature": "def brands_simple(self, request)"
},
{
"docstring": "返回商品分类,第一次返回父类, 再次请求返回二级和三级",
"name": "channel_categories",
"signature": "def channel_categories(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004360 | Implement the Python class `SPUSViewSet` described below.
Class description:
SPU视图集
Method signatures and docstrings:
- def brands_simple(self, request): 返回简单的商品品牌
- def channel_categories(self, request, pk=None): 返回商品分类,第一次返回父类, 再次请求返回二级和三级 | Implement the Python class `SPUSViewSet` described below.
Class description:
SPU视图集
Method signatures and docstrings:
- def brands_simple(self, request): 返回简单的商品品牌
- def channel_categories(self, request, pk=None): 返回商品分类,第一次返回父类, 再次请求返回二级和三级
<|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(sel... | d3ce2185ec3c68325e8becddce07d0a9da144325 | <|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
<|body_0|>
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回父类, 再次请求返回二级和三级"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
instance = Brand.objects.all()
serializer = BrandsSimpleSerializer(instance, many=True)
return Response(serializer.data)
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/views/spus.py | qls7/dianshanghoutai | train | 0 |
75239f2e0f0a59cb9b706c37c00e2bb14010b311 | [
"Parametre.__init__(self, 'lister', 'list')\nself.schema = ''\nself.aide_courte = 'liste les attitudes existantes'\nself.aide_longue = 'Cette sous-commande offre une liste des attitudes existantes.'",
"attitudes = None\nif personnage.est_immortel():\n attitudes = type(self).importeur.communication.attitudes.va... | <|body_start_0|>
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'liste les attitudes existantes'
self.aide_longue = 'Cette sous-commande offre une liste des attitudes existantes.'
<|end_body_0|>
<|body_start_1|>
attitudes = None
if personn... | Commande 'attitudes lister'. | PrmLister | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre... | stack_v2_sparse_classes_10k_train_004662 | 3,460 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmLister` described below.
Class description:
Commande 'attitudes lister'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmLister` described below.
Class description:
Commande 'attitudes lister'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmLister:
"""Commande 'attitu... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmLister:
"""Commande 'attitudes lister'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'lister', 'list')
self.schema = ''
self.aide_courte = 'liste les attitudes existantes'
self.aide_longue = 'Cette sous-commande offre une liste... | the_stack_v2_python_sparse | src/primaires/communication/commandes/attitudes/lister.py | vincent-lg/tsunami | train | 5 |
080f763229dc6df2d2a54807ffab2b120f726c4e | [
"super(PointWiseFeedForward, self).__init__()\nself.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout1 = torch.nn.Dropout(p=dropout_rate)\nself.relu = torch.nn.ReLU()\nself.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)\nself.dropout2 = torch.nn.Dropout(p=dropout_r... | <|body_start_0|>
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
self.dropout1 = torch.nn.Dropout(p=dropout_rate)
self.relu = torch.nn.ReLU()
self.conv2 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=... | PointWise forward Module. Args: torch ([type]): [description] | PointWiseFeedForward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def for... | stack_v2_sparse_classes_10k_train_004663 | 15,823 | permissive | [
{
"docstring": "Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate.",
"name": "__init__",
"signature": "def __init__(self, hidden_units, dropout_rate)"
},
{
"docstring": "Forward function. Args: inputs ([type]): [description] Returns: [typ... | 2 | stack_v2_sparse_classes_30k_test_000264 | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([... | Implement the Python class `PointWiseFeedForward` described below.
Class description:
PointWise forward Module. Args: torch ([type]): [description]
Method signatures and docstrings:
- def __init__(self, hidden_units, dropout_rate): Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
<|body_0|>
def for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointWiseFeedForward:
"""PointWise forward Module. Args: torch ([type]): [description]"""
def __init__(self, hidden_units, dropout_rate):
"""Class Initialization. Args: hidden_units ([int]): Embedding dimension. dropout_rate ([float]): dropout rate."""
super(PointWiseFeedForward, self).__... | the_stack_v2_python_sparse | beta_rec/models/tisasrec.py | beta-team/beta-recsys | train | 156 |
31a4a54a697d9c5e417451437c460ba6f668ded2 | [
"concept_parsers.ConceptParser.ForResource('TRIGGER', resource_args.GetTriggerResourceSpec(), 'Build Trigger.', required=True).AddToParser(parser)\nflag_config = trigger_utils.AddTriggerArgs(parser, add_region_flag=False, add_name=False)\nflag_config.add_argument('--secret', help=textwrap.dedent('\\n The... | <|body_start_0|>
concept_parsers.ConceptParser.ForResource('TRIGGER', resource_args.GetTriggerResourceSpec(), 'Build Trigger.', required=True).AddToParser(parser)
flag_config = trigger_utils.AddTriggerArgs(parser, add_region_flag=False, add_name=False)
flag_config.add_argument('--secret', help=t... | Update a Webhook trigger used by Google Cloud Build. | UpdateWebhook | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateWebhook:
"""Update a Webhook trigger used by Google Cloud Build."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
... | stack_v2_sparse_classes_10k_train_004664 | 5,691 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Parses arguments into a build tri... | 3 | null | Implement the Python class `UpdateWebhook` described below.
Class description:
Update a Webhook trigger used by Google Cloud Build.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some inf... | Implement the Python class `UpdateWebhook` described below.
Class description:
Update a Webhook trigger used by Google Cloud Build.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some inf... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class UpdateWebhook:
"""Update a Webhook trigger used by Google Cloud Build."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateWebhook:
"""Update a Webhook trigger used by Google Cloud Build."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
concept_parse... | the_stack_v2_python_sparse | lib/surface/builds/triggers/update/webhook.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
84df8be10b6ed116635f6def1b64b8adc92a48a8 | [
"import collections as cc\nunion = cc.defaultdict(list)\n\ndef find(node):\n if not union[node]:\n return node\n return find(union[node][0])\n\ndef uf(edge):\n x, y = (edge[0], edge[1])\n x = find(x)\n y = find(y)\n if x == y:\n return edge\n union[x].append(y)\nfor e in edges:\n ... | <|body_start_0|>
import collections as cc
union = cc.defaultdict(list)
def find(node):
if not union[node]:
return node
return find(union[node][0])
def uf(edge):
x, y = (edge[0], edge[1])
x = find(x)
y = find(y)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantConnection_smart(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_10k_train_004665 | 2,993 | no_license | [
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantConnection",
"signature": "def findRedundantConnection(self, edges)"
},
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantConnection_smart",
"signature": "def findR... | 2 | stack_v2_sparse_classes_30k_train_001642 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantConnection_smart(self, edges): :type edges: List[List[int]] :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantConnection_smart(self, edges): :type edges: List[List[int]] :rtype: Li... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantConnection_smart(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findRedundantConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
import collections as cc
union = cc.defaultdict(list)
def find(node):
if not union[node]:
return node
return find(union[node][0])
... | the_stack_v2_python_sparse | co_google/684_Redundant_Connection.py | vsdrun/lc_public | train | 6 | |
ca126b5979e94a5a80047e9d2c3c03b1005b568e | [
"def generate(A):\n if len(A) == 2 * n:\n if valid(A):\n ret.append(''.join(A))\n print(''.join(A))\n else:\n A.append('(')\n generate(A)\n A.pop()\n A.append(')')\n generate(A)\n A.pop()\n\ndef valid(A):\n bal = 0\n for i in A:\n ... | <|body_start_0|>
def generate(A):
if len(A) == 2 * n:
if valid(A):
ret.append(''.join(A))
print(''.join(A))
else:
A.append('(')
generate(A)
A.pop()
A.append(')')
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def generate(A):
if len(A) ==... | stack_v2_sparse_classes_10k_train_004666 | 1,568 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Solution:
def generat... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
def generate(A):
if len(A) == 2 * n:
if valid(A):
ret.append(''.join(A))
print(''.join(A))
else:
A.append('(')
... | the_stack_v2_python_sparse | leetcode/22.py | liuweilin17/algorithm | train | 3 | |
f8b3ea6bdf77ce81af3b9f50b07a3bce034c65fb | [
"line = line.split()\nself.nevery = int(line[1])\nself.x_store = np.zeros((nsteps / self.nevery, natoms))\nself.y_store = np.zeros((nsteps / self.nevery, natoms))\nself.scprod = np.zeros((nsteps / self.nevery, natoms))\nself.counter = 0\nreturn",
"if step % self.nevery != 0:\n return\ncos = np.cos(phi)\nsin = ... | <|body_start_0|>
line = line.split()
self.nevery = int(line[1])
self.x_store = np.zeros((nsteps / self.nevery, natoms))
self.y_store = np.zeros((nsteps / self.nevery, natoms))
self.scprod = np.zeros((nsteps / self.nevery, natoms))
self.counter = 0
return
<|end_bod... | OrientVel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrientVel:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate density array"""
<|body_0|>
def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'):
"""compute a density distribution and a histogram of the density distribution"""
<|body_... | stack_v2_sparse_classes_10k_train_004667 | 1,754 | no_license | [
{
"docstring": "initialize: allocate density array",
"name": "__init__",
"signature": "def __init__(self, nsteps, natoms, line)"
},
{
"docstring": "compute a density distribution and a histogram of the density distribution",
"name": "compute",
"signature": "def compute(self, step, x, y, ... | 2 | stack_v2_sparse_classes_30k_train_004815 | Implement the Python class `OrientVel` described below.
Class description:
Implement the OrientVel class.
Method signatures and docstrings:
- def __init__(self, nsteps, natoms, line): initialize: allocate density array
- def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): compute a density distribution ... | Implement the Python class `OrientVel` described below.
Class description:
Implement the OrientVel class.
Method signatures and docstrings:
- def __init__(self, nsteps, natoms, line): initialize: allocate density array
- def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'): compute a density distribution ... | 7d2659bee85c955c680eda019cbff6e2b93ecff2 | <|skeleton|>
class OrientVel:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate density array"""
<|body_0|>
def compute(self, step, x, y, vx, vy, phi, natoms, plot='False'):
"""compute a density distribution and a histogram of the density distribution"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrientVel:
def __init__(self, nsteps, natoms, line):
"""initialize: allocate density array"""
line = line.split()
self.nevery = int(line[1])
self.x_store = np.zeros((nsteps / self.nevery, natoms))
self.y_store = np.zeros((nsteps / self.nevery, natoms))
self.scpr... | the_stack_v2_python_sparse | analyse_collective/orientvel.py | melampyge/CollectiveFilament | train | 0 | |
9bf558bb460aabd2fceea414d998fb0f69312652 | [
"pubsub_stanza = self.xmpp['xep_0060'].stanza\nregister_stanza_plugin(pubsub_stanza.EventItem, stanza)\nself.add_interest(stanza.namespace)\nself.xmpp['xep_0030'].add_feature(stanza.namespace)\nself.xmpp['xep_0060'].map_node_event(stanza.namespace, name)",
"if not isinstance(namespace, set) and (not isinstance(na... | <|body_start_0|>
pubsub_stanza = self.xmpp['xep_0060'].stanza
register_stanza_plugin(pubsub_stanza.EventItem, stanza)
self.add_interest(stanza.namespace)
self.xmpp['xep_0030'].add_feature(stanza.namespace)
self.xmpp['xep_0060'].map_node_event(stanza.namespace, name)
<|end_body_0|... | XEP-0163: Personal Eventing Protocol (PEP) | XEP_0163 | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from th... | stack_v2_sparse_classes_10k_train_004668 | 4,561 | permissive | [
{
"docstring": "Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from the PEP content's namespace to the given name. :param str name: The event name prefix to use for PEP events. :para... | 4 | stack_v2_sparse_classes_30k_train_002557 | Implement the Python class `XEP_0163` described below.
Class description:
XEP-0163: Personal Eventing Protocol (PEP)
Method signatures and docstrings:
- def register_pep(self, name, stanza): Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Registe... | Implement the Python class `XEP_0163` described below.
Class description:
XEP-0163: Personal Eventing Protocol (PEP)
Method signatures and docstrings:
- def register_pep(self, name, stanza): Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Registe... | cc1d470397de768ffcc41d2ed5ac3118d19f09f5 | <|skeleton|>
class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from the PEP content... | the_stack_v2_python_sparse | sleekxmpp/plugins/xep_0163.py | fritzy/SleekXMPP | train | 658 |
098488790d31900f44208d9cd2279a4afd2423c9 | [
"self.seg = WordSegmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags)\nself.wc_background = get_default_wc_background()\nif type(wc_background) is str:\n self.wc_background = wc_background\nself.font_path = get_default_font_path()\nif type(font_path) is str:\n self.font_path = fon... | <|body_start_0|>
self.seg = WordSegmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags)
self.wc_background = get_default_wc_background()
if type(wc_background) is str:
self.wc_background = wc_background
self.font_path = get_default_font_path()
... | WordCloud | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordCloud:
def __init__(self, stop_words_file=None, allow_speech_tags=conf.allow_speech_tags, wc_background=None, font_path=None, max_words=200, max_font_size=100, save_path=None, wc_name=None, topK=10):
""":param stop_words_file: -- str,停用词文件路径,若不是str则使用默认停用词文件 :param allow_speech_tags:... | stack_v2_sparse_classes_10k_train_004669 | 4,561 | no_license | [
{
"docstring": ":param stop_words_file: -- str,停用词文件路径,若不是str则使用默认停用词文件 :param allow_speech_tags: -- 词性列表 :param wc_background: 词云图背景图片 :param max_words: 最多显示词数,默认200 :param max_font_size: 字体最大值,默认100 :param save_path: 词云图保存地址,默认当前文件夹",
"name": "__init__",
"signature": "def __init__(self, stop_words_fil... | 4 | stack_v2_sparse_classes_30k_train_000184 | Implement the Python class `WordCloud` described below.
Class description:
Implement the WordCloud class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=conf.allow_speech_tags, wc_background=None, font_path=None, max_words=200, max_font_size=100, save_path=None, wc_name... | Implement the Python class `WordCloud` described below.
Class description:
Implement the WordCloud class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=conf.allow_speech_tags, wc_background=None, font_path=None, max_words=200, max_font_size=100, save_path=None, wc_name... | a477c2926e97c86135623a2c7c844812be3be696 | <|skeleton|>
class WordCloud:
def __init__(self, stop_words_file=None, allow_speech_tags=conf.allow_speech_tags, wc_background=None, font_path=None, max_words=200, max_font_size=100, save_path=None, wc_name=None, topK=10):
""":param stop_words_file: -- str,停用词文件路径,若不是str则使用默认停用词文件 :param allow_speech_tags:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordCloud:
def __init__(self, stop_words_file=None, allow_speech_tags=conf.allow_speech_tags, wc_background=None, font_path=None, max_words=200, max_font_size=100, save_path=None, wc_name=None, topK=10):
""":param stop_words_file: -- str,停用词文件路径,若不是str则使用默认停用词文件 :param allow_speech_tags: -- 词性列表 :para... | the_stack_v2_python_sparse | WordCloud/word_cloud/word_cloud.py | FredZhao04/chinese-nlp | train | 5 | |
30f0bf9ea9e1102f441545bda407a19df9afa903 | [
"if os.path.isfile(file_path):\n self.file_path = file_path\nelse:\n raise OSError('file path provided does not have a file')\nif type(test_size) is float:\n self.test_size = test_size\nelse:\n self.test_size = 0.2",
"with open(self.file_path) as json_file:\n dictionary = json.load(json_file)\npath... | <|body_start_0|>
if os.path.isfile(file_path):
self.file_path = file_path
else:
raise OSError('file path provided does not have a file')
if type(test_size) is float:
self.test_size = test_size
else:
self.test_size = 0.2
<|end_body_0|>
<|bo... | Implementation of DataReader for the files containing all 278 features. | DataReader278Features | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testin... | stack_v2_sparse_classes_10k_train_004670 | 2,736 | no_license | [
{
"docstring": "Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testing.",
"name": "__init__",
"signature": "def __init__(self, file_path, test_size)"
},
{
"docstring": "Extracts 278 features from the specified f... | 2 | stack_v2_sparse_classes_30k_train_005360 | Implement the Python class `DataReader278Features` described below.
Class description:
Implementation of DataReader for the files containing all 278 features.
Method signatures and docstrings:
- def __init__(self, file_path, test_size): Init method :param file_path: file path containing a file of data. :param test_si... | Implement the Python class `DataReader278Features` described below.
Class description:
Implementation of DataReader for the files containing all 278 features.
Method signatures and docstrings:
- def __init__(self, file_path, test_size): Init method :param file_path: file path containing a file of data. :param test_si... | 9d751f6d6434fb9b418037cbaf928b0edd20a784 | <|skeleton|>
class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testing."""
... | the_stack_v2_python_sparse | reco_code/datareader_278_features.py | martheveldhuis/ReCo | train | 1 |
c891ea6c60d4b38eeb7717a4f9bb87c812324201 | [
"c = 1\nself.weight = weight\nself.age = age\nself.color = color\nc = 1",
"c = 1\nres = super().__new__(cls)\nc = 1\nreturn res"
] | <|body_start_0|>
c = 1
self.weight = weight
self.age = age
self.color = color
c = 1
<|end_body_0|>
<|body_start_1|>
c = 1
res = super().__new__(cls)
c = 1
return res
<|end_body_1|>
| Matryoshka | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matryoshka:
def __init__(self, weight, age, color):
"""Раскрашивает нашу болванку"""
<|body_0|>
def __new__(cls, *args, **kwargs):
"""Изготавливает пустую болванку"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
c = 1
self.weight = weight
... | stack_v2_sparse_classes_10k_train_004671 | 8,031 | no_license | [
{
"docstring": "Раскрашивает нашу болванку",
"name": "__init__",
"signature": "def __init__(self, weight, age, color)"
},
{
"docstring": "Изготавливает пустую болванку",
"name": "__new__",
"signature": "def __new__(cls, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006631 | Implement the Python class `Matryoshka` described below.
Class description:
Implement the Matryoshka class.
Method signatures and docstrings:
- def __init__(self, weight, age, color): Раскрашивает нашу болванку
- def __new__(cls, *args, **kwargs): Изготавливает пустую болванку | Implement the Python class `Matryoshka` described below.
Class description:
Implement the Matryoshka class.
Method signatures and docstrings:
- def __init__(self, weight, age, color): Раскрашивает нашу болванку
- def __new__(cls, *args, **kwargs): Изготавливает пустую болванку
<|skeleton|>
class Matryoshka:
def... | b3c1bc09a35d706d84a6ae67a484c7ae359cede8 | <|skeleton|>
class Matryoshka:
def __init__(self, weight, age, color):
"""Раскрашивает нашу болванку"""
<|body_0|>
def __new__(cls, *args, **kwargs):
"""Изготавливает пустую болванку"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Matryoshka:
def __init__(self, weight, age, color):
"""Раскрашивает нашу болванку"""
c = 1
self.weight = weight
self.age = age
self.color = color
c = 1
def __new__(cls, *args, **kwargs):
"""Изготавливает пустую болванку"""
c = 1
res ... | the_stack_v2_python_sparse | dasha_folder/lesson_17.py | Totoro2205/for_my_shiny_students | train | 0 | |
467b62c5c6dbd3ff8834c49ebb91a6b8b0e504c7 | [
"for k in range(len(self.mset) + 1):\n for comb in Combinations_setk(self.mset, k):\n yield comb",
"k = 0\nn = len(self.mset)\nb = binomial(n, k)\nwhile r >= b:\n r -= b\n k += 1\n b = binomial(n, k)\nreturn [self.mset[i] for i in from_rank(r, n, k)]",
"x = [self.mset.index(_) for _ in x]\nr ... | <|body_start_0|>
for k in range(len(self.mset) + 1):
for comb in Combinations_setk(self.mset, k):
yield comb
<|end_body_0|>
<|body_start_1|>
k = 0
n = len(self.mset)
b = binomial(n, k)
while r >= b:
r -= b
k += 1
b ... | Combinations_set | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Combinations_set:
def __iter__(self):
"""EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]"""
<|body_0|>
def unrank(self, r):
"""EXAMPLES:: sage: c = Combinations([1,2,3]) sage: c.list() == map(c.un... | stack_v2_sparse_classes_10k_train_004672 | 16,000 | no_license | [
{
"docstring": "EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]",
"name": "__iter__",
"signature": "def __iter__(self)"
},
{
"docstring": "EXAMPLES:: sage: c = Combinations([1,2,3]) sage: c.list() == map(c.unrank, range(c.car... | 3 | null | Implement the Python class `Combinations_set` described below.
Class description:
Implement the Combinations_set class.
Method signatures and docstrings:
- def __iter__(self): EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
- def unrank(self, r): ... | Implement the Python class `Combinations_set` described below.
Class description:
Implement the Combinations_set class.
Method signatures and docstrings:
- def __iter__(self): EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
- def unrank(self, r): ... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class Combinations_set:
def __iter__(self):
"""EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]"""
<|body_0|>
def unrank(self, r):
"""EXAMPLES:: sage: c = Combinations([1,2,3]) sage: c.list() == map(c.un... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Combinations_set:
def __iter__(self):
"""EXAMPLES:: sage: Combinations([1,2,3]).list() #indirect doctest [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]"""
for k in range(len(self.mset) + 1):
for comb in Combinations_setk(self.mset, k):
yield comb
def un... | the_stack_v2_python_sparse | sage/src/sage/combinat/combination.py | bopopescu/geosci | train | 0 | |
d7f47a058014efd4aa4e8f07b64b44942e6f85a9 | [
"assert self.user_id is not None\nbelongs_to_learnt_list = False\ngoals_limit_exceeded = False\nbelongs_to_learnt_list, goals_limit_exceeded = learner_progress_services.validate_and_add_topic_to_learn_goal(self.user_id, topic_id)\nself.values.update({'belongs_to_learnt_list': belongs_to_learnt_list, 'goals_limit_ex... | <|body_start_0|>
assert self.user_id is not None
belongs_to_learnt_list = False
goals_limit_exceeded = False
belongs_to_learnt_list, goals_limit_exceeded = learner_progress_services.validate_and_add_topic_to_learn_goal(self.user_id, topic_id)
self.values.update({'belongs_to_learn... | Handles operations related to the learner goals. | LearnerGoalsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnerGoalsHandler:
"""Handles operations related to the learner goals."""
def post(self, activity_type: str, topic_id: str) -> None:
"""Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type. topic_id: str. The ID of the topic."""
<|body_0... | stack_v2_sparse_classes_10k_train_004673 | 3,947 | permissive | [
{
"docstring": "Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type. topic_id: str. The ID of the topic.",
"name": "post",
"signature": "def post(self, activity_type: str, topic_id: str) -> None"
},
{
"docstring": "Removes a topic from the learner's learning... | 2 | stack_v2_sparse_classes_30k_train_000377 | Implement the Python class `LearnerGoalsHandler` described below.
Class description:
Handles operations related to the learner goals.
Method signatures and docstrings:
- def post(self, activity_type: str, topic_id: str) -> None: Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type... | Implement the Python class `LearnerGoalsHandler` described below.
Class description:
Handles operations related to the learner goals.
Method signatures and docstrings:
- def post(self, activity_type: str, topic_id: str) -> None: Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class LearnerGoalsHandler:
"""Handles operations related to the learner goals."""
def post(self, activity_type: str, topic_id: str) -> None:
"""Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type. topic_id: str. The ID of the topic."""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LearnerGoalsHandler:
"""Handles operations related to the learner goals."""
def post(self, activity_type: str, topic_id: str) -> None:
"""Adds a topic to the learner's learning goals. Args: activity_type: str. The activity type. topic_id: str. The ID of the topic."""
assert self.user_id i... | the_stack_v2_python_sparse | core/controllers/learner_goals.py | oppia/oppia | train | 6,172 |
bd487e09af6d18f93bf1d59df677765294db5a40 | [
"valid_places = (lite.Place(lite.TargetType.kFPGA, lite.PrecisionType.kFP16, lite.DataLayoutType.kNHWC), lite.Place(lite.TargetType.kHost, lite.PrecisionType.kFloat), lite.Place(lite.TargetType.kARM, lite.PrecisionType.kFloat))\nconfig = lite.CxxConfig()\nif model_dir:\n config.set_model_dir(model_dir)\nelse:\n ... | <|body_start_0|>
valid_places = (lite.Place(lite.TargetType.kFPGA, lite.PrecisionType.kFP16, lite.DataLayoutType.kNHWC), lite.Place(lite.TargetType.kHost, lite.PrecisionType.kFloat), lite.Place(lite.TargetType.kARM, lite.PrecisionType.kFloat))
config = lite.CxxConfig()
if model_dir:
... | cxx_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cxx_model:
def load_model(self, model_flie, param_file, thread_num, model_dir):
"""加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器"""
<|body_0|>
def data_feed(self, data_shape):
"""初始化CxxCongig模型输入数据张量 参数:数据形状, 预测器 返回:数据张量"""
<|body_1|>
def predict(self, ... | stack_v2_sparse_classes_10k_train_004674 | 3,563 | permissive | [
{
"docstring": "加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器",
"name": "load_model",
"signature": "def load_model(self, model_flie, param_file, thread_num, model_dir)"
},
{
"docstring": "初始化CxxCongig模型输入数据张量 参数:数据形状, 预测器 返回:数据张量",
"name": "data_feed",
"signature": "def data_feed(self, ... | 3 | null | Implement the Python class `cxx_model` described below.
Class description:
Implement the cxx_model class.
Method signatures and docstrings:
- def load_model(self, model_flie, param_file, thread_num, model_dir): 加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器
- def data_feed(self, data_shape): 初始化CxxCongig模型输入数据张量 参数:数... | Implement the Python class `cxx_model` described below.
Class description:
Implement the cxx_model class.
Method signatures and docstrings:
- def load_model(self, model_flie, param_file, thread_num, model_dir): 加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器
- def data_feed(self, data_shape): 初始化CxxCongig模型输入数据张量 参数:数... | afbd0e081763c53833617a4892d03043e644d641 | <|skeleton|>
class cxx_model:
def load_model(self, model_flie, param_file, thread_num, model_dir):
"""加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器"""
<|body_0|>
def data_feed(self, data_shape):
"""初始化CxxCongig模型输入数据张量 参数:数据形状, 预测器 返回:数据张量"""
<|body_1|>
def predict(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cxx_model:
def load_model(self, model_flie, param_file, thread_num, model_dir):
"""加载CxxCongig模型 参数:模型文件、模型参数文件、线程数、模型目录 返回:模型预测器"""
valid_places = (lite.Place(lite.TargetType.kFPGA, lite.PrecisionType.kFP16, lite.DataLayoutType.kNHWC), lite.Place(lite.TargetType.kHost, lite.PrecisionType.kFlo... | the_stack_v2_python_sparse | mastercar/eblite_smart_car-master/model.py | wpy-111/python | train | 1 | |
588b1e7ec922834ad5143bae0e228b55142a06a4 | [
"self.dimension = dimension\nself.a1 = np.array(a1)\nself.a2 = np.array(a2)\nself.a3 = np.array(a3)\nself.sites = []\nself.bonds = []\nself.Nsites = 0\nself.Nbonds = 0",
"if site.label == None:\n site.label = site_label_dir[str(self.Nsites)]\nif site.color == None:\n site.color = site_color_dir[str(self.Nsi... | <|body_start_0|>
self.dimension = dimension
self.a1 = np.array(a1)
self.a2 = np.array(a2)
self.a3 = np.array(a3)
self.sites = []
self.bonds = []
self.Nsites = 0
self.Nbonds = 0
<|end_body_0|>
<|body_start_1|>
if site.label == None:
sit... | Primitive cell of the lattice | Cell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitiv... | stack_v2_sparse_classes_10k_train_004675 | 7,577 | permissive | [
{
"docstring": "Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitive vector a3 : list third component of primitive vector",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_004765 | Implement the Python class `Cell` described below.
Class description:
Primitive cell of the lattice
Method signatures and docstrings:
- def __init__(self, dimension, a1, a2, a3): Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component o... | Implement the Python class `Cell` described below.
Class description:
Primitive cell of the lattice
Method signatures and docstrings:
- def __init__(self, dimension, a1, a2, a3): Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component o... | 9b6323857fc27b17056ad6c8520d4a10a23dad4b | <|skeleton|>
class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitiv... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitive vector a3 :... | the_stack_v2_python_sparse | moha/modelsystem/lattice.py | xujunyao0928/moha | train | 0 |
cfd7138c712b3a62643e83e1f03453e19bab8b26 | [
"l, r = (0, len(nums))\nwhile l < r:\n m = l + (r - l) // 2\n if nums[m] == target:\n return m\n elif nums[m] < target:\n l = m + 1\n else:\n r = m\nreturn -1",
"l, r = (0, len(nums) - 1)\nwhile l <= r:\n m = l + (r - l) // 2\n if nums[m] == target:\n return m\n el... | <|body_start_0|>
l, r = (0, len(nums))
while l < r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums[m] < target:
l = m + 1
else:
r = m
return -1
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
<|body_0|>
def search_1(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length ... | stack_v2_sparse_classes_10k_train_004676 | 1,522 | permissive | [
{
"docstring": "Two Pointers Running Time: O(log n) where n is the length of nums.",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) -> int"
},
{
"docstring": "Two Pointers Running Time: O(log n) where n is the length of nums.",
"name": "search_1",
"signatu... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Two Pointers Running Time: O(log n) where n is the length of nums.
- def search_1(self, nums: List[int], target: int) -> in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Two Pointers Running Time: O(log n) where n is the length of nums.
- def search_1(self, nums: List[int], target: int) -> in... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
<|body_0|>
def search_1(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums: List[int], target: int) -> int:
"""Two Pointers Running Time: O(log n) where n is the length of nums."""
l, r = (0, len(nums))
while l < r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums... | the_stack_v2_python_sparse | solutions/704_binary_search.py | YiqunPeng/leetcode_pro | train | 0 | |
d2478bf7780aa015a8d60e209b9e6684fa6a9346 | [
"self.glacier_retrieval_type = glacier_retrieval_type\nself.restore_objects = restore_objects\nself.search_job_uid = search_job_uid\nself.task_name = task_name\nself.vault_id = vault_id",
"if dictionary is None:\n return None\nglacier_retrieval_type = dictionary.get('glacierRetrievalType')\nrestore_objects = N... | <|body_start_0|>
self.glacier_retrieval_type = glacier_retrieval_type
self.restore_objects = restore_objects
self.search_job_uid = search_job_uid
self.task_name = task_name
self.vault_id = vault_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return... | Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current Cluster. Attributes: glacier_retrieval_type (GlacierRetrievalTypeEnum): Specifies the way data needs to b... | CreateRemoteVaultRestoreTaskParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRemoteVaultRestoreTaskParameters:
"""Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current Cluster. Attributes: glacier_retrieval_... | stack_v2_sparse_classes_10k_train_004677 | 4,811 | permissive | [
{
"docstring": "Constructor for the CreateRemoteVaultRestoreTaskParameters class",
"name": "__init__",
"signature": "def __init__(self, glacier_retrieval_type=None, restore_objects=None, search_job_uid=None, task_name=None, vault_id=None)"
},
{
"docstring": "Creates an instance of this model fro... | 2 | stack_v2_sparse_classes_30k_train_000360 | Implement the Python class `CreateRemoteVaultRestoreTaskParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current ... | Implement the Python class `CreateRemoteVaultRestoreTaskParameters` described below.
Class description:
Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CreateRemoteVaultRestoreTaskParameters:
"""Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current Cluster. Attributes: glacier_retrieval_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateRemoteVaultRestoreTaskParameters:
"""Implementation of the 'CreateRemoteVaultRestoreTaskParameters' model. Specifies settings required to create a task that restores the index and/or the Snapshots of a Protection Job from a remote Vault to the current Cluster. Attributes: glacier_retrieval_type (Glacier... | the_stack_v2_python_sparse | cohesity_management_sdk/models/create_remote_vault_restore_task_parameters.py | cohesity/management-sdk-python | train | 24 |
0305fb0d454ed58c554b012b4db6fb1813ecee58 | [
"if model is SyncQueue:\n return SYNC_QUEUE\nreturn None",
"if model is SyncQueue:\n return SYNC_QUEUE\nreturn None",
"if obj1._meta.model is SyncQueue and obj2._meta.model is SyncQueue:\n return True\nelif SyncQueue not in [obj1._meta.model, obj2._meta.model]:\n return None\nreturn False",
"if ap... | <|body_start_0|>
if model is SyncQueue:
return SYNC_QUEUE
return None
<|end_body_0|>
<|body_start_1|>
if model is SyncQueue:
return SYNC_QUEUE
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.model is SyncQueue and obj2._meta.model is SyncQueue:... | Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database. | SyncQueueRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
<|body_0|>
def db_fo... | stack_v2_sparse_classes_10k_train_004678 | 18,207 | permissive | [
{
"docstring": "Send all read operations on the SyncQueue model to SYNC_QUEUE.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Send all write operations on the SyncQueue model to SYNC_QUEUE.",
"name": "db_for_write",
"signature": "def db_f... | 4 | null | Implement the Python class `SyncQueueRouter` described below.
Class description:
Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on the SyncQueue ... | Implement the Python class `SyncQueueRouter` described below.
Class description:
Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on the SyncQueue ... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
<|body_0|>
def db_fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
if model is SyncQueue:
ret... | the_stack_v2_python_sparse | kolibri/core/device/models.py | learningequality/kolibri | train | 689 |
2619c35a0c04efc0995553f410c5c4bc14682c75 | [
"dp_max = [nums[0]] * len(nums)\ndp_min = [nums[0]] * len(nums)\nfor i in range(1, len(nums)):\n dp_max[i] = max(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])\n dp_min[i] = min(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])\nreturn max(dp_max)",
"max_now = min_now = max_prodcut = nu... | <|body_start_0|>
dp_max = [nums[0]] * len(nums)
dp_min = [nums[0]] * len(nums)
for i in range(1, len(nums)):
dp_max[i] = max(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])
dp_min[i] = min(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct1(self, nums: List[int]) -> int:
"""dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。"""
<|body_0|>
def maxProduct2(self, nums: List[int]) -> int:
"""Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_004679 | 2,021 | no_license | [
{
"docstring": "dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。",
"name": "maxProduct1",
"signature": "def maxProduct1(self, nums: List[int]) -> int"
},
{
"docstring": "Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。",
"name": "maxProduct2",
"signature": "def maxProduct2(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct1(self, nums: List[int]) -> int: dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。
- def maxProduct2(self, nums: List[int]) -> int: Kadane算法,类似053... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct1(self, nums: List[int]) -> int: dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。
- def maxProduct2(self, nums: List[int]) -> int: Kadane算法,类似053... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def maxProduct1(self, nums: List[int]) -> int:
"""dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。"""
<|body_0|>
def maxProduct2(self, nums: List[int]) -> int:
"""Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct1(self, nums: List[int]) -> int:
"""dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。"""
dp_max = [nums[0]] * len(nums)
dp_min = [nums[0]] * len(nums)
for i in range(1, len(nums)):
dp_max[i] = max(dp_max[i - 1] * nums[i], dp... | the_stack_v2_python_sparse | 152_maximum-product-subarray.py | helloocc/algorithm | train | 1 | |
ea9e14053c3cbd5b90c142ceff775c96ba8707ab | [
"i = 0\nfor num in nums:\n if num != val:\n nums[i] = num\n i += 1\nreturn i",
"for i in range(len(nums) - 1, -1, -1):\n if nums[i] == val:\n nums.pop(i)\nreturn len(nums)"
] | <|body_start_0|>
i = 0
for num in nums:
if num != val:
nums[i] = num
i += 1
return i
<|end_body_0|>
<|body_start_1|>
for i in range(len(nums) - 1, -1, -1):
if nums[i] == val:
nums.pop(i)
return len(nums)
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement_MK1(self, nums: List[int], val: int) -> int:
"""双指针法 Approach 1: Two Pointers"""
<|body_0|>
def removeElement_MK2(self, nums: List[int], val: int) -> int:
"""改进的双指针法,当要删除的元素很少时,速度更快 Approach 2: Two Pointers - when elements to remove are ra... | stack_v2_sparse_classes_10k_train_004680 | 692 | no_license | [
{
"docstring": "双指针法 Approach 1: Two Pointers",
"name": "removeElement_MK1",
"signature": "def removeElement_MK1(self, nums: List[int], val: int) -> int"
},
{
"docstring": "改进的双指针法,当要删除的元素很少时,速度更快 Approach 2: Two Pointers - when elements to remove are rare",
"name": "removeElement_MK2",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_MK1(self, nums: List[int], val: int) -> int: 双指针法 Approach 1: Two Pointers
- def removeElement_MK2(self, nums: List[int], val: int) -> int: 改进的双指针法,当要删除的元素很少时,速... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_MK1(self, nums: List[int], val: int) -> int: 双指针法 Approach 1: Two Pointers
- def removeElement_MK2(self, nums: List[int], val: int) -> int: 改进的双指针法,当要删除的元素很少时,速... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def removeElement_MK1(self, nums: List[int], val: int) -> int:
"""双指针法 Approach 1: Two Pointers"""
<|body_0|>
def removeElement_MK2(self, nums: List[int], val: int) -> int:
"""改进的双指针法,当要删除的元素很少时,速度更快 Approach 2: Two Pointers - when elements to remove are ra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement_MK1(self, nums: List[int], val: int) -> int:
"""双指针法 Approach 1: Two Pointers"""
i = 0
for num in nums:
if num != val:
nums[i] = num
i += 1
return i
def removeElement_MK2(self, nums: List[int], val: in... | the_stack_v2_python_sparse | 0027. Remove Element/Solution.py | faterazer/LeetCode | train | 4 | |
9e693986a4cb626cfd6ebfbaef62a86d5ae52e27 | [
"max_profit, min_price = (0, float('inf'))\nfor price in prices:\n min_price = min(min_price, price)\n profit = price - min_price\n max_profit = max(max_profit, profit)\nreturn max_profit",
"maxprofit = 0\nfor i in range(len(prices)):\n for j in range(i + 1, len(prices)):\n profit = prices[j] -... | <|body_start_0|>
max_profit, min_price = (0, float('inf'))
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
<|end_body_0|>
<|body_start_1|>
maxprofit = 0
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_brute_force(self, prices):
"""Brute Force Time O(n^2) space O(1) :type prices: List[int] :rtype: int"""
<|body_1|... | stack_v2_sparse_classes_10k_train_004681 | 1,037 | no_license | [
{
"docstring": "Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "Brute Force Time O(n^2) space O(1) :type prices: List[int] :rtype: int",
"name": "maxProfit_brute_force",
"sign... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int
- def maxProfit_brute_force(self, prices): Brute Force Time O(n^2) space ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int
- def maxProfit_brute_force(self, prices): Brute Force Time O(n^2) space ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_brute_force(self, prices):
"""Brute Force Time O(n^2) space O(1) :type prices: List[int] :rtype: int"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
"""Kadane's algorithm Time O(n) space O(1) :type prices: List[int] :rtype: int"""
max_profit, min_price = (0, float('inf'))
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_p... | the_stack_v2_python_sparse | LeetCode/Array/121_best_time_to_buy_and_sell_stock.py | XyK0907/for_work | train | 0 | |
590818b9021b8044953baffcdb23423b10962eb0 | [
"super().__init__()\nself.k_list = k_list\nself.data = data\nself.d = data.shape[-1]\nself.init_centroids = init_centroids\nself.frozen_centroids = frozen_centroids\nself.logger = logging.getLogger('Kmeans')\nself.debug = False\nself.epoch = epoch + 1",
"data = self.data\nlabels = []\ncentroids = []\ntqdm_batch =... | <|body_start_0|>
super().__init__()
self.k_list = k_list
self.data = data
self.d = data.shape[-1]
self.init_centroids = init_centroids
self.frozen_centroids = frozen_centroids
self.logger = logging.getLogger('Kmeans')
self.debug = False
self.epoch ... | Kmeans | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
<|body_0|>
def compute_clusters(self):
"""compute cluster Returns: torch.tensor, lis... | stack_v2_sparse_classes_10k_train_004682 | 3,988 | no_license | [
{
"docstring": "Performs many k-means clustering. Args: data (np.array N * dim): data to cluster",
"name": "__init__",
"signature": "def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False)"
},
{
"docstring": "compute cluster Returns: torch.tensor, list: clus_labels... | 2 | stack_v2_sparse_classes_30k_train_003175 | Implement the Python class `Kmeans` described below.
Class description:
Implement the Kmeans class.
Method signatures and docstrings:
- def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False): Performs many k-means clustering. Args: data (np.array N * dim): data to cluster
- def compute... | Implement the Python class `Kmeans` described below.
Class description:
Implement the Kmeans class.
Method signatures and docstrings:
- def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False): Performs many k-means clustering. Args: data (np.array N * dim): data to cluster
- def compute... | 1b82dd088e5475b45688bec44830f3e96ae65d32 | <|skeleton|>
class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
<|body_0|>
def compute_clusters(self):
"""compute cluster Returns: torch.tensor, lis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Kmeans:
def __init__(self, k_list, data, epoch=0, init_centroids=None, frozen_centroids=False):
"""Performs many k-means clustering. Args: data (np.array N * dim): data to cluster"""
super().__init__()
self.k_list = k_list
self.data = data
self.d = data.shape[-1]
... | the_stack_v2_python_sparse | pcs/models/clustering.py | andyincode2/PCS-FUDA | train | 0 | |
88f225d86c1b18605129320e5f8bcb6453145bfb | [
"super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs)\nidp_choices = utils.get_idp_choices()\nif idp_choices is not None:\n self.fields['provider_id'] = forms.TypedChoiceField(choices=idp_choices)",
"super(EnterpriseCustomerIdentityProviderAdminForm, self).clean()\nprovider_id = s... | <|body_start_0|>
super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs)
idp_choices = utils.get_idp_choices()
if idp_choices is not None:
self.fields['provider_id'] = forms.TypedChoiceField(choices=idp_choices)
<|end_body_0|>
<|body_start_1|>
supe... | Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField. | EnterpriseCustomerIdentityProviderAdminForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnterpriseCustomerIdentityProviderAdminForm:
"""Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField."""
def __init__(self, *arg... | stack_v2_sparse_classes_10k_train_004683 | 14,734 | no_license | [
{
"docstring": "Initialize the form. Substitutes CharField with TypedChoiceField for the provider_id field.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Final validations of model fields. 1. Validate that selected site for enterprise customer matche... | 2 | stack_v2_sparse_classes_30k_train_003763 | Implement the Python class `EnterpriseCustomerIdentityProviderAdminForm` described below.
Class description:
Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a Cha... | Implement the Python class `EnterpriseCustomerIdentityProviderAdminForm` described below.
Class description:
Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a Cha... | de3d1b297fa99d61cf32addb981cdfc55aec9891 | <|skeleton|>
class EnterpriseCustomerIdentityProviderAdminForm:
"""Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField."""
def __init__(self, *arg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnterpriseCustomerIdentityProviderAdminForm:
"""Alternate form for the EnterpriseCustomerIdentityProvider admin page. This form fetches identity providers from lms third_party_auth app. If third_party_auth app is not avilable it displays provider_id as a CharField."""
def __init__(self, *args, **kwargs):... | the_stack_v2_python_sparse | venvs/edxapp/lib/python2.7/site-packages/enterprise/admin/forms.py | UOMx/CITeS-VM-edxapp | train | 0 |
57b9fc03cd07705e7a03f717af91c5c3a89a16a1 | [
"self.delimiter = delimiter\nself.exclude_cols = exclude_cols\nself.fieldnames = fieldnames",
"with open(file, 'r') as f:\n reader = csv.DictReader(f, delimiter=self.delimiter, fieldnames=self.fieldnames)\n ncols = np.arange(len(reader.fieldnames))\n include_cols = np.delete(ncols, self.exclude_cols)\n ... | <|body_start_0|>
self.delimiter = delimiter
self.exclude_cols = exclude_cols
self.fieldnames = fieldnames
<|end_body_0|>
<|body_start_1|>
with open(file, 'r') as f:
reader = csv.DictReader(f, delimiter=self.delimiter, fieldnames=self.fieldnames)
ncols = np.arange... | FileReader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileReader:
def __init__(self, delimiter: str=',', exclude_cols: list=[], fieldnames: list=None):
"""Initialize object class to read a file. Args: delimiter (str): Delimiter used in the file (default `,`). exclude_cols (list): Exclude column in the file (default `None`). fieldnames (list... | stack_v2_sparse_classes_10k_train_004684 | 1,550 | permissive | [
{
"docstring": "Initialize object class to read a file. Args: delimiter (str): Delimiter used in the file (default `,`). exclude_cols (list): Exclude column in the file (default `None`). fieldnames (list): Names of the column in the file (default `None`).",
"name": "__init__",
"signature": "def __init__... | 2 | stack_v2_sparse_classes_30k_train_000299 | Implement the Python class `FileReader` described below.
Class description:
Implement the FileReader class.
Method signatures and docstrings:
- def __init__(self, delimiter: str=',', exclude_cols: list=[], fieldnames: list=None): Initialize object class to read a file. Args: delimiter (str): Delimiter used in the fil... | Implement the Python class `FileReader` described below.
Class description:
Implement the FileReader class.
Method signatures and docstrings:
- def __init__(self, delimiter: str=',', exclude_cols: list=[], fieldnames: list=None): Initialize object class to read a file. Args: delimiter (str): Delimiter used in the fil... | 29657c0b0f3952dd2e817bdfe8253f76800c2342 | <|skeleton|>
class FileReader:
def __init__(self, delimiter: str=',', exclude_cols: list=[], fieldnames: list=None):
"""Initialize object class to read a file. Args: delimiter (str): Delimiter used in the file (default `,`). exclude_cols (list): Exclude column in the file (default `None`). fieldnames (list... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileReader:
def __init__(self, delimiter: str=',', exclude_cols: list=[], fieldnames: list=None):
"""Initialize object class to read a file. Args: delimiter (str): Delimiter used in the file (default `,`). exclude_cols (list): Exclude column in the file (default `None`). fieldnames (list): Names of th... | the_stack_v2_python_sparse | end2you/data_generator/file_reader.py | end2you/end2you | train | 101 | |
8f920582e79521c1b77270695cae6f5a483c42c8 | [
"\"\"\":field\n Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity.\n \"\"\"\nself.d... | <|body_start_0|>
""":field
Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity.... | Data for an Obi collision material. | CollisionMaterial | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=Ma... | stack_v2_sparse_classes_10k_train_004685 | 4,244 | permissive | [
{
"docstring": ":param dynamic_friction: Percentage of relative tangential velocity removed in a collision, once the static friction threshold has been surpassed and the particle is moving relative to the surface. 0 means things will slide as if made of ice, 1 will result in total loss of tangential velocity. :... | 2 | null | Implement the Python class `CollisionMaterial` described below.
Class description:
Data for an Obi collision material.
Method signatures and docstrings:
- def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=Mat... | Implement the Python class `CollisionMaterial` described below.
Class description:
Data for an Obi collision material.
Method signatures and docstrings:
- def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=Mat... | 9df96fba455b327bb360d8dd5886d8754046c690 | <|skeleton|>
class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=Ma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CollisionMaterial:
"""Data for an Obi collision material."""
def __init__(self, dynamic_friction: float=0.3, static_friction: float=0.3, stickiness: float=0, stick_distance: float=0, friction_combine: MaterialCombineMode=MaterialCombineMode.average, stickiness_combine: MaterialCombineMode=MaterialCombine... | the_stack_v2_python_sparse | Python/tdw/obi_data/collision_materials/collision_material.py | threedworld-mit/tdw | train | 427 |
57de9a46dfbf33b117c2dfbb534a5020e019d520 | [
"ret = [0]\nfor i in range(1, len(pattern)):\n j = ret[i - 1]\n while j > 0 and pattern[j] != pattern[i]:\n j = ret[j - 1]\n ret.append(j + 1 if pattern[j] == pattern[i] else j)\nreturn ret",
"partial, j = (self.partial(P), 0)\nfor i in range(len(T)):\n while j > 0 and T[i] != P[j]:\n j ... | <|body_start_0|>
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
return ret
<|end_body_0|>
<|body_start_1|>
partial... | KMP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
<|body_0|>
def search(self, T, P):
"""KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_004686 | 45,905 | no_license | [
{
"docstring": "Calculate partial match table: String -> [Int]",
"name": "partial",
"signature": "def partial(self, pattern)"
},
{
"docstring": "KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T",
"name": "search",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_001087 | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def partial(self, pattern): Calculate partial match table: String -> [Int]
- def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o... | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def partial(self, pattern): Calculate partial match table: String -> [Int]
- def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o... | 7e9f47e1dc7c79802ad7ff692514f1314815515a | <|skeleton|>
class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
<|body_0|>
def search(self, T, P):
"""KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] ==... | the_stack_v2_python_sparse | python/820. Short Encoding of Words.py | forrest0402/leetcode | train | 0 | |
9bae58aa8fd472afea8bd1af5ba5b89fa2afbdd9 | [
"p0 = nm.array(p0, dtype=nm.float64)\np1 = nm.array(p1, dtype=nm.float64)\nname = 'line [%s, %s]' % (p0, p1)\nProbe.__init__(self, name=name, share_geometry=share_geometry, p0=p0, p1=p1, n_point=n_point)\ndirvec = self.p1 - self.p0\nself.length = nm.linalg.norm(dirvec)\nself.dirvec = dirvec / self.length",
"out =... | <|body_start_0|>
p0 = nm.array(p0, dtype=nm.float64)
p1 = nm.array(p1, dtype=nm.float64)
name = 'line [%s, %s]' % (p0, p1)
Probe.__init__(self, name=name, share_geometry=share_geometry, p0=p0, p1=p1, n_point=n_point)
dirvec = self.p1 - self.p0
self.length = nm.linalg.norm... | Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative, -n_point is used as an initial gues... | LineProbe | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineProbe:
"""Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative... | stack_v2_sparse_classes_10k_train_004687 | 21,182 | permissive | [
{
"docstring": "Parameters ---------- p0 : array_like The coordinates of the start point. p1 : array_like The coordinates of the end point.",
"name": "__init__",
"signature": "def __init__(self, p0, p1, n_point, share_geometry=True)"
},
{
"docstring": "Report the probe parameters.",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_004950 | Implement the Python class `LineProbe` described below.
Class description:
Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are dete... | Implement the Python class `LineProbe` described below.
Class description:
Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are dete... | 0c2d1690e764b601b2687be1e4261b82207ca366 | <|skeleton|>
class LineProbe:
"""Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LineProbe:
"""Probe variables along a line. If n_point is positive, that number of evenly spaced points is used. If n_point is None or non-positive, an adaptive refinement based on element diameters is used and the number of points and their spacing are determined automatically. If it is negative, -n_point is... | the_stack_v2_python_sparse | sfepy/discrete/probes.py | sfepy/sfepy | train | 651 |
830346597676594a708e350f622b68ef6f1b525d | [
"self.exclusion_list = BoxHolder()\nif initial_exclusion_list is not None:\n for initial in initial_exclusion_list:\n self.exclusion_list.add_box(initial)",
"excluded = self.exclusion_list.is_in_box(mz, rt)\nif excluded:\n return (True, 0.0)\nelse:\n return (False, 1.0)",
"rt = current_scan.rt\n... | <|body_start_0|>
self.exclusion_list = BoxHolder()
if initial_exclusion_list is not None:
for initial in initial_exclusion_list:
self.exclusion_list.add_box(initial)
<|end_body_0|>
<|body_start_1|>
excluded = self.exclusion_list.is_in_box(mz, rt)
if excluded:... | A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes. | TopNExclusion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusio... | stack_v2_sparse_classes_10k_train_004688 | 16,141 | permissive | [
{
"docstring": "Initialise a Top-N dynamic exclusion object Args: initial_exclusion_list: the initial list of boxes, if provided",
"name": "__init__",
"signature": "def __init__(self, initial_exclusion_list=None)"
},
{
"docstring": "Checks if a pair of (mz, rt) value is currently excluded by dyn... | 4 | stack_v2_sparse_classes_30k_train_006716 | Implement the Python class `TopNExclusion` described below.
Class description:
A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes.
Method signatures and docstrings:
- def __init__(self, initial_exclusion_list=None): Initialis... | Implement the Python class `TopNExclusion` described below.
Class description:
A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes.
Method signatures and docstrings:
- def __init__(self, initial_exclusion_list=None): Initialis... | e5d97ae4ff42d613fc55db51443e1e733999b908 | <|skeleton|>
class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusio... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusion_list: the i... | the_stack_v2_python_sparse | vimms/Exclusion.py | glasgowcompbio/vimms | train | 22 |
bd718d8b37f1acdab2f99917f36e36d98dd9537b | [
"rule_id = request.GET.get('rule_id', '0')\nrules = CouponRule.objects.filter(owner=request.manager, id=rule_id)\nc = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(request), 'second_nav_name': export.MALL_PROMOTION_SECOND_NAV, 'third_nav_name': e... | <|body_start_0|>
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_id)
c = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(request), 'second_nav_name': export.MALL_PROMOTI... | CouponInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(request):
"""增加库存"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_i... | stack_v2_sparse_classes_10k_train_004689 | 16,819 | no_license | [
{
"docstring": "添加库存页面",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "增加库存",
"name": "api_post",
"signature": "def api_post(request)"
}
] | 2 | null | Implement the Python class `CouponInfo` described below.
Class description:
Implement the CouponInfo class.
Method signatures and docstrings:
- def get(request): 添加库存页面
- def api_post(request): 增加库存 | Implement the Python class `CouponInfo` described below.
Class description:
Implement the CouponInfo class.
Method signatures and docstrings:
- def get(request): 添加库存页面
- def api_post(request): 增加库存
<|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(reques... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class CouponInfo:
def get(request):
"""添加库存页面"""
<|body_0|>
def api_post(request):
"""增加库存"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CouponInfo:
def get(request):
"""添加库存页面"""
rule_id = request.GET.get('rule_id', '0')
rules = CouponRule.objects.filter(owner=request.manager, id=rule_id)
c = RequestContext(request, {'first_nav_name': FIRST_NAV_NAME, 'second_navs': export.get_promotion_and_apps_second_navs(requ... | the_stack_v2_python_sparse | weapp/mall/promotion/coupon.py | chengdg/weizoom | train | 1 | |
d01d2d37164921bb9c2e22372dc99fc5dfb2f1d5 | [
"lru = LRUCache(4)\nself.assertIsInstance(lru, LRUCache)\nself.assertEqual(lru.capacity, 4)\nself.assertEqual(lru.length, 0)\nself.assertIsNone(lru.head)\nself.assertIsNone(lru.tail)\nself.assertEqual(lru.cache, {})",
"lru = LRUCache(2)\nlru.put('3', 3)\nlru.put('2', 2)\nlru.get('3')\nlru.put('1', 1)\nself.assert... | <|body_start_0|>
lru = LRUCache(4)
self.assertIsInstance(lru, LRUCache)
self.assertEqual(lru.capacity, 4)
self.assertEqual(lru.length, 0)
self.assertIsNone(lru.head)
self.assertIsNone(lru.tail)
self.assertEqual(lru.cache, {})
<|end_body_0|>
<|body_start_1|>
... | TestLRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
<|body_0|>
def test_removes_old_cached_values(self):
"""Does not contain old nodes if removed from cache"""
<|body_1|>
def test_moves_accessed_values_to_head(self... | stack_v2_sparse_classes_10k_train_004690 | 1,542 | permissive | [
{
"docstring": "Instantiates a new LRU Cache",
"name": "test_instantiates_new_lru_cache",
"signature": "def test_instantiates_new_lru_cache(self)"
},
{
"docstring": "Does not contain old nodes if removed from cache",
"name": "test_removes_old_cached_values",
"signature": "def test_remove... | 4 | stack_v2_sparse_classes_30k_train_002681 | Implement the Python class `TestLRUCache` described below.
Class description:
Implement the TestLRUCache class.
Method signatures and docstrings:
- def test_instantiates_new_lru_cache(self): Instantiates a new LRU Cache
- def test_removes_old_cached_values(self): Does not contain old nodes if removed from cache
- def... | Implement the Python class `TestLRUCache` described below.
Class description:
Implement the TestLRUCache class.
Method signatures and docstrings:
- def test_instantiates_new_lru_cache(self): Instantiates a new LRU Cache
- def test_removes_old_cached_values(self): Does not contain old nodes if removed from cache
- def... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
<|body_0|>
def test_removes_old_cached_values(self):
"""Does not contain old nodes if removed from cache"""
<|body_1|>
def test_moves_accessed_values_to_head(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestLRUCache:
def test_instantiates_new_lru_cache(self):
"""Instantiates a new LRU Cache"""
lru = LRUCache(4)
self.assertIsInstance(lru, LRUCache)
self.assertEqual(lru.capacity, 4)
self.assertEqual(lru.length, 0)
self.assertIsNone(lru.head)
self.assertIs... | the_stack_v2_python_sparse | src/leetcode/medium/lru-cache/test_lru_cache.py | nwthomas/code-challenges | train | 2 | |
7a21f8c4078a95825f26b57f50138744ae448ee9 | [
"super().__init__(sys_argv)\nlog.debug('Supplying Thread information from init of QApplication')\nself.setAttribute(Qt.AA_EnableHighDpiScaling)\nself.setStyle('Fusion')\nself.mainWindow = MainWindow()\nself.mainWindow.setWindowTitle('jet-tracker')\nself.mainWindow.show()",
"if issubclass(exc_type, KeyboardInterru... | <|body_start_0|>
super().__init__(sys_argv)
log.debug('Supplying Thread information from init of QApplication')
self.setAttribute(Qt.AA_EnableHighDpiScaling)
self.setStyle('Fusion')
self.mainWindow = MainWindow()
self.mainWindow.setWindowTitle('jet-tracker')
self.... | App | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
def __init__(self, sys_argv):
"""Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application."""
<|body_0|>
def handle_exception(exc_type, exc_value, exc_traceback):
"""Static method for handling uncaught ... | stack_v2_sparse_classes_10k_train_004691 | 2,711 | permissive | [
{
"docstring": "Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application.",
"name": "__init__",
"signature": "def __init__(self, sys_argv)"
},
{
"docstring": "Static method for handling uncaught exceptions. Parameters: exc_type(type): T... | 2 | stack_v2_sparse_classes_30k_train_002542 | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, sys_argv): Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application.
- def handle_exception(exc_type, exc_val... | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, sys_argv): Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application.
- def handle_exception(exc_type, exc_val... | 55a62be17cec19c3e3dc92d3805e72b191b7c112 | <|skeleton|>
class App:
def __init__(self, sys_argv):
"""Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application."""
<|body_0|>
def handle_exception(exc_type, exc_value, exc_traceback):
"""Static method for handling uncaught ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class App:
def __init__(self, sys_argv):
"""Constructor method for the App class. Parameters: sys_argv(list): Command - line arguments passed to the application."""
super().__init__(sys_argv)
log.debug('Supplying Thread information from init of QApplication')
self.setAttribute(Qt.AA_... | the_stack_v2_python_sparse | jet_tracking/main.py | pcdshub/jet_tracking | train | 3 | |
2d57e31e6c305401117a2256525f793e28fd296a | [
"sez = niz.split()\nself.x = int(sez[0])\nself.y = int(sez[1])",
"razd_krajišči = math.sqrt((krajišče1.x - krajišče2.x) ** 2 + (krajišče1.y - krajišče2.y) ** 2)\nrazd1 = math.sqrt((self.y - krajišče1.y) ** 2 + (self.x - krajišče1.x) ** 2)\nrazd2 = math.sqrt((self.y - krajišče2.y) ** 2 + (self.x - krajišče2.x) ** ... | <|body_start_0|>
sez = niz.split()
self.x = int(sez[0])
self.y = int(sez[1])
<|end_body_0|>
<|body_start_1|>
razd_krajišči = math.sqrt((krajišče1.x - krajišče2.x) ** 2 + (krajišče1.y - krajišče2.y) ** 2)
razd1 = math.sqrt((self.y - krajišče1.y) ** 2 + (self.x - krajišče1.x) ** 2... | Predstavlja točko s koordinatama x in y. | Točka | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Točka:
"""Predstavlja točko s koordinatama x in y."""
def __init__(self, niz):
"""Dobi niz oblike 'x y' in iz njega razbere točkini koordinati."""
<|body_0|>
def je_na_črti(self, krajišče1, krajišče2):
"""Preveri ali točka 'točka' leži na daljici med krajišče1 in... | stack_v2_sparse_classes_10k_train_004692 | 2,501 | no_license | [
{
"docstring": "Dobi niz oblike 'x y' in iz njega razbere točkini koordinati.",
"name": "__init__",
"signature": "def __init__(self, niz)"
},
{
"docstring": "Preveri ali točka 'točka' leži na daljici med krajišče1 in krajišče2.",
"name": "je_na_črti",
"signature": "def je_na_črti(self, k... | 2 | stack_v2_sparse_classes_30k_train_004289 | Implement the Python class `Točka` described below.
Class description:
Predstavlja točko s koordinatama x in y.
Method signatures and docstrings:
- def __init__(self, niz): Dobi niz oblike 'x y' in iz njega razbere točkini koordinati.
- def je_na_črti(self, krajišče1, krajišče2): Preveri ali točka 'točka' leži na dal... | Implement the Python class `Točka` described below.
Class description:
Predstavlja točko s koordinatama x in y.
Method signatures and docstrings:
- def __init__(self, niz): Dobi niz oblike 'x y' in iz njega razbere točkini koordinati.
- def je_na_črti(self, krajišče1, krajišče2): Preveri ali točka 'točka' leži na dal... | 32fd8fde84fa5c1e2d2b366d9d97bb9835a61ec4 | <|skeleton|>
class Točka:
"""Predstavlja točko s koordinatama x in y."""
def __init__(self, niz):
"""Dobi niz oblike 'x y' in iz njega razbere točkini koordinati."""
<|body_0|>
def je_na_črti(self, krajišče1, krajišče2):
"""Preveri ali točka 'točka' leži na daljici med krajišče1 in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Točka:
"""Predstavlja točko s koordinatama x in y."""
def __init__(self, niz):
"""Dobi niz oblike 'x y' in iz njega razbere točkini koordinati."""
sez = niz.split()
self.x = int(sez[0])
self.y = int(sez[1])
def je_na_črti(self, krajišče1, krajišče2):
"""Prever... | the_stack_v2_python_sparse | poininpolygon.py | EminaMerlakSusman/kattis-solutions | train | 0 |
415374d0cdf745a0774554af3f2a53b3363202a0 | [
"super(Discriminator, self).__init__()\nassert image_size % 16 == 0, 'image size must be a multiple of 16!'\nself.num_gpu = num_gpu\nself.layer = nn.Sequential()\nself.layer.add_module('init.{}-{}.conv'.format(num_channels, conv_dim), nn.Conv2d(num_channels, conv_dim, 4, 2, 1, bias=False))\nself.layer.add_module('i... | <|body_start_0|>
super(Discriminator, self).__init__()
assert image_size % 16 == 0, 'image size must be a multiple of 16!'
self.num_gpu = num_gpu
self.layer = nn.Sequential()
self.layer.add_module('init.{}-{}.conv'.format(num_channels, conv_dim), nn.Conv2d(num_channels, conv_dim,... | Model for Discriminator. | Discriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""Model for Discriminator."""
def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Discriminator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Discriminator model."""
<... | stack_v2_sparse_classes_10k_train_004693 | 7,633 | permissive | [
{
"docstring": "Init for Discriminator model.",
"name": "__init__",
"signature": "def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN)"
},
{
"docstring": "Forward step for Discriminator model.",
"name": "forward",
"signature": "def forward(self, input... | 2 | stack_v2_sparse_classes_30k_train_006305 | Implement the Python class `Discriminator` described below.
Class description:
Model for Discriminator.
Method signatures and docstrings:
- def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN): Init for Discriminator model.
- def forward(self, input): Forward step for Discriminato... | Implement the Python class `Discriminator` described below.
Class description:
Model for Discriminator.
Method signatures and docstrings:
- def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN): Init for Discriminator model.
- def forward(self, input): Forward step for Discriminato... | fd4498da35ace5a3d1696ff4fbec3568eddbe6a1 | <|skeleton|>
class Discriminator:
"""Model for Discriminator."""
def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Discriminator model."""
<|body_0|>
def forward(self, input):
"""Forward step for Discriminator model."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Discriminator:
"""Model for Discriminator."""
def __init__(self, num_channels, conv_dim, image_size, num_gpu, num_extra_layers, use_BN):
"""Init for Discriminator model."""
super(Discriminator, self).__init__()
assert image_size % 16 == 0, 'image size must be a multiple of 16!'
... | the_stack_v2_python_sparse | WGAN-GP/models.py | corenel/GAN-Zoo | train | 10 |
06a72380412a61e31b47c4be5bda90006cbcfe97 | [
"form_valid = isinstance(response, HttpResponseRedirect)\nif request.POST.get('_save') and form_valid:\n return redirect('admin:index')\nreturn response",
"try:\n singleton = self.model.objects.get()\nexcept (self.model.DoesNotExist, self.model.MultipleObjectsReturned):\n kwargs.setdefault('extra_context... | <|body_start_0|>
form_valid = isinstance(response, HttpResponseRedirect)
if request.POST.get('_save') and form_valid:
return redirect('admin:index')
return response
<|end_body_0|>
<|body_start_1|>
try:
singleton = self.model.objects.get()
except (self.mod... | Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton attribute to the div contain... | SingletonAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_10k_train_004694 | 3,870 | permissive | [
{
"docstring": "Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid.",
"name": "handle_save",
"signature": "def handle_save(self, request, response)"
},
{
"docstring": "Redirec... | 4 | stack_v2_sparse_classes_30k_train_002786 | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | c4fad2fe2cacaa21dd252a7407a84229dd20a46c | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton... | the_stack_v2_python_sparse | backend/apps/utils/admin.py | MadeInHaus/django-template | train | 1 |
c42548783cf725937afdc9c2d8c90be62fa27cae | [
"self.project_path = project_path\nself.package_path = package_path\nself.filename_path = filename_path\nself.project = self.package = self.filename = None\nif self.project_path is not None:\n self.project = wc_read_project(self.project_path)\nif self.package_path is not None:\n if wc_is_package(self.package_... | <|body_start_0|>
self.project_path = project_path
self.package_path = package_path
self.filename_path = filename_path
self.project = self.package = self.filename = None
if self.project_path is not None:
self.project = wc_read_project(self.project_path)
if self... | Represents a wc path. | WCPath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WCPath:
"""Represents a wc path."""
def __init__(self, project_path, package_path, filename_path):
"""Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filename_path is the path to the wc filename. Either project_p... | stack_v2_sparse_classes_10k_train_004695 | 19,804 | no_license | [
{
"docstring": "Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filename_path is the path to the wc filename. Either project_path or package_path or both aren't None.",
"name": "__init__",
"signature": "def __init__(self, project_pa... | 3 | stack_v2_sparse_classes_30k_train_001558 | Implement the Python class `WCPath` described below.
Class description:
Represents a wc path.
Method signatures and docstrings:
- def __init__(self, project_path, package_path, filename_path): Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filen... | Implement the Python class `WCPath` described below.
Class description:
Represents a wc path.
Method signatures and docstrings:
- def __init__(self, project_path, package_path, filename_path): Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filen... | fd75a75371ae33740a68913ca8ab64a9e8e6654a | <|skeleton|>
class WCPath:
"""Represents a wc path."""
def __init__(self, project_path, package_path, filename_path):
"""Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filename_path is the path to the wc filename. Either project_p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WCPath:
"""Represents a wc path."""
def __init__(self, project_path, package_path, filename_path):
"""Constructs a new WCPath object. project_path is the path to the project wc. package_path is the path to the package wc. filename_path is the path to the wc filename. Either project_path or packag... | the_stack_v2_python_sparse | osc2/oscargs.py | openSUSE/osc2 | train | 16 |
baf53e7da6ecad69cd56647b7e9a54103e28fb5d | [
"num_issues = ProcessingIssue.objects.filter(project=project).count()\nlast_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first()\nresolveable_issues, has_more = ProcessingIssue.objects.find_resolved(project_id=project.id)\nreprocessing_issues = ReprocessingReport.objects.filter(proje... | <|body_start_0|>
num_issues = ProcessingIssue.objects.filter(project=project).count()
last_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first()
resolveable_issues, has_more = ProcessingIssue.objects.find_resolved(project_id=project.id)
reprocessing_issues ... | ProjectProcessingIssuesEndpoint | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectProcessingIssuesEndpoint:
def get(self, request, project):
"""List a project's processing issues."""
<|body_0|>
def delete(self, request, project):
"""This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox"""
... | stack_v2_sparse_classes_10k_train_004696 | 4,504 | permissive | [
{
"docstring": "List a project's processing issues.",
"name": "get",
"signature": "def get(self, request, project)"
},
{
"docstring": "This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox",
"name": "delete",
"signature": "def delete(self, re... | 2 | stack_v2_sparse_classes_30k_train_005407 | Implement the Python class `ProjectProcessingIssuesEndpoint` described below.
Class description:
Implement the ProjectProcessingIssuesEndpoint class.
Method signatures and docstrings:
- def get(self, request, project): List a project's processing issues.
- def delete(self, request, project): This deletes all open pro... | Implement the Python class `ProjectProcessingIssuesEndpoint` described below.
Class description:
Implement the ProjectProcessingIssuesEndpoint class.
Method signatures and docstrings:
- def get(self, request, project): List a project's processing issues.
- def delete(self, request, project): This deletes all open pro... | b937615079d7b24dc225a83b99b1b65da932fc66 | <|skeleton|>
class ProjectProcessingIssuesEndpoint:
def get(self, request, project):
"""List a project's processing issues."""
<|body_0|>
def delete(self, request, project):
"""This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectProcessingIssuesEndpoint:
def get(self, request, project):
"""List a project's processing issues."""
num_issues = ProcessingIssue.objects.filter(project=project).count()
last_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first()
resolveable... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_processingissues.py | atlassian/sentry | train | 1 | |
f77e4a6a531897333011cdc2b314447b56386524 | [
"with mock.patch('sys.stdout.buffer.write') as mock_write:\n utils.binary_print('hello')\n mock_write.assert_called_with('hello\\n')",
"with mock.patch('sys.stdout.buffer.write') as mock_write:\n utils.binary_print(b'hello')\n mock_write.assert_called_with(b'hello\\n')"
] | <|body_start_0|>
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print('hello')
mock_write.assert_called_with('hello\n')
<|end_body_0|>
<|body_start_1|>
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print(b'hello')
... | Tests for utils.binary_print. | BinaryPrintTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
<|body_0|>
def test_binary_string(self):
"""Tests that utils.binary_print can print a bianry string."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004697 | 5,775 | permissive | [
{
"docstring": "Tests that utils.binary_print can print a regular string.",
"name": "test_string",
"signature": "def test_string(self)"
},
{
"docstring": "Tests that utils.binary_print can print a bianry string.",
"name": "test_binary_string",
"signature": "def test_binary_string(self)"
... | 2 | null | Implement the Python class `BinaryPrintTest` described below.
Class description:
Tests for utils.binary_print.
Method signatures and docstrings:
- def test_string(self): Tests that utils.binary_print can print a regular string.
- def test_binary_string(self): Tests that utils.binary_print can print a bianry string. | Implement the Python class `BinaryPrintTest` described below.
Class description:
Tests for utils.binary_print.
Method signatures and docstrings:
- def test_string(self): Tests that utils.binary_print can print a regular string.
- def test_binary_string(self): Tests that utils.binary_print can print a bianry string.
... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
<|body_0|>
def test_binary_string(self):
"""Tests that utils.binary_print can print a bianry string."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print('hello')
mock_write.assert_called_with('hello\n'... | the_stack_v2_python_sparse | infra/utils_test.py | google/oss-fuzz | train | 9,438 |
30e47e03e2a52a31911b7356ecbed74d613e2bec | [
"from sims4communitylib.utils.sims.common_gender_utils import CommonGenderUtils\nif CommonGenderUtils.is_male(sim_info):\n return CommonGender.MALE\nelif CommonGenderUtils.is_female(sim_info):\n return CommonGender.FEMALE\nreturn CommonGender.INVALID",
"if gender == CommonGender.INVALID:\n return None\ni... | <|body_start_0|>
from sims4communitylib.utils.sims.common_gender_utils import CommonGenderUtils
if CommonGenderUtils.is_male(sim_info):
return CommonGender.MALE
elif CommonGenderUtils.is_female(sim_info):
return CommonGender.FEMALE
return CommonGender.INVALID
<|en... | Custom Gender enum containing all genders. | CommonGender | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents wha... | stack_v2_sparse_classes_10k_train_004698 | 3,081 | permissive | [
{
"docstring": "get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents what gender a Sim is or CommonGender.INVALID if their gender cannot be determined. :rtype: CommonGender",
"name": "get_gender",
... | 3 | stack_v2_sparse_classes_30k_train_003953 | Implement the Python class `CommonGender` described below.
Class description:
Custom Gender enum containing all genders.
Method signatures and docstrings:
- def get_gender(sim_info: SimInfo) -> 'CommonGender': get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_in... | Implement the Python class `CommonGender` described below.
Class description:
Custom Gender enum containing all genders.
Method signatures and docstrings:
- def get_gender(sim_info: SimInfo) -> 'CommonGender': get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_in... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents wha... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents what gender a Si... | the_stack_v2_python_sparse | src/sims4communitylib/enums/common_gender.py | velocist/TS4CheatsInfo | train | 1 |
790dbd28b7d09ada3db7eb5fed8c3e4e869ef927 | [
"if not head or not head.next or (not head.next.next):\n return\ncur = head\nlst = []\nwhile cur:\n lst.append(cur)\n cur = cur.next\ni = 0\nj = -i if i < 0 else -(i + 1)\nwhile lst[i] != lst[j]:\n lst[i].next = lst[j]\n i = j\n j = -i if i < 0 else -(i + 1)\nlst[i].next = None",
"if not head or... | <|body_start_0|>
if not head or not head.next or (not head.next.next):
return
cur = head
lst = []
while cur:
lst.append(cur)
cur = cur.next
i = 0
j = -i if i < 0 else -(i + 1)
while lst[i] != lst[j]:
lst[i].next = ls... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
<|body_0|>
def reorderList(self, head):
"""07/26/2018 05:45"""
<|body_1|>
def reorderList(self, head: Optional[ListNode]) -> None:
"""Do not return anything, modify head in-place inste... | stack_v2_sparse_classes_10k_train_004699 | 3,188 | no_license | [
{
"docstring": "07/26/2018 05:12",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": "07/26/2018 05:45",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": "Do not return anything, modify head in-place instead.",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): 07/26/2018 05:12
- def reorderList(self, head): 07/26/2018 05:45
- def reorderList(self, head: Optional[ListNode]) -> None: Do not return anything, m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): 07/26/2018 05:12
- def reorderList(self, head): 07/26/2018 05:45
- def reorderList(self, head: Optional[ListNode]) -> None: Do not return anything, m... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
<|body_0|>
def reorderList(self, head):
"""07/26/2018 05:45"""
<|body_1|>
def reorderList(self, head: Optional[ListNode]) -> None:
"""Do not return anything, modify head in-place inste... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
if not head or not head.next or (not head.next.next):
return
cur = head
lst = []
while cur:
lst.append(cur)
cur = cur.next
i = 0
j = -i if i < 0 else -(i + ... | the_stack_v2_python_sparse | leetcode/solved/143_Reorder_List/solution.py | sungminoh/algorithms | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.