blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
48b2e6ab04d420b27bf456ea452c39997d7260d2 | [
"super().__init__()\nif equivalence_library is None:\n from qiskit.circuit.library.standard_gates.equivalence_library import _sel\n equivalence_library = _sel\nif target is not None:\n supported_gates = target.operation_names\nelif supported_gates is None:\n raise ValueError('One of ``supported_gates`` ... | <|body_start_0|>
super().__init__()
if equivalence_library is None:
from qiskit.circuit.library.standard_gates.equivalence_library import _sel
equivalence_library = _sel
if target is not None:
supported_gates = target.operation_names
elif supported_gat... | Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recursively decomposed. The recursion is stopped once all parameterized gates are in ``supported_gat... | TranslateParameterizedGates | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TranslateParameterizedGates:
"""Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recursively decomposed. The recursion is stop... | stack_v2_sparse_classes_75kplus_train_004300 | 7,377 | permissive | [
{
"docstring": "Args: supported_gates: A list of suppported basis gates specified as string. If ``None``, a ``target`` must be provided. equivalence_library: The equivalence library to translate the gates. Defaults to the equivalence library of all Qiskit standard gates. target: A :class:`.Target` containing th... | 2 | stack_v2_sparse_classes_30k_train_020573 | Implement the Python class `TranslateParameterizedGates` described below.
Class description:
Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recurs... | Implement the Python class `TranslateParameterizedGates` described below.
Class description:
Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recurs... | 0b51250e219ca303654fc28a318c21366584ccd3 | <|skeleton|>
class TranslateParameterizedGates:
"""Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recursively decomposed. The recursion is stop... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TranslateParameterizedGates:
"""Translate parameterized gates to a supported basis set. Once a parameterized instruction is found that is not in the ``supported_gates`` list, the instruction is decomposed one level and the parameterized sub-blocks are recursively decomposed. The recursion is stopped once all ... | the_stack_v2_python_sparse | qiskit/transpiler/passes/basis/translate_parameterized.py | 1ucian0/qiskit-terra | train | 6 |
754acbeab75b9b4efddca5e91182675e27f18af3 | [
"super(ConvTransformerDecoderBlock, self).__init__()\nself.d_v = d_v\nself.batch_norm = nn.BatchNorm3d(d_v)\nself.dec_only_mha_module = ConvMultiHeadAttention(num_heads, d_v, d_v)\nself.comb_enc_dec_mha_module = ConvMultiHeadAttention(num_heads, d_v, d_v)\nself.ff_module = nn.Sequential(nn.Conv2d(d_v, d_ff, 3, padd... | <|body_start_0|>
super(ConvTransformerDecoderBlock, self).__init__()
self.d_v = d_v
self.batch_norm = nn.BatchNorm3d(d_v)
self.dec_only_mha_module = ConvMultiHeadAttention(num_heads, d_v, d_v)
self.comb_enc_dec_mha_module = ConvMultiHeadAttention(num_heads, d_v, d_v)
self... | ConvTransformerDecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvTransformerDecoderBlock:
def __init__(self, num_heads, d_v, d_ff):
"""Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimensionality (number of features) of the values :param d_ff: Intermediate dimensionality of the feed-forward part of th... | stack_v2_sparse_classes_75kplus_train_004301 | 26,416 | no_license | [
{
"docstring": "Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimensionality (number of features) of the values :param d_ff: Intermediate dimensionality of the feed-forward part of this decoder block",
"name": "__init__",
"signature": "def __init__(self, nu... | 3 | null | Implement the Python class `ConvTransformerDecoderBlock` described below.
Class description:
Implement the ConvTransformerDecoderBlock class.
Method signatures and docstrings:
- def __init__(self, num_heads, d_v, d_ff): Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimen... | Implement the Python class `ConvTransformerDecoderBlock` described below.
Class description:
Implement the ConvTransformerDecoderBlock class.
Method signatures and docstrings:
- def __init__(self, num_heads, d_v, d_ff): Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimen... | da2872999c38c3aab0357cb6e7e0db9100638505 | <|skeleton|>
class ConvTransformerDecoderBlock:
def __init__(self, num_heads, d_v, d_ff):
"""Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimensionality (number of features) of the values :param d_ff: Intermediate dimensionality of the feed-forward part of th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvTransformerDecoderBlock:
def __init__(self, num_heads, d_v, d_ff):
"""Constructor :param num_heads: The number of heads to use in multi-head attention :param d_v: Dimensionality (number of features) of the values :param d_ff: Intermediate dimensionality of the feed-forward part of this decoder blo... | the_stack_v2_python_sparse | src/models/self_attention/submodules.py | MichiganCOG/video-frame-inpainting | train | 9 | |
964c4fc85ab2fbb725dafba33e568382593a5e73 | [
"try:\n res = requests.get(args.get('url'), timeout=1)\n if res.status_code == 200:\n ServerMachine.save(args)\n else:\n abort(400, message='Server machine disabled 服务器不可用')\nexcept Exception as e:\n abort(500, message='Save server machine failed')",
"try:\n machines = ServerMachine.q... | <|body_start_0|>
try:
res = requests.get(args.get('url'), timeout=1)
if res.status_code == 200:
ServerMachine.save(args)
else:
abort(400, message='Server machine disabled 服务器不可用')
except Exception as e:
abort(500, message='S... | ServerMachineSrv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerMachineSrv:
def save(cls, args: dict):
"""功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常"""
<|body_0|>
def list(cls):
"""功能: 列出所有的服务器 :return: 成功返回服务器信息列表,url,is_master,status三个字段的信息, data的值格式如下: [ {'url':'http://172.10.10.184:6800', 'is_master': '0', 'status': '1'}... | stack_v2_sparse_classes_75kplus_train_004302 | 2,096 | no_license | [
{
"docstring": "功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常",
"name": "save",
"signature": "def save(cls, args: dict)"
},
{
"docstring": "功能: 列出所有的服务器 :return: 成功返回服务器信息列表,url,is_master,status三个字段的信息, data的值格式如下: [ {'url':'http://172.10.10.184:6800', 'is_master': '0', 'status': '1'} ] 失败则返回空列表",
... | 3 | null | Implement the Python class `ServerMachineSrv` described below.
Class description:
Implement the ServerMachineSrv class.
Method signatures and docstrings:
- def save(cls, args: dict): 功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常
- def list(cls): 功能: 列出所有的服务器 :return: 成功返回服务器信息列表,url,is_master,status三个字段的信息, data的值格式如下: [... | Implement the Python class `ServerMachineSrv` described below.
Class description:
Implement the ServerMachineSrv class.
Method signatures and docstrings:
- def save(cls, args: dict): 功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常
- def list(cls): 功能: 列出所有的服务器 :return: 成功返回服务器信息列表,url,is_master,status三个字段的信息, data的值格式如下: [... | b6b2175da6c53572cd3a1c11ea2e0cf7fe59027a | <|skeleton|>
class ServerMachineSrv:
def save(cls, args: dict):
"""功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常"""
<|body_0|>
def list(cls):
"""功能: 列出所有的服务器 :return: 成功返回服务器信息列表,url,is_master,status三个字段的信息, data的值格式如下: [ {'url':'http://172.10.10.184:6800', 'is_master': '0', 'status': '1'}... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerMachineSrv:
def save(cls, args: dict):
"""功能: 添加服务器 :return: 成功返回success, 失败返回相应的异常"""
try:
res = requests.get(args.get('url'), timeout=1)
if res.status_code == 200:
ServerMachine.save(args)
else:
abort(400, message='Ser... | the_stack_v2_python_sparse | ScrapyKeeper/service/ServerMachineSrv.py | Miss-chan/ScrapyKeeper | train | 0 | |
9e47d023686ece645382a63815da1c5e97720387 | [
"super(SFEWrapper, self).__init__()\nself.agent = agent\nself.baseline_type = baseline_type",
"scores = self.agent(*args, **kwargs)\ndistr = Categorical(logits=scores)\nentropy = distr.entropy()\nsample = distr.sample()\nreturn (sample, scores, entropy)"
] | <|body_start_0|>
super(SFEWrapper, self).__init__()
self.agent = agent
self.baseline_type = baseline_type
<|end_body_0|>
<|body_start_1|>
scores = self.agent(*args, **kwargs)
distr = Categorical(logits=scores)
entropy = distr.entropy()
sample = distr.sample()
... | SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for the Categorical). | SFEWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SFEWrapper:
"""SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for the Categorical)."""
def __init__... | stack_v2_sparse_classes_75kplus_train_004303 | 10,120 | permissive | [
{
"docstring": "Arguments: agent -- The agent to be wrapped. agent.forward() has to output scores over the categories baseline_type {str} -- which baseline to use. Either 'runavg' or 'sample'.",
"name": "__init__",
"signature": "def __init__(self, agent, baseline_type)"
},
{
"docstring": "Forwar... | 2 | stack_v2_sparse_classes_30k_train_046530 | Implement the Python class `SFEWrapper` described below.
Class description:
SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for... | Implement the Python class `SFEWrapper` described below.
Class description:
SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for... | e161e55432f5e30fedf7eae8ae11189c01bcd54a | <|skeleton|>
class SFEWrapper:
"""SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for the Categorical)."""
def __init__... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SFEWrapper:
"""SFE Wrapper for a network. Assumes that the during the forward pass, the network returns scores over the potential output categories. The wrapper transforms them into a tuple of (sample from the Categorical, log-prob of the sample, entropy for the Categorical)."""
def __init__(self, agent,... | the_stack_v2_python_sparse | mnist_ssvae/lvmhelpers/sfe.py | Zirui0623/EvSoftmax | train | 0 |
d31615874aec78fdadfebbc7a1914d2896e54659 | [
"super().__init__()\nself.coupling_map = coupling_map\nself.layout = initial_layout",
"new_dag = DAGCircuit()\nif self.layout is None:\n self.layout = Layout.generate_trivial_layout(*dag.qregs.values())\nfor layer in dag.serial_layers():\n subdag = layer['graph']\n for cnot_node in subdag.named_nodes('cx... | <|body_start_0|>
super().__init__()
self.coupling_map = coupling_map
self.layout = initial_layout
<|end_body_0|>
<|body_start_1|>
new_dag = DAGCircuit()
if self.layout is None:
self.layout = Layout.generate_trivial_layout(*dag.qregs.values())
for layer in dag... | Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]-- | CXDirection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CXDirection:
"""Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]--"""
def __init__(self, coupling_map, initial_layout=None):
"""Args: coupling... | stack_v2_sparse_classes_75kplus_train_004304 | 3,750 | permissive | [
{
"docstring": "Args: coupling_map (CouplingMap): Directed graph represented a coupling map. initial_layout (Layout): The initial layout of the DAG.",
"name": "__init__",
"signature": "def __init__(self, coupling_map, initial_layout=None)"
},
{
"docstring": "Flips the cx nodes to match the direc... | 2 | null | Implement the Python class `CXDirection` described below.
Class description:
Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]--
Method signatures and docstrings:
- def __init__... | Implement the Python class `CXDirection` described below.
Class description:
Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]--
Method signatures and docstrings:
- def __init__... | abf6c23d4ab6c63f9c01c7434fb46321e6a69200 | <|skeleton|>
class CXDirection:
"""Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]--"""
def __init__(self, coupling_map, initial_layout=None):
"""Args: coupling... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CXDirection:
"""Rearranges the direction of the cx nodes to make the circuit compatible with the directed coupling map. It uses this equivalence:: ---(+)--- --[H]---.---[H]-- | = | ----.---- --[H]--(+)--[H]--"""
def __init__(self, coupling_map, initial_layout=None):
"""Args: coupling_map (Couplin... | the_stack_v2_python_sparse | qiskit/transpiler/passes/mapping/cx_direction.py | indian-institute-of-science-qc/qiskit-aakash | train | 37 |
2e956274b3b34bf3b6d16f62f453ae2ef87ef3fb | [
"from sktime.distances._distance_alignment_paths import compute_lcss_return_path\nfrom sktime.distances._lcss_numba import _sequence_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, it... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_lcss_return_path
from sktime.distances._lcss_numba import _sequence_cost_matrix
from sktime.distances.lower_bounding import resolve_bounding_matrix
from sktime.utils.numba.njit import njit
_bounding_m... | Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence that is common to two discrete series based on the edit distance. This approach ... | _LcssDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LcssDistance:
"""Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence that is common to two discrete series b... | stack_v2_sparse_classes_75kplus_train_004305 | 9,185 | permissive | [
{
"docstring": "Create a no_python compiled lcss distance alignment path callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array ... | 2 | stack_v2_sparse_classes_30k_train_006574 | Implement the Python class `_LcssDistance` described below.
Class description:
Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence ... | Implement the Python class `_LcssDistance` described below.
Class description:
Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence ... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _LcssDistance:
"""Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence that is common to two discrete series b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _LcssDistance:
"""Longest common subsequence (LCSS) between two time series. The LCSS distance for time series is based on the solution to the longest common subsequence problem in pattern matching [1]. The typical problem is to find the longest subsequence that is common to two discrete series based on the e... | the_stack_v2_python_sparse | sktime/distances/_lcss.py | sktime/sktime | train | 1,117 |
8f92fed1e4b980fae92ff03f10315330171ba983 | [
"self.x = x\nself.y = y\nself._epochs_completed = 0\nself.sample_size = x.shape[0]\nself._index_in_epoch = 0",
"start = self._index_in_epoch\nif self._epochs_completed == 0 and start == 0 and shuffle:\n perm0 = np.arange(self.sample_size)\n np.random.shuffle(perm0)\n self._x = self.x[perm0]\n self._y ... | <|body_start_0|>
self.x = x
self.y = y
self._epochs_completed = 0
self.sample_size = x.shape[0]
self._index_in_epoch = 0
<|end_body_0|>
<|body_start_1|>
start = self._index_in_epoch
if self._epochs_completed == 0 and start == 0 and shuffle:
perm0 = np... | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
def __init__(self, x, y):
""":param x: shape, sample_size * dimension :param y: shape, sample_size * 1"""
<|body_0|>
def next_batch(self, batch_size, shuffle=True):
"""Return the next 'batch_size' examples from this dataset. :param batch_size: :param shuffle... | stack_v2_sparse_classes_75kplus_train_004306 | 2,404 | no_license | [
{
"docstring": ":param x: shape, sample_size * dimension :param y: shape, sample_size * 1",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "Return the next 'batch_size' examples from this dataset. :param batch_size: :param shuffle: :return:",
"name": "next_batc... | 3 | stack_v2_sparse_classes_30k_train_024389 | Implement the Python class `Dataset` described below.
Class description:
Implement the Dataset class.
Method signatures and docstrings:
- def __init__(self, x, y): :param x: shape, sample_size * dimension :param y: shape, sample_size * 1
- def next_batch(self, batch_size, shuffle=True): Return the next 'batch_size' e... | Implement the Python class `Dataset` described below.
Class description:
Implement the Dataset class.
Method signatures and docstrings:
- def __init__(self, x, y): :param x: shape, sample_size * dimension :param y: shape, sample_size * 1
- def next_batch(self, batch_size, shuffle=True): Return the next 'batch_size' e... | f7ac2a587ceda4e0b711fbb0476a0f854c75b4a3 | <|skeleton|>
class Dataset:
def __init__(self, x, y):
""":param x: shape, sample_size * dimension :param y: shape, sample_size * 1"""
<|body_0|>
def next_batch(self, batch_size, shuffle=True):
"""Return the next 'batch_size' examples from this dataset. :param batch_size: :param shuffle... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
def __init__(self, x, y):
""":param x: shape, sample_size * dimension :param y: shape, sample_size * 1"""
self.x = x
self.y = y
self._epochs_completed = 0
self.sample_size = x.shape[0]
self._index_in_epoch = 0
def next_batch(self, batch_size, shuff... | the_stack_v2_python_sparse | PlasticityKer/modelval/dataset.py | ShuangLiBCM/Plasticity_ker | train | 1 | |
a9747ce41ff499347bf66d2de1eadd68e0cacc14 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AdministrativeUnit()",
"from .directory_object import DirectoryObject\nfrom .extension import Extension\nfrom .scoped_role_membership import ScopedRoleMembership\nfrom .directory_object import DirectoryObject\nfrom .extension import Ex... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AdministrativeUnit()
<|end_body_0|>
<|body_start_1|>
from .directory_object import DirectoryObject
from .extension import Extension
from .scoped_role_membership import ScopedRole... | AdministrativeUnit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdministrativeUnit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AdministrativeUnit:
"""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 obje... | stack_v2_sparse_classes_75kplus_train_004307 | 4,322 | 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: AdministrativeUnit",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_000170 | Implement the Python class `AdministrativeUnit` described below.
Class description:
Implement the AdministrativeUnit class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AdministrativeUnit: Creates a new instance of the appropriate class based on disc... | Implement the Python class `AdministrativeUnit` described below.
Class description:
Implement the AdministrativeUnit class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AdministrativeUnit: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AdministrativeUnit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AdministrativeUnit:
"""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 obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdministrativeUnit:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AdministrativeUnit:
"""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: Ad... | the_stack_v2_python_sparse | msgraph/generated/models/administrative_unit.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2f1ad7ac7f6050c2778e9142cf1a6d1b48f016f3 | [
"if output_image_shape[0] % 2 == 1 or output_image_shape[1] % 2 == 1:\n raise NotImplementedError(f'Image width and height should be even numbers: {output_image_shape}, odd numbers not supported.')\nself.output_image_shape = np.array((output_image_shape[0], output_image_shape[1]))\nself.frame_preprocessing = fra... | <|body_start_0|>
if output_image_shape[0] % 2 == 1 or output_image_shape[1] % 2 == 1:
raise NotImplementedError(f'Image width and height should be even numbers: {output_image_shape}, odd numbers not supported.')
self.output_image_shape = np.array((output_image_shape[0], output_image_shape[1]... | The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping | RealDataset | [
"CC-BY-4.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealDataset:
"""The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping"""
def __init__(self, frame_preprocessing: BaseFramePreprocessing, output_image_shape: ... | stack_v2_sparse_classes_75kplus_train_004308 | 4,683 | permissive | [
{
"docstring": ":param frame_preprocessing: the FramePreprocessing object containing the image preprocessing logic :param output_image_shape: the desired output size of the images",
"name": "__init__",
"signature": "def __init__(self, frame_preprocessing: BaseFramePreprocessing, output_image_shape: Tupl... | 2 | null | Implement the Python class `RealDataset` described below.
Class description:
The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `RealDataset` described below.
Class description:
The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping
Method signatures and docstrings:
- def __init__(sel... | fb1d77eac56538569f639ab58a62470bff10f04c | <|skeleton|>
class RealDataset:
"""The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping"""
def __init__(self, frame_preprocessing: BaseFramePreprocessing, output_image_shape: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RealDataset:
"""The RealDataset takes a raw image and apply the FramePreprocessing, it also ensures all the resulting images have the same size, by expanding the region if necessary, or by simply cropping"""
def __init__(self, frame_preprocessing: BaseFramePreprocessing, output_image_shape: Tuple[int, in... | the_stack_v2_python_sparse | wormpose/images/real_dataset.py | iteal/wormpose | train | 45 |
8065e1ce33a4190914cc02812d1d5db4dd1b07e8 | [
"super().__init__(*args, **kwargs)\nself.extra_price_fields = []\nself.subtotal = Decimal('0.0')\nself.total = Decimal('0.0')\nself.current_total = Decimal('0.0')",
"if not isinstance(value, Decimal):\n value = Decimal(value)\nself.extra_price_fields.append((label, value))\nself.current_total += value",
"sel... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.extra_price_fields = []
self.subtotal = Decimal('0.0')
self.total = Decimal('0.0')
self.current_total = Decimal('0.0')
<|end_body_0|>
<|body_start_1|>
if not isinstance(value, Decimal):
value = Decimal(v... | Holder for the quantity and pointer to actual `Product`s. | CartItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartItem:
"""Holder for the quantity and pointer to actual `Product`s."""
def __init__(self, *args, **kwargs):
"""Hold extra fields to display to the user (ex. taxes, discount)."""
<|body_0|>
def add_modifier(self, label, value):
"""Add rebates/penales to the car... | stack_v2_sparse_classes_75kplus_train_004309 | 33,820 | permissive | [
{
"docstring": "Hold extra fields to display to the user (ex. taxes, discount).",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add rebates/penales to the cart item when cart is being rendered/ordered.",
"name": "add_modifier",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_041161 | Implement the Python class `CartItem` described below.
Class description:
Holder for the quantity and pointer to actual `Product`s.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Hold extra fields to display to the user (ex. taxes, discount).
- def add_modifier(self, label, value): Add rebat... | Implement the Python class `CartItem` described below.
Class description:
Holder for the quantity and pointer to actual `Product`s.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Hold extra fields to display to the user (ex. taxes, discount).
- def add_modifier(self, label, value): Add rebat... | 84c4fa10aefbd792a956cef3d727623ca78cb5fd | <|skeleton|>
class CartItem:
"""Holder for the quantity and pointer to actual `Product`s."""
def __init__(self, *args, **kwargs):
"""Hold extra fields to display to the user (ex. taxes, discount)."""
<|body_0|>
def add_modifier(self, label, value):
"""Add rebates/penales to the car... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartItem:
"""Holder for the quantity and pointer to actual `Product`s."""
def __init__(self, *args, **kwargs):
"""Hold extra fields to display to the user (ex. taxes, discount)."""
super().__init__(*args, **kwargs)
self.extra_price_fields = []
self.subtotal = Decimal('0.0'... | the_stack_v2_python_sparse | market/checkout/models.py | katomaso/django-market | train | 0 |
412f56d37953828168a990f05e663165e334e00e | [
"current_user_reviews = request.user.reviews.all()\nserializer = self.get_serializer(instance=current_user_reviews, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"current_user_reviews = request.user.reviews_of.all()\nserializer = self.get_serializer(instance=current_user_reviews, many=... | <|body_start_0|>
current_user_reviews = request.user.reviews.all()
serializer = self.get_serializer(instance=current_user_reviews, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
current_user_reviews = request.user.reviews_of.all()
... | ViewSet for viewing reviews. | UserReviewViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserReviewViewSet:
"""ViewSet for viewing reviews."""
def from_me(self, request, *args, **kwargs):
"""Return list of reviews from current user."""
<|body_0|>
def to_me(self, request, *args, **kwargs):
"""Return list of reviews about current user."""
<|bod... | stack_v2_sparse_classes_75kplus_train_004310 | 3,759 | no_license | [
{
"docstring": "Return list of reviews from current user.",
"name": "from_me",
"signature": "def from_me(self, request, *args, **kwargs)"
},
{
"docstring": "Return list of reviews about current user.",
"name": "to_me",
"signature": "def to_me(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052901 | Implement the Python class `UserReviewViewSet` described below.
Class description:
ViewSet for viewing reviews.
Method signatures and docstrings:
- def from_me(self, request, *args, **kwargs): Return list of reviews from current user.
- def to_me(self, request, *args, **kwargs): Return list of reviews about current u... | Implement the Python class `UserReviewViewSet` described below.
Class description:
ViewSet for viewing reviews.
Method signatures and docstrings:
- def from_me(self, request, *args, **kwargs): Return list of reviews from current user.
- def to_me(self, request, *args, **kwargs): Return list of reviews about current u... | 0879ade24685b628624dce06698f8a0afd042000 | <|skeleton|>
class UserReviewViewSet:
"""ViewSet for viewing reviews."""
def from_me(self, request, *args, **kwargs):
"""Return list of reviews from current user."""
<|body_0|>
def to_me(self, request, *args, **kwargs):
"""Return list of reviews about current user."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserReviewViewSet:
"""ViewSet for viewing reviews."""
def from_me(self, request, *args, **kwargs):
"""Return list of reviews from current user."""
current_user_reviews = request.user.reviews.all()
serializer = self.get_serializer(instance=current_user_reviews, many=True)
r... | the_stack_v2_python_sparse | camp-python-2021-find-me-develop/apps/users/api/views.py | rhanmar/oi_projects_summer_2021 | train | 0 |
0ebf0cd9e831cb61ab6346fd09200285b76a0de5 | [
"if _debug:\n IOGroup._debug('__init__')\nIOCB.__init__(self)\nself.ioMembers = []\nself.ioState = COMPLETED\nself.ioComplete.set()",
"if _debug:\n IOGroup._debug('Add %r', iocb)\nself.ioMembers.append(iocb)\nself.ioState = PENDING\nself.ioComplete.clear()\niocb.add_callback(self.group_callback)",
"if _de... | <|body_start_0|>
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
<|end_body_0|>
<|body_start_1|>
if _debug:
IOGroup._debug('Add %r', iocb)
self.ioMembers.append(i... | IOGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_75kplus_train_004311 | 39,489 | permissive | [
{
"docstring": "Initialize a group.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add an IOCB to the group, you can also add other groups.",
"name": "add",
"signature": "def add(self, iocb)"
},
{
"docstring": "Callback when a child iocb completes.",
... | 4 | stack_v2_sparse_classes_30k_train_031899 | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IOGroup:
def __init__(self):
"""Initialize a group."""
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
def add(self, iocb):
"""Add an IOCB to the group, you can... | the_stack_v2_python_sparse | sandbox/io.py | JoelBender/bacpypes | train | 284 | |
cd6b3db956ce3f23bb665fe90e3dcccc7a8b1fc9 | [
"data = []\nif not root:\n return data\ncur = [root]\nwhile cur:\n next = []\n for node in cur:\n if node:\n data.append(node.val)\n next.append(node.left)\n next.append(node.right)\n else:\n data.append(None)\n cur = next\nreturn data",
"if no... | <|body_start_0|>
data = []
if not root:
return data
cur = [root]
while cur:
next = []
for node in cur:
if node:
data.append(node.val)
next.append(node.left)
next.append(node.ri... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004312 | 2,776 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_010725 | 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:... | 2df1a58aa9474f2ecec2ee7c45ebf12466181391 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
data = []
if not root:
return data
cur = [root]
while cur:
next = []
for node in cur:
if node:
... | the_stack_v2_python_sparse | SerializeAndDeserializeBinaryTree.py | zjuzpz/Algorithms | train | 2 | |
2aa37973f000896d6317b2964e0783f309c6e0c6 | [
"seen = set()\nnum = list(str(n))\nsum = 0\nwhile True:\n for i in num:\n sum += int(i) ** 2\n if sum == 1:\n return True\n if sum in seen:\n return False\n seen.add(sum)\n num = list(str(sum))\n sum = 0",
"def get_next(n):\n sum = 0\n num = list(str(n))\n for i in ... | <|body_start_0|>
seen = set()
num = list(str(n))
sum = 0
while True:
for i in num:
sum += int(i) ** 2
if sum == 1:
return True
if sum in seen:
return False
seen.add(sum)
num = list... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy_1(self, n):
"""*使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)"""
<|body_0|>
def isHappy_2(self, n):
"""*使用两个指针 时间复杂度 o(logn) 空间复杂度 o(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_004313 | 1,243 | no_license | [
{
"docstring": "*使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)",
"name": "isHappy_1",
"signature": "def isHappy_1(self, n)"
},
{
"docstring": "*使用两个指针 时间复杂度 o(logn) 空间复杂度 o(1)",
"name": "isHappy_2",
"signature": "def isHappy_2(self, n)... | 2 | stack_v2_sparse_classes_30k_train_014584 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy_1(self, n): *使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)
- def isHappy_2(self, n): *使用两个指针 时间复杂度 o(logn) 空间复杂度 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy_1(self, n): *使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)
- def isHappy_2(self, n): *使用两个指针 时间复杂度 o(logn) 空间复杂度 ... | ebf9503d4bc6d4335c463aa2b4622dd7df55fb87 | <|skeleton|>
class Solution:
def isHappy_1(self, n):
"""*使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)"""
<|body_0|>
def isHappy_2(self, n):
"""*使用两个指针 时间复杂度 o(logn) 空间复杂度 o(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isHappy_1(self, n):
"""*使用set 检查数字是否在哈希集中需要O(1)的时间,而对于其他数据结构,则需要O(n)的时间。选择正确的数据结构是解决这些问题的关键部分。 时间复杂度 o(logn) 空间复杂度 o(logn)"""
seen = set()
num = list(str(n))
sum = 0
while True:
for i in num:
sum += int(i) ** 2
if su... | the_stack_v2_python_sparse | 202_happy_number.py | huuu97/LeetCode | train | 0 | |
f7c7b8f1e85dcc4b42c917f4352be00537f8187b | [
"self['user'] = None\nself['use_keyring'] = False\nself['keyring_service'] = 'SR tools'\nself['server'] = 'www.studentrobotics.org'\nself['https_port'] = 443\ntry:\n self.update_from_file(get_config_filename())\nexcept OSError:\n pass",
"with open(fname) as file:\n d = yaml.safe_load(file)\nif d is not N... | <|body_start_0|>
self['user'] = None
self['use_keyring'] = False
self['keyring_service'] = 'SR tools'
self['server'] = 'www.studentrobotics.org'
self['https_port'] = 443
try:
self.update_from_file(get_config_filename())
except OSError:
pass... | Configuration reader for the tools. | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Configuration reader for the tools."""
def __init__(self):
"""Create a new configuration reader with the default configuration values set."""
<|body_0|>
def update_from_file(self, fname):
"""Update the config from the given YAML file :param str fname: ... | stack_v2_sparse_classes_75kplus_train_004314 | 3,258 | no_license | [
{
"docstring": "Create a new configuration reader with the default configuration values set.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the config from the given YAML file :param str fname: The filename of the YAML file. :raises IOError: If the YAML file ca... | 4 | stack_v2_sparse_classes_30k_train_030229 | Implement the Python class `Config` described below.
Class description:
Configuration reader for the tools.
Method signatures and docstrings:
- def __init__(self): Create a new configuration reader with the default configuration values set.
- def update_from_file(self, fname): Update the config from the given YAML fi... | Implement the Python class `Config` described below.
Class description:
Configuration reader for the tools.
Method signatures and docstrings:
- def __init__(self): Create a new configuration reader with the default configuration values set.
- def update_from_file(self, fname): Update the config from the given YAML fi... | c97cea716311004129bdbf3651712ba3e970c1ff | <|skeleton|>
class Config:
"""Configuration reader for the tools."""
def __init__(self):
"""Create a new configuration reader with the default configuration values set."""
<|body_0|>
def update_from_file(self, fname):
"""Update the config from the given YAML file :param str fname: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
"""Configuration reader for the tools."""
def __init__(self):
"""Create a new configuration reader with the default configuration values set."""
self['user'] = None
self['use_keyring'] = False
self['keyring_service'] = 'SR tools'
self['server'] = 'www.stude... | the_stack_v2_python_sparse | sr/tools/config.py | srobo/tools | train | 4 |
18927d88eab6aaf565372ecb99ee9e18706c1b6c | [
"grad = x.sigmoid()\nctx['probabilities'] = grad\nreturn grad",
"probs = ctx['probabilities']\nres_grad = grad * probs * (1 - probs)\nreturn res_grad"
] | <|body_start_0|>
grad = x.sigmoid()
ctx['probabilities'] = grad
return grad
<|end_body_0|>
<|body_start_1|>
probs = ctx['probabilities']
res_grad = grad * probs * (1 - probs)
return res_grad
<|end_body_1|>
| The sigmoid gradient function. | GradSigmoid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradSigmoid:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCT... | stack_v2_sparse_classes_75kplus_train_004315 | 27,230 | permissive | [
{
"docstring": "Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor): The operand on which to apply the sigmoid function Returns: sigmoid(x) (MPCTensor): The sigmoid approximation applied ... | 2 | null | Implement the Python class `GradSigmoid` described below.
Class description:
The sigmoid gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor: Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context use... | Implement the Python class `GradSigmoid` described below.
Class description:
The sigmoid gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor: Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context use... | ee6ac74050acd03c3088104855d0b8e4ab3e03fa | <|skeleton|>
class GradSigmoid:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCT... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradSigmoid:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the sigmoid operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor): The o... | the_stack_v2_python_sparse | src/sympc/grads/grad_functions.py | shubhank-saxena/SyMPC | train | 1 |
e75855a24e6fa08965eedcdea5cc645d78d197b9 | [
"parser.add_argument('--model', required=True, help='Name of the model.')\nparser.add_argument('--version', help='Name of the version. If unspecified, the default version of the model will be used.')\ngroup = parser.add_mutually_exclusive_group(required=True)\njson_flag = group.add_argument('--json-instances', '--i... | <|body_start_0|>
parser.add_argument('--model', required=True, help='Name of the model.')
parser.add_argument('--version', help='Name of the version. If unspecified, the default version of the model will be used.')
group = parser.add_mutually_exclusive_group(required=True)
json_flag = gr... | Run Cloud ML online prediction. | Predict | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predict:
"""Run Cloud ML online prediction."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were pro... | stack_v2_sparse_classes_75kplus_train_004316 | 4,895 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value ... | 2 | stack_v2_sparse_classes_30k_train_033174 | Implement the Python class `Predict` described below.
Class description:
Run Cloud ML online prediction.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the ar... | Implement the Python class `Predict` described below.
Class description:
Run Cloud ML online prediction.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All the ar... | c97dd7b906e5ef3ec157581fd0bcadd3e3fc220e | <|skeleton|>
class Predict:
"""Run Cloud ML online prediction."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predict:
"""Run Cloud ML online prediction."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('--model', required=True, help='Name of the model.')
parser.add_argument('--version', help='Name of the version. If unspecified, the default version of the m... | the_stack_v2_python_sparse | files/home/gcloud/google-cloud-sdk/lib/surface/ml/predict.py | vo0doO/com.termux | train | 2 |
1db74666e1a6c0582590688112e98b3d0c64c960 | [
"self.name = name\nself.word_vector = word_vector\nself.rnn_size = state_size\nself.length_limit = length_limit\nself.learning_rate_start = 0.001\nself.global_step = tf.Variable(0, trainable=False)\nself.learning_rate = tf.train.exponential_decay(self.learning_rate_start, self.global_step, 30, 0.96, staircase=True)... | <|body_start_0|>
self.name = name
self.word_vector = word_vector
self.rnn_size = state_size
self.length_limit = length_limit
self.learning_rate_start = 0.001
self.global_step = tf.Variable(0, trainable=False)
self.learning_rate = tf.train.exponential_decay(self.le... | AssignmentRNNModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentRNNModel:
def __init__(self, length_limit, word_vector, state_size, name):
"""Function: Initialization."""
<|body_0|>
def RnnModel(self):
"""Function: Build the RNN model."""
<|body_1|>
def LossFunction(self):
"""Function: Define loss f... | stack_v2_sparse_classes_75kplus_train_004317 | 17,808 | no_license | [
{
"docstring": "Function: Initialization.",
"name": "__init__",
"signature": "def __init__(self, length_limit, word_vector, state_size, name)"
},
{
"docstring": "Function: Build the RNN model.",
"name": "RnnModel",
"signature": "def RnnModel(self)"
},
{
"docstring": "Function: De... | 5 | stack_v2_sparse_classes_30k_val_001574 | Implement the Python class `AssignmentRNNModel` described below.
Class description:
Implement the AssignmentRNNModel class.
Method signatures and docstrings:
- def __init__(self, length_limit, word_vector, state_size, name): Function: Initialization.
- def RnnModel(self): Function: Build the RNN model.
- def LossFunc... | Implement the Python class `AssignmentRNNModel` described below.
Class description:
Implement the AssignmentRNNModel class.
Method signatures and docstrings:
- def __init__(self, length_limit, word_vector, state_size, name): Function: Initialization.
- def RnnModel(self): Function: Build the RNN model.
- def LossFunc... | 929e28c3ea5aec63bc655035c48d96d2d3cff5bc | <|skeleton|>
class AssignmentRNNModel:
def __init__(self, length_limit, word_vector, state_size, name):
"""Function: Initialization."""
<|body_0|>
def RnnModel(self):
"""Function: Build the RNN model."""
<|body_1|>
def LossFunction(self):
"""Function: Define loss f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssignmentRNNModel:
def __init__(self, length_limit, word_vector, state_size, name):
"""Function: Initialization."""
self.name = name
self.word_vector = word_vector
self.rnn_size = state_size
self.length_limit = length_limit
self.learning_rate_start = 0.001
... | the_stack_v2_python_sparse | Ao_Zhang/assignment3/assignment3.py | ZhangAoCanada/CSI5138_Assignments | train | 1 | |
fb7b86666d2cc65ea663da18fb4a08aa8788a22d | [
"self.model = model.eval()\nself.save_dir = save_dir\nif os.path.exists(save_dir) is False:\n os.makedirs(save_dir)",
"path = os.path.join(self.save_path, save_name + '.npy')\nif os.path.exists(path) is True:\n print('{} already exist'.format(path))\n return False\ntry:\n extracted_feature = self.mode... | <|body_start_0|>
self.model = model.eval()
self.save_dir = save_dir
if os.path.exists(save_dir) is False:
os.makedirs(save_dir)
<|end_body_0|>
<|body_start_1|>
path = os.path.join(self.save_path, save_name + '.npy')
if os.path.exists(path) is True:
print(... | BaseFeatureExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
<|body_0|>
def extract_feature(self, video, save_name):
"""Extract feature from video and save as save_path... | stack_v2_sparse_classes_75kplus_train_004318 | 3,195 | no_license | [
{
"docstring": "Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save",
"name": "__init__",
"signature": "def __init__(self, model, save_dir)"
},
{
"docstring": "Extract feature from video and save as save_path/save_name.npy Args: video (Tensor): Video Te... | 3 | stack_v2_sparse_classes_30k_train_000393 | Implement the Python class `BaseFeatureExtractor` described below.
Class description:
Implement the BaseFeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, model, save_dir): Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save
- def extract_feature(... | Implement the Python class `BaseFeatureExtractor` described below.
Class description:
Implement the BaseFeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, model, save_dir): Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save
- def extract_feature(... | dc6fdb5ed4ee7746e731cbe449ce83a0831eb860 | <|skeleton|>
class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
<|body_0|>
def extract_feature(self, video, save_name):
"""Extract feature from video and save as save_path... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
self.model = model.eval()
self.save_dir = save_dir
if os.path.exists(save_dir) is False:
os.makedirs(save_... | the_stack_v2_python_sparse | agents/base.py | robinstart/video2text_abr | train | 5 | |
664d0cd8a14df0c733193adf7cf4a6c6e7748a5c | [
"filtered = [x for x in self if ue_id in x.ue_measurements]\ncells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrp'], reverse=True)\nreturn CellPool(cells)",
"filtered = [x for x in self if ue_id in x.ue_measurements]\ncells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrq'], revers... | <|body_start_0|>
filtered = [x for x in self if ue_id in x.ue_measurements]
cells = sorted(filtered, key=lambda x: x.ue_measurements[ue_id]['rsrp'], reverse=True)
return CellPool(cells)
<|end_body_0|>
<|body_start_1|>
filtered = [x for x in self if ue_id in x.ue_measurements]
ce... | EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods | CellPool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CellPool:
"""EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rsrp(self, ue_id):
"""Return list sorted by rsrp for the specified address."""
<|body_0|>
def sort_by_rsrq(self, ue_id):
"""Return list sorted... | stack_v2_sparse_classes_75kplus_train_004319 | 5,209 | permissive | [
{
"docstring": "Return list sorted by rsrp for the specified address.",
"name": "sort_by_rsrp",
"signature": "def sort_by_rsrp(self, ue_id)"
},
{
"docstring": "Return list sorted by rsrq for the specified address.",
"name": "sort_by_rsrq",
"signature": "def sort_by_rsrq(self, ue_id)"
}... | 4 | stack_v2_sparse_classes_30k_train_053157 | Implement the Python class `CellPool` described below.
Class description:
EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods
Method signatures and docstrings:
- def sort_by_rsrp(self, ue_id): Return list sorted by rsrp for the specified address.
- def sort_by_rsrq(self, ue_id... | Implement the Python class `CellPool` described below.
Class description:
EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods
Method signatures and docstrings:
- def sort_by_rsrp(self, ue_id): Return list sorted by rsrp for the specified address.
- def sort_by_rsrq(self, ue_id... | eda52649f855722fdec1d02e25a28c61a8fbda06 | <|skeleton|>
class CellPool:
"""EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rsrp(self, ue_id):
"""Return list sorted by rsrp for the specified address."""
<|body_0|>
def sort_by_rsrq(self, ue_id):
"""Return list sorted... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CellPool:
"""EmPOWER cell pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rsrp(self, ue_id):
"""Return list sorted by rsrp for the specified address."""
filtered = [x for x in self if ue_id in x.ue_measurements]
cells = sorted(filtere... | the_stack_v2_python_sparse | empower/core/cellpool.py | imec-idlab/sdn_wifi_manager | train | 0 |
5b1199bfdf2f0cd32f6d85c026e29c1243a36afe | [
"start = kwargs.get('start', '')\nend = kwargs.get('end', start)\norigin = kwargs.get('origin', '').strip()\npath = kwargs.get('path', '').strip()\nif start:\n self.index_by_date(start, end)\n cherrypy.response.status = 204\n return\nif origin == 'gcp/appengine':\n self.index_by_gcp_file(path)\n cher... | <|body_start_0|>
start = kwargs.get('start', '')
end = kwargs.get('end', start)
origin = kwargs.get('origin', '').strip()
path = kwargs.get('path', '').strip()
if start:
self.index_by_date(start, end)
cherrypy.response.status = 204
return
... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def POST(self, **kwargs: str) -> None:
"""Dispatch to a subhandler based on the URL path."""
<|body_0|>
def index_by_date(start: str, end: str) -> None:
"""Index logs in combined format based on a date range."""
<|body_1|>
def index_by_gcp_fi... | stack_v2_sparse_classes_75kplus_train_004320 | 2,422 | no_license | [
{
"docstring": "Dispatch to a subhandler based on the URL path.",
"name": "POST",
"signature": "def POST(self, **kwargs: str) -> None"
},
{
"docstring": "Index logs in combined format based on a date range.",
"name": "index_by_date",
"signature": "def index_by_date(start: str, end: str) ... | 3 | stack_v2_sparse_classes_30k_train_006540 | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def POST(self, **kwargs: str) -> None: Dispatch to a subhandler based on the URL path.
- def index_by_date(start: str, end: str) -> None: Index logs in combined format based ... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def POST(self, **kwargs: str) -> None: Dispatch to a subhandler based on the URL path.
- def index_by_date(start: str, end: str) -> None: Index logs in combined format based ... | 7129415303b94d5d10b2c29ec432f0c7d41cc651 | <|skeleton|>
class Controller:
def POST(self, **kwargs: str) -> None:
"""Dispatch to a subhandler based on the URL path."""
<|body_0|>
def index_by_date(start: str, end: str) -> None:
"""Index logs in combined format based on a date range."""
<|body_1|>
def index_by_gcp_fi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def POST(self, **kwargs: str) -> None:
"""Dispatch to a subhandler based on the URL path."""
start = kwargs.get('start', '')
end = kwargs.get('end', start)
origin = kwargs.get('origin', '').strip()
path = kwargs.get('path', '').strip()
if start:
... | the_stack_v2_python_sparse | apps/logindex/main.py | lovett/medley | train | 6 | |
536563c680f65385764d84e0b2d0b534c5a77ed1 | [
"self.father = father\nself.row = row\nself.column = column\nself.h = distance((row, column), (target_pos[0], target_pos[1]))\nif not father:\n self.g = 0\nelse:\n self.g = self.father.g + values[map[row][column]]\nself.f = self.h + self.g",
"result = ''\nresult += 'Fila: ' + str(self.row)\nresult += ' Colu... | <|body_start_0|>
self.father = father
self.row = row
self.column = column
self.h = distance((row, column), (target_pos[0], target_pos[1]))
if not father:
self.g = 0
else:
self.g = self.father.g + values[map[row][column]]
self.f = self.h + s... | @brief Representa un nodo(posible estado) en el A* | Nodo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nodo:
"""@brief Representa un nodo(posible estado) en el A*"""
def __init__(self, row, column, target_pos, father=None):
"""@brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param target_pos Posicion del objetivo al que se desea llegar.... | stack_v2_sparse_classes_75kplus_train_004321 | 9,806 | no_license | [
{
"docstring": "@brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param target_pos Posicion del objetivo al que se desea llegar. @param father Nodo padre, None por defecto",
"name": "__init__",
"signature": "def __init__(self, row, column, target_pos, fath... | 2 | stack_v2_sparse_classes_30k_train_040280 | Implement the Python class `Nodo` described below.
Class description:
@brief Representa un nodo(posible estado) en el A*
Method signatures and docstrings:
- def __init__(self, row, column, target_pos, father=None): @brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param... | Implement the Python class `Nodo` described below.
Class description:
@brief Representa un nodo(posible estado) en el A*
Method signatures and docstrings:
- def __init__(self, row, column, target_pos, father=None): @brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param... | 994a5ca9b464c9e11de96d50079503743a0035fc | <|skeleton|>
class Nodo:
"""@brief Representa un nodo(posible estado) en el A*"""
def __init__(self, row, column, target_pos, father=None):
"""@brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param target_pos Posicion del objetivo al que se desea llegar.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Nodo:
"""@brief Representa un nodo(posible estado) en el A*"""
def __init__(self, row, column, target_pos, father=None):
"""@brief Constructor @param row Fila del nodo en el mapa @param column Columna del nodo en el mapa @param target_pos Posicion del objetivo al que se desea llegar. @param fathe... | the_stack_v2_python_sparse | engine/astar.py | jmarente/zycars | train | 0 |
8081d7904aa4a3593185da02031ba7f09c33d419 | [
"if number == 0:\n return 0\nif number == 1:\n return 1\nreturn 2 * self.jumpFloorII_1(number - 1)",
"if number == 0:\n return 0\nif number == 1:\n return 1\na = 1\nret = 0\nfor _ in range(2, number + 1):\n ret = 2 * a\n a = ret\nreturn ret",
"if number < 1:\n return 0\nreturn 2 ** (number ... | <|body_start_0|>
if number == 0:
return 0
if number == 1:
return 1
return 2 * self.jumpFloorII_1(number - 1)
<|end_body_0|>
<|body_start_1|>
if number == 0:
return 0
if number == 1:
return 1
a = 1
ret = 0
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jumpFloorII_1(self, number):
"""方法一:使用递归"""
<|body_0|>
def jumpFloorII_2(self, number):
"""方法二:使用for循环来代替递归"""
<|body_1|>
def jumpFloorII_3(self, number):
"""方法三:根据数学推导,直接返回结果。 f(n) = 2*f(n-1) = 2*(2*f(n-2)) = …… = 2^i * f(n-i) = 2^... | stack_v2_sparse_classes_75kplus_train_004322 | 1,733 | no_license | [
{
"docstring": "方法一:使用递归",
"name": "jumpFloorII_1",
"signature": "def jumpFloorII_1(self, number)"
},
{
"docstring": "方法二:使用for循环来代替递归",
"name": "jumpFloorII_2",
"signature": "def jumpFloorII_2(self, number)"
},
{
"docstring": "方法三:根据数学推导,直接返回结果。 f(n) = 2*f(n-1) = 2*(2*f(n-2)) = ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jumpFloorII_1(self, number): 方法一:使用递归
- def jumpFloorII_2(self, number): 方法二:使用for循环来代替递归
- def jumpFloorII_3(self, number): 方法三:根据数学推导,直接返回结果。 f(n) = 2*f(n-1) = 2*(2*f(n-2))... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jumpFloorII_1(self, number): 方法一:使用递归
- def jumpFloorII_2(self, number): 方法二:使用for循环来代替递归
- def jumpFloorII_3(self, number): 方法三:根据数学推导,直接返回结果。 f(n) = 2*f(n-1) = 2*(2*f(n-2))... | 6ee455019ae2d9adeea9fc3876f5da4297320715 | <|skeleton|>
class Solution:
def jumpFloorII_1(self, number):
"""方法一:使用递归"""
<|body_0|>
def jumpFloorII_2(self, number):
"""方法二:使用for循环来代替递归"""
<|body_1|>
def jumpFloorII_3(self, number):
"""方法三:根据数学推导,直接返回结果。 f(n) = 2*f(n-1) = 2*(2*f(n-2)) = …… = 2^i * f(n-i) = 2^... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def jumpFloorII_1(self, number):
"""方法一:使用递归"""
if number == 0:
return 0
if number == 1:
return 1
return 2 * self.jumpFloorII_1(number - 1)
def jumpFloorII_2(self, number):
"""方法二:使用for循环来代替递归"""
if number == 0:
... | the_stack_v2_python_sparse | p7_recursion_and_loop/a3_jumpFloorII.py | atm1992/nowcoder_offer_in_Python27 | train | 0 | |
483f730361df8edfdb655a421af5cf1d84ae1317 | [
"try:\n r = requests.get(url, params=params, headers=headers, files=files)\n log1.info('请求的内容:%s' % params)\n status_code = r.status_code\n log1.info('获取返回的状态码:%d' % status_code)\n response_json = r.json()\n log1.info('响应内容:%s' % response_json)\n reurl = r.url\n log1.info('url为:%s' % reurl)\... | <|body_start_0|>
try:
r = requests.get(url, params=params, headers=headers, files=files)
log1.info('请求的内容:%s' % params)
status_code = r.status_code
log1.info('获取返回的状态码:%d' % status_code)
response_json = r.json()
log1.info('响应内容:%s' % respon... | test_requests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_requests:
def get(self, url, params=None, headers=None, files=None):
"""封装get方法,return响应码和相应内容"""
<|body_0|>
def post(self, url, data=None, headers=None, files=None):
"""封装post请求,return响应码和响应内容"""
<|body_1|>
def post_json(self, url, data=None, heade... | stack_v2_sparse_classes_75kplus_train_004323 | 3,103 | no_license | [
{
"docstring": "封装get方法,return响应码和相应内容",
"name": "get",
"signature": "def get(self, url, params=None, headers=None, files=None)"
},
{
"docstring": "封装post请求,return响应码和响应内容",
"name": "post",
"signature": "def post(self, url, data=None, headers=None, files=None)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_053805 | Implement the Python class `test_requests` described below.
Class description:
Implement the test_requests class.
Method signatures and docstrings:
- def get(self, url, params=None, headers=None, files=None): 封装get方法,return响应码和相应内容
- def post(self, url, data=None, headers=None, files=None): 封装post请求,return响应码和响应内容
- ... | Implement the Python class `test_requests` described below.
Class description:
Implement the test_requests class.
Method signatures and docstrings:
- def get(self, url, params=None, headers=None, files=None): 封装get方法,return响应码和相应内容
- def post(self, url, data=None, headers=None, files=None): 封装post请求,return响应码和响应内容
- ... | 5afa8a2220165e0ef749b61e91b31b4b267ea635 | <|skeleton|>
class test_requests:
def get(self, url, params=None, headers=None, files=None):
"""封装get方法,return响应码和相应内容"""
<|body_0|>
def post(self, url, data=None, headers=None, files=None):
"""封装post请求,return响应码和响应内容"""
<|body_1|>
def post_json(self, url, data=None, heade... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_requests:
def get(self, url, params=None, headers=None, files=None):
"""封装get方法,return响应码和相应内容"""
try:
r = requests.get(url, params=params, headers=headers, files=files)
log1.info('请求的内容:%s' % params)
status_code = r.status_code
log1.info('获... | the_stack_v2_python_sparse | framework/Base_requests.py | maomaokeen/pyAutoTest | train | 1 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nstat = adm.get_state_by_id(state_id)\nreturn stat",
"adm = ProjectAdministration()\nstat = adm.get_state_by_id(state_id)\nif stat is not None:\n adm.delete_state(stat)\n return ('gelöscht', 200)\nelse:\n return ('There was some error', 500)"
] | <|body_start_0|>
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
return stat
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
if stat is not None:
adm.delete_state(stat)
return (... | StateOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, state_id):
"""Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI best... | stack_v2_sparse_classes_75kplus_train_004324 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, state_id)"
},
{
"docstring": "Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI bestimmt wird.",
"name": "de... | 2 | stack_v2_sparse_classes_30k_train_008081 | Implement the Python class `StateOperations` described below.
Class description:
Implement the StateOperations class.
Method signatures and docstrings:
- def get(self, state_id): Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.
- def delete(self, state_id): Löschen eines ... | Implement the Python class `StateOperations` described below.
Class description:
Implement the StateOperations class.
Method signatures and docstrings:
- def get(self, state_id): Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.
- def delete(self, state_id): Löschen eines ... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, state_id):
"""Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI best... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
return stat
def delete(self, state_id):
"""Löschen eine... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
f47a9060f8844cd2e36496bb6e0ad964fc1a06ad | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"if list_objs is None:\n list_objs = []\nl = []\nfor obj in list_objs:\n l.append(cls.to_dictionary... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None:
return '[]'
else:
return json.dumps(list_dictionaries)
<|en... | Manage id attribute in all future classes | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Manage id attribute in all future classes"""
def __init__(self, id=None):
"""the init method"""
<|body_0|>
def to_json_string(list_dictionaries):
"""convert to a json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save to ... | stack_v2_sparse_classes_75kplus_train_004325 | 1,506 | no_license | [
{
"docstring": "the init method",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "convert to a json string",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "save to json file",
"name": "save_t... | 5 | stack_v2_sparse_classes_30k_train_024616 | Implement the Python class `Base` described below.
Class description:
Manage id attribute in all future classes
Method signatures and docstrings:
- def __init__(self, id=None): the init method
- def to_json_string(list_dictionaries): convert to a json string
- def save_to_file(cls, list_objs): save to json file
- def... | Implement the Python class `Base` described below.
Class description:
Manage id attribute in all future classes
Method signatures and docstrings:
- def __init__(self, id=None): the init method
- def to_json_string(list_dictionaries): convert to a json string
- def save_to_file(cls, list_objs): save to json file
- def... | 04c2424c6e98680ead4efa974ec2d948d21024ad | <|skeleton|>
class Base:
"""Manage id attribute in all future classes"""
def __init__(self, id=None):
"""the init method"""
<|body_0|>
def to_json_string(list_dictionaries):
"""convert to a json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""save to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Manage id attribute in all future classes"""
def __init__(self, id=None):
"""the init method"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | AhlemKaabi/holbertonschool-higher_level_programming | train | 1 |
a57de99f40ac58259136f3d63db1aa7f0d3d1c2a | [
"result = []\nfor i in range(len(temperatures)):\n for j in range(i + 1, len(temperatures)):\n if temperatures[j] > temperatures[i]:\n result.append(j - i)\n break\n if j == len(temperatures) - 1 and temperatures[j] <= temperatures[i]:\n result.append(0)\nresult.app... | <|body_start_0|>
result = []
for i in range(len(temperatures)):
for j in range(i + 1, len(temperatures)):
if temperatures[j] > temperatures[i]:
result.append(j - i)
break
if j == len(temperatures) - 1 and temperatures[j]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_004326 | 1,544 | no_license | [
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures1",
"signature": "def dailyTemperatures1(self, temperatures)"
},
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(... | 2 | stack_v2_sparse_classes_30k_train_030550 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | 96e847591aa6ea7ea285dbcfc1c9bcfc32026de5 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
result = []
for i in range(len(temperatures)):
for j in range(i + 1, len(temperatures)):
if temperatures[j] > temperatures[i]:
res... | the_stack_v2_python_sparse | DueueStack/L739_daily-temperatures.py | lihujun101/LeetCode | train | 0 | |
4b31b06425da59b84b296bcbb3eb19d1405d5cf7 | [
"if coins:\n if isinstance(coins, dict):\n if all((isinstance(key, int) for key in coins)) and all((isinstance(value, int) for value in coins.values())):\n super().__init__(coins)\n else:\n raise ValueError('Coins works only with integers')\n elif isinstance(coins, list):\n... | <|body_start_0|>
if coins:
if isinstance(coins, dict):
if all((isinstance(key, int) for key in coins)) and all((isinstance(value, int) for value in coins.values())):
super().__init__(coins)
else:
raise ValueError('Coins works on... | Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 Coins({200:0, 100:2, 50:4, 20:1, 10:1}) ``` Warning: Negative coins amoun... | Coins | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coins:
"""Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 Coins({200:0, 100:2, 50:4, 20:1, 10:1}) ... | stack_v2_sparse_classes_75kplus_train_004327 | 4,080 | permissive | [
{
"docstring": "Create a Coin object, expect a dict of coins or a list of coins. If no argument is given, the coins object is empty Usage: ``` >>> Coins({200:2, 100:5}) Coins({200:2, 100:5}) >>> Coins([200, 200, 100, 100, 100, 100, 100]) Coins({200:2, 100:5}) >>> Coins() Coins() ```",
"name": "__init__",
... | 4 | stack_v2_sparse_classes_30k_train_029097 | Implement the Python class `Coins` described below.
Class description:
Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 C... | Implement the Python class `Coins` described below.
Class description:
Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 C... | c3bdfbb9e3b06caa6314c08ab6fb1251422518f8 | <|skeleton|>
class Coins:
"""Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 Coins({200:0, 100:2, 50:4, 20:1, 10:1}) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Coins:
"""Class that represents Coins Usage: ``` >>> coins = Coins({200: 0, 100: 2, 50: 4, 20: 3, 10: 1}) >>> coins.value 470 >>> coins2 = Coins({200:0, 100:0, 50:0, 20:2, 10:0}) >>> coins + coins2 Coins({200:0, 100:2, 50:4, 20:5, 10:1}) >>> coins - coins2 Coins({200:0, 100:2, 50:4, 20:1, 10:1}) ``` Warning: ... | the_stack_v2_python_sparse | coins.py | PaulEcoffet/megamachineacaoua | train | 0 |
8d09fbc245df9dce8d26e9bc10152d6647048e2e | [
"super(BatchSystemSupport, self).__init__()\nself.config = config\nself.maxCores = maxCores\nself.maxMemory = maxMemory\nself.maxDisk = maxDisk\nself.environment = {}\n'\\n :type: dict[str,str]\\n '\nself.workerCleanupInfo = WorkerCleanupInfo(workDir=self.config.workDir, workflowID=self.config.workflo... | <|body_start_0|>
super(BatchSystemSupport, self).__init__()
self.config = config
self.maxCores = maxCores
self.maxMemory = maxMemory
self.maxDisk = maxDisk
self.environment = {}
'\n :type: dict[str,str]\n '
self.workerCleanupInfo = WorkerClea... | Partial implementation of AbstractBatchSystem, support methods. | BatchSystemSupport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchSystemSupport:
"""Partial implementation of AbstractBatchSystem, support methods."""
def __init__(self, config, maxCores, maxMemory, maxDisk):
"""Initializes initial state of the object :param toil.common.Config config: object is setup by the toilSetup script and has configurati... | stack_v2_sparse_classes_75kplus_train_004328 | 20,544 | permissive | [
{
"docstring": "Initializes initial state of the object :param toil.common.Config config: object is setup by the toilSetup script and has configuration parameters for the jobtree. You can add code to that script to get parameters for your batch system. :param float maxCores: the maximum number of cores the batc... | 5 | stack_v2_sparse_classes_30k_train_039181 | Implement the Python class `BatchSystemSupport` described below.
Class description:
Partial implementation of AbstractBatchSystem, support methods.
Method signatures and docstrings:
- def __init__(self, config, maxCores, maxMemory, maxDisk): Initializes initial state of the object :param toil.common.Config config: ob... | Implement the Python class `BatchSystemSupport` described below.
Class description:
Partial implementation of AbstractBatchSystem, support methods.
Method signatures and docstrings:
- def __init__(self, config, maxCores, maxMemory, maxDisk): Initializes initial state of the object :param toil.common.Config config: ob... | 18fcc6f3406138cf993ffa9b0c2428ec556fd040 | <|skeleton|>
class BatchSystemSupport:
"""Partial implementation of AbstractBatchSystem, support methods."""
def __init__(self, config, maxCores, maxMemory, maxDisk):
"""Initializes initial state of the object :param toil.common.Config config: object is setup by the toilSetup script and has configurati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchSystemSupport:
"""Partial implementation of AbstractBatchSystem, support methods."""
def __init__(self, config, maxCores, maxMemory, maxDisk):
"""Initializes initial state of the object :param toil.common.Config config: object is setup by the toilSetup script and has configuration parameters... | the_stack_v2_python_sparse | src/toil/batchSystems/abstractBatchSystem.py | mskcc/toil | train | 7 |
0ba815d767b864b7c6d5f9fe0cf3f5672d1e677f | [
"super().__init__()\nself.deconv1 = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, output_padding=output_padding)\nself.deconv2 = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=st... | <|body_start_0|>
super().__init__()
self.deconv1 = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, output_padding=output_padding)
self.deconv2 = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, ... | GluConvTranspose2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GluConvTranspose2d:
def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, output_padding=(0, 0)):
"""ConvTranspose2d with Gated Linear Units (GLU). Input and output shapes are the same as regular ConvTranspose2d layers. Reference: Section III-B in [1] Args: in_cha... | stack_v2_sparse_classes_75kplus_train_004329 | 18,544 | permissive | [
{
"docstring": "ConvTranspose2d with Gated Linear Units (GLU). Input and output shapes are the same as regular ConvTranspose2d layers. Reference: Section III-B in [1] Args: in_channels (int): number of input channels out_channels (int): number of output channels kernel_size (int/tuple): kernel size in ConvTrans... | 2 | stack_v2_sparse_classes_30k_train_024614 | Implement the Python class `GluConvTranspose2d` described below.
Class description:
Implement the GluConvTranspose2d class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, output_padding=(0, 0)): ConvTranspose2d with Gated Linear Units (GLU). Input and... | Implement the Python class `GluConvTranspose2d` described below.
Class description:
Implement the GluConvTranspose2d class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, output_padding=(0, 0)): ConvTranspose2d with Gated Linear Units (GLU). Input and... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class GluConvTranspose2d:
def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, output_padding=(0, 0)):
"""ConvTranspose2d with Gated Linear Units (GLU). Input and output shapes are the same as regular ConvTranspose2d layers. Reference: Section III-B in [1] Args: in_cha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GluConvTranspose2d:
def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, output_padding=(0, 0)):
"""ConvTranspose2d with Gated Linear Units (GLU). Input and output shapes are the same as regular ConvTranspose2d layers. Reference: Section III-B in [1] Args: in_channels (int): n... | the_stack_v2_python_sparse | espnet2/enh/layers/dc_crn.py | espnet/espnet | train | 7,242 | |
e51ea1e9cd9459421b9e5b847dc1dee6ceae7584 | [
"count = [0] * 32\nfor num in nums:\n k = 0\n while k < 32:\n count[k] += num >> k & 1\n k += 1\nres = 0\nfor i in range(32):\n res += count[i] % 3 * 2 ** i\nreturn res",
"ones, twos = (0, 0)\nfor num in nums:\n ones = (ones ^ num) & ~twos\n twos = (twos ^ num) & ~ones\nreturn ones"
] | <|body_start_0|>
count = [0] * 32
for num in nums:
k = 0
while k < 32:
count[k] += num >> k & 1
k += 1
res = 0
for i in range(32):
res += count[i] % 3 * 2 ** i
return res
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNumberAppearingOnce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findNumberAppearingOnce_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = [0] * 32
... | stack_v2_sparse_classes_75kplus_train_004330 | 1,038 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findNumberAppearingOnce",
"signature": "def findNumberAppearingOnce(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findNumberAppearingOnce_2",
"signature": "def findNumberAppearingOnce_2(self, nums... | 2 | stack_v2_sparse_classes_30k_train_050800 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberAppearingOnce(self, nums): :type nums: List[int] :rtype: int
- def findNumberAppearingOnce_2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberAppearingOnce(self, nums): :type nums: List[int] :rtype: int
- def findNumberAppearingOnce_2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solu... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def findNumberAppearingOnce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findNumberAppearingOnce_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findNumberAppearingOnce(self, nums):
""":type nums: List[int] :rtype: int"""
count = [0] * 32
for num in nums:
k = 0
while k < 32:
count[k] += num >> k & 1
k += 1
res = 0
for i in range(32):
... | the_stack_v2_python_sparse | jianzhi_offer/52_数组中唯一只出现一次的数字.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
b435512200fc41b217e7b054e1cff06bf7f0eeed | [
"nums1[:m].extend(nums2[:n])\nnums1[:m] + nums2[:n]\nnums1.sort()",
"for i in range(n):\n nums1[m + i] = nums2[i]\nnums1.sort()"
] | <|body_start_0|>
nums1[:m].extend(nums2[:n])
nums1[:m] + nums2[:n]
nums1.sort()
<|end_body_0|>
<|body_start_1|>
for i in range(n):
nums1[m + i] = nums2[i]
nums1.sort()
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge1(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_004331 | 1,387 | no_license | [
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge1",
"signature": "def merge1(self, nums1, m, nums2, n)"
},
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge2",
"signature": "def merge2(self, nums1, m, nums2, n)"... | 2 | stack_v2_sparse_classes_30k_train_050379 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead.
- def merge2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place instead.
- def merge2(self, nums1, m, nums2, n): Do not return anything, modify nums1 in-place... | b8f705a77cfcdb7d498d3422f9c4ee88fd61a3b3 | <|skeleton|>
class Solution:
def merge1(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge1(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instead."""
nums1[:m].extend(nums2[:n])
nums1[:m] + nums2[:n]
nums1.sort()
def merge2(self, nums1, m, nums2, n):
"""Do not return anything, modify nums1 in-place instea... | the_stack_v2_python_sparse | LeetcodePython/Base/算法面试题2018/1-4-合并两个有序数组.py | selonsy/leetcode | train | 0 | |
d0b244f3103d95f468cb4d6bc99d960afc0aa2bb | [
"self.n_samples = n_samples\nself.upper_bound = boundaries[1]\nself.lower_bound = boundaries[0]\nself.dimensions = dimensions\nself.samples = np.random.uniform(boundaries[1], boundaries[0], size=(n_samples, dimensions))",
"domain = (self.upper_bound - self.lower_bound) ** self.dimensions\nintegration_output = np.... | <|body_start_0|>
self.n_samples = n_samples
self.upper_bound = boundaries[1]
self.lower_bound = boundaries[0]
self.dimensions = dimensions
self.samples = np.random.uniform(boundaries[1], boundaries[0], size=(n_samples, dimensions))
<|end_body_0|>
<|body_start_1|>
domain ... | Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration | MonteCarloIntegrator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonteCarloIntegrator:
"""Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration"""
def __init__(self, n_samples: int, boundaries: Lis... | stack_v2_sparse_classes_75kplus_train_004332 | 1,852 | no_license | [
{
"docstring": ":param n_samples: number of samples used for calculating average value :param boundaries: range of the integration in domain of multidimensional cube :param dimensions: dimension of the domain",
"name": "__init__",
"signature": "def __init__(self, n_samples: int, boundaries: List, dimens... | 2 | stack_v2_sparse_classes_30k_train_023080 | Implement the Python class `MonteCarloIntegrator` described below.
Class description:
Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration
Method signatures ... | Implement the Python class `MonteCarloIntegrator` described below.
Class description:
Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration
Method signatures ... | 04b34d97f72329a39d3974ec7011bc0266efface | <|skeleton|>
class MonteCarloIntegrator:
"""Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration"""
def __init__(self, n_samples: int, boundaries: Lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonteCarloIntegrator:
"""Monte Carlo methods are often used in calculation of multi dimensional integral This class enables vectorized calculation of multidimensional integrals, although we need to defined finite ranges of the integration"""
def __init__(self, n_samples: int, boundaries: List, dimensions... | the_stack_v2_python_sparse | SCF_method/calculation/integration/integrators.py | Semanames/quantum_chemistry | train | 0 |
96b316984e58f7aeac9c9ece573eb3387602c0c4 | [
"user = g.user\nproject = Project.find_by_id(project_id)\nproject_dump = ProjectSchema().dump(project)\nfor project_users in project.users:\n if project_users.user_id == user.id:\n project_dump['myRole'] = project_users.role\nreturn (project_dump, HTTPStatus.OK)",
"user = g.user\nproject = Project.find_... | <|body_start_0|>
user = g.user
project = Project.find_by_id(project_id)
project_dump = ProjectSchema().dump(project)
for project_users in project.users:
if project_users.user_id == user.id:
project_dump['myRole'] = project_users.role
return (project_du... | Resource for managing get project by id. | ProjectResourceById | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
<|body_0|>
def delete(project_id):
"""Delete project."""
<|body_1|>
def put(project_id):
"""Update project details."""
... | stack_v2_sparse_classes_75kplus_train_004333 | 6,357 | permissive | [
{
"docstring": "Get project details.",
"name": "get",
"signature": "def get(project_id)"
},
{
"docstring": "Delete project.",
"name": "delete",
"signature": "def delete(project_id)"
},
{
"docstring": "Update project details.",
"name": "put",
"signature": "def put(project_... | 4 | stack_v2_sparse_classes_30k_train_018503 | Implement the Python class `ProjectResourceById` described below.
Class description:
Resource for managing get project by id.
Method signatures and docstrings:
- def get(project_id): Get project details.
- def delete(project_id): Delete project.
- def put(project_id): Update project details.
- def patch(project_id): ... | Implement the Python class `ProjectResourceById` described below.
Class description:
Resource for managing get project by id.
Method signatures and docstrings:
- def get(project_id): Get project details.
- def delete(project_id): Delete project.
- def put(project_id): Update project details.
- def patch(project_id): ... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
<|body_0|>
def delete(project_id):
"""Delete project."""
<|body_1|>
def put(project_id):
"""Update project details."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
user = g.user
project = Project.find_by_id(project_id)
project_dump = ProjectSchema().dump(project)
for project_users in project.users:
i... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/resources/project.py | bcgov/BCSC-SS | train | 2 |
34111399be25279218275ead78c5ab8a74d7af9c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'appCrashCount': lambda n: setattr(self, 'app_crash_count', n.g... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Calla... | The user experience analytics application performance entity contains application performance by application version device id. | UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienc... | stack_v2_sparse_classes_75kplus_train_004334 | 4,506 | 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: UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId",
"name": "create_from_discriminator_value",
... | 3 | stack_v2_sparse_classes_30k_train_004587 | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version device id.
Method signatures and docstrings:
- def create_from_discri... | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version device id.
Method signatures and docstrings:
- def create_from_discri... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsApp... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_app_performance_by_app_version_device_id.py | microsoftgraph/msgraph-sdk-python | train | 135 |
272c1aedd7fc8afbd42c545aa3242bde67844852 | [
"Parametre.__init__(self, 'renommer', 'rename')\nself.schema = '<nombre> <message>'\nself.aide_courte = 'renomme un navire'\nself.aide_longue = \"Cette commande vous permet de changer le nom d'un navire. Celui-ci doit être dans le chantier naval où vous vous trouvez. Vous devez préciser en premier paramètre le numé... | <|body_start_0|>
Parametre.__init__(self, 'renommer', 'rename')
self.schema = '<nombre> <message>'
self.aide_courte = 'renomme un navire'
self.aide_longue = "Cette commande vous permet de changer le nom d'un navire. Celui-ci doit être dans le chantier naval où vous vous trouvez. Vous dev... | Commande 'chantier renommer'. | PrmRenommer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmRenommer:
"""Commande 'chantier renommer'."""
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|>
Parame... | stack_v2_sparse_classes_75kplus_train_004335 | 3,911 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033896 | Implement the Python class `PrmRenommer` described below.
Class description:
Commande 'chantier renommer'.
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 `PrmRenommer` described below.
Class description:
Commande 'chantier renommer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmRenommer:
"""Commande 'c... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmRenommer:
"""Commande 'chantier renommer'."""
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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmRenommer:
"""Commande 'chantier renommer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'renommer', 'rename')
self.schema = '<nombre> <message>'
self.aide_courte = 'renomme un navire'
self.aide_longue = "Cette commande vous per... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/chantier/renommer.py | vincent-lg/tsunami | train | 5 |
ccad470a9af344f8690dc219c252171a14076fda | [
"assert pool\nself.pool = pool\nself.iterpool = iterpool or pool\nself.fs = fs\nself._as_parameter_ = POINTER(svn_fs_root_t)()\nif txn and rev:\n raise Exception(\"You can't specify both a txn and a rev\")\nif txn:\n svn_fs_txn_root(byref(self._as_parameter_), txn, self.pool)\nelse:\n if not rev:\n ... | <|body_start_0|>
assert pool
self.pool = pool
self.iterpool = iterpool or pool
self.fs = fs
self._as_parameter_ = POINTER(svn_fs_root_t)()
if txn and rev:
raise Exception("You can't specify both a txn and a rev")
if txn:
svn_fs_txn_root(byr... | NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object | _fs_root | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _fs_root:
"""NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object"""
def __init__(self, fs, rev=None, txn=None, pool=None, iterpool=None):
"""See _fs.root()"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_004336 | 23,667 | permissive | [
{
"docstring": "See _fs.root()",
"name": "__init__",
"signature": "def __init__(self, fs, rev=None, txn=None, pool=None, iterpool=None)"
},
{
"docstring": "Check whether the specified path exists in this root. See Repos.check_path() for details.",
"name": "check_path",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_012607 | Implement the Python class `_fs_root` described below.
Class description:
NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object
Method signatures and docstrings:
- def __init__(self, fs, rev=None, txn=None, pool=None, iter... | Implement the Python class `_fs_root` described below.
Class description:
NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object
Method signatures and docstrings:
- def __init__(self, fs, rev=None, txn=None, pool=None, iter... | 8918d8ce8d15cc494f499859cfbfe8e66c574acc | <|skeleton|>
class _fs_root:
"""NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object"""
def __init__(self, fs, rev=None, txn=None, pool=None, iterpool=None):
"""See _fs.root()"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _fs_root:
"""NOTE: This is a private class. Don't use it outside of this module. Use the Repos.txn() method instead. This class represents an svn_fs_root_t object"""
def __init__(self, fs, rev=None, txn=None, pool=None, iterpool=None):
"""See _fs.root()"""
assert pool
self.pool = ... | the_stack_v2_python_sparse | subversion-1.6.13/subversion/bindings/ctypes-python/csvn/repos.py | RussellBauer/G5_Deps | train | 0 |
4cb1f4fc2217cad4fc531b53081abd7590cf9906 | [
"self.capacity = capacity\nself.c_size = 0\nself.history = []\nself._data = {}",
"if self._data.get(key, None) is None:\n return -1\nelse:\n self.history.remove(key)\n self.history.append(key)\nreturn self._data.get(key)",
"if self._data.get(key, -1) == -1:\n if self.c_size == self.capacity:\n ... | <|body_start_0|>
self.capacity = capacity
self.c_size = 0
self.history = []
self._data = {}
<|end_body_0|>
<|body_start_1|>
if self._data.get(key, None) is None:
return -1
else:
self.history.remove(key)
self.history.append(key)
... | LRUCache_On_List_sol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache_On_List_sol:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_004337 | 4,563 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_033460 | Implement the Python class `LRUCache_On_List_sol` described below.
Class description:
Implement the LRUCache_On_List_sol class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: n... | Implement the Python class `LRUCache_On_List_sol` described below.
Class description:
Implement the LRUCache_On_List_sol class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: n... | d308e0e41c288f23a846b8505e572943d30b1392 | <|skeleton|>
class LRUCache_On_List_sol:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache_On_List_sol:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.c_size = 0
self.history = []
self._data = {}
def get(self, key):
""":rtype: int"""
if self._data.get(key, None) is None:
return -... | the_stack_v2_python_sparse | python/146_LRU_Cache.py | HankerZheng/LeetCode-Problems | train | 2 | |
3ca3f9e17f1bdf084784758cfe8ddb41b7f0e7cd | [
"student.dob = str(student.dob)\nif 'str' not in str(type(student.dob)):\n dob_str = '-'.join([str(student.dob.year), str(student.dob.month), str(student.dob.day)])\nelse:\n dob_str = student.dob\nreturn [str(student.enrolmentNumber), student.firstName, student.lastName, dob_str, student.faculty, student.emai... | <|body_start_0|>
student.dob = str(student.dob)
if 'str' not in str(type(student.dob)):
dob_str = '-'.join([str(student.dob.year), str(student.dob.month), str(student.dob.day)])
else:
dob_str = student.dob
return [str(student.enrolmentNumber), student.firstName, s... | This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer . | StudentListMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentListMapper:
"""This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer ."""
def map_to_list(self, student):
"""creates list of from model.Student.Student :param student: model.Student.Student :retur... | stack_v2_sparse_classes_75kplus_train_004338 | 1,338 | no_license | [
{
"docstring": "creates list of from model.Student.Student :param student: model.Student.Student :return: list of strings",
"name": "map_to_list",
"signature": "def map_to_list(self, student)"
},
{
"docstring": "create model.Student.Student instance from list of strings - data :param data: list ... | 2 | stack_v2_sparse_classes_30k_train_014482 | Implement the Python class `StudentListMapper` described below.
Class description:
This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer .
Method signatures and docstrings:
- def map_to_list(self, student): creates list of from model.Stu... | Implement the Python class `StudentListMapper` described below.
Class description:
This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer .
Method signatures and docstrings:
- def map_to_list(self, student): creates list of from model.Stu... | a30389aa4542a23011a955ac61bf5b853c3e7854 | <|skeleton|>
class StudentListMapper:
"""This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer ."""
def map_to_list(self, student):
"""creates list of from model.Student.Student :param student: model.Student.Student :retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudentListMapper:
"""This class is used by serializer.StudentPDFSerializer.StudentPDFSerializer and by serializer.StudentCSVSerializer.StudentCSVSerializer ."""
def map_to_list(self, student):
"""creates list of from model.Student.Student :param student: model.Student.Student :return: list of st... | the_stack_v2_python_sparse | mapper/StudentListMapper.py | edutilos6666/PythonSciStudentProject | train | 0 |
a2cce17b5ca19917e29dd82497c944b6d8342003 | [
"qos = qos or self._qos\nif val is not None:\n val = self._values.get(bool(val)) or self._values.get(val) or self._values.get(str(val).lower()) or val\n val = 'ON' if val is True else val\n val = 'OFF' if val is False else val\n try:\n val = val.upper()\n except AttributeError:\n pass\n... | <|body_start_0|>
qos = qos or self._qos
if val is not None:
val = self._values.get(bool(val)) or self._values.get(val) or self._values.get(str(val).lower()) or val
val = 'ON' if val is True else val
val = 'OFF' if val is False else val
try:
... | Representation of a Denon telnet message command. | DenonTelnetCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenonTelnetCommand:
"""Representation of a Denon telnet message command."""
def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand:
"""Format the command with argument and return."""
<|body_0|>
def set_query(self, qos: int=N... | stack_v2_sparse_classes_75kplus_train_004339 | 7,223 | permissive | [
{
"docstring": "Format the command with argument and return.",
"name": "set_val",
"signature": "def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand"
},
{
"docstring": "Format the command with query and return.",
"name": "set_query",
"sign... | 2 | null | Implement the Python class `DenonTelnetCommand` described below.
Class description:
Representation of a Denon telnet message command.
Method signatures and docstrings:
- def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand: Format the command with argument and return.
... | Implement the Python class `DenonTelnetCommand` described below.
Class description:
Representation of a Denon telnet message command.
Method signatures and docstrings:
- def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand: Format the command with argument and return.
... | 2c86d0ab1f3bca886d2a876096ac760ffb1dcd5f | <|skeleton|>
class DenonTelnetCommand:
"""Representation of a Denon telnet message command."""
def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand:
"""Format the command with argument and return."""
<|body_0|>
def set_query(self, qos: int=N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DenonTelnetCommand:
"""Representation of a Denon telnet message command."""
def set_val(self, val: Union[int, float, str]=None, qos: int=None, sequence: int=-1) -> TelnetCommand:
"""Format the command with argument and return."""
qos = qos or self._qos
if val is not None:
... | the_stack_v2_python_sparse | pyavreceiver/denon/commands.py | JPHutchins/pyavreceiver | train | 4 |
ea1d26246f8b62aa32ba472c0cb190c7434f78c0 | [
"@lru_cache(None)\ndef dp(i, j):\n if i == len(nums1) or j == len(nums2):\n return 0\n if nums1[i] == nums2[j]:\n return 1 + dp(i + 1, j + 1)\n return 0\nreturn max((dp(i, j) for i in range(len(nums1)) for j in range(len(nums2))))",
"dp = [[0] * (len(nums2) + 1) for _ in range(len(nums1) + ... | <|body_start_0|>
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if nums1[i] == nums2[j]:
return 1 + dp(i + 1, j + 1)
return 0
return max((dp(i, j) for i in range(len(nums1)) for j in range(len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_75kplus_train_004340 | 7,237 | no_license | [
{
"docstring": "09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)",
"name": "findLength",
"signature": "def findLength(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "08/12/2021 01:32 DP bottom up",
"name": "findLength",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_043819 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if... | the_stack_v2_python_sparse | leetcode/solved/718_Maximum_Length_of_Repeated_Subarray/solution.py | sungminoh/algorithms | train | 0 | |
b36fcfe7d6d5350afb995f1862d974729d01e333 | [
"parser.add_argument('appname', help='The sample app name, e.g. \"finance\".')\nparser.add_argument('--instance-id', required=True, type=str, help='The Cloud Spanner instance ID for the sample app.')\nparser.add_argument('--database-id', type=str, help='ID of the new Cloud Spanner database to create for the sample ... | <|body_start_0|>
parser.add_argument('appname', help='The sample app name, e.g. "finance".')
parser.add_argument('--instance-id', required=True, type=str, help='The Cloud Spanner instance ID for the sample app.')
parser.add_argument('--database-id', type=str, help='ID of the new Cloud Spanner da... | Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application. | Init | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Init:
"""Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args... | stack_v2_sparse_classes_75kplus_train_004341 | 9,146 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_019166 | Implement the Python class `Init` described below.
Class description:
Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application.
Method signatures and docstrings:
- def Args(parser): Args is call... | Implement the Python class `Init` described below.
Class description:
Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application.
Method signatures and docstrings:
- def Args(parser): Args is call... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Init:
"""Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Init:
"""Initialize a Cloud Spanner sample app. This command creates a Cloud Spanner database in the given instance for the sample app and loads any initial data required by the application."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An ... | the_stack_v2_python_sparse | lib/surface/spanner/samples/init.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
a68bf9935bee67f782a635278599b7d0facdd6f6 | [
"self.__qf = qf\nif edismax:\n self.__deftype = 'edismax'\nelse:\n self.__deftype = 'dismax'\nself.__optional_params = {'q.alt': alt, 'mm': mm, 'pf': pf, 'ps': ps, 'qs': qs, 'tie': tie, 'bq': bq, 'bf': bf}",
"params = []\nparams.append(('defType', self.__deftype))\nparams.append(('qf', self.__qf))\nfor p in... | <|body_start_0|>
self.__qf = qf
if edismax:
self.__deftype = 'edismax'
else:
self.__deftype = 'dismax'
self.__optional_params = {'q.alt': alt, 'mm': mm, 'pf': pf, 'ps': ps, 'qs': qs, 'tie': tie, 'bq': bq, 'bf': bf}
<|end_body_0|>
<|body_start_1|>
params =... | The dismax query. | DisMax | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisMax:
"""The dismax query."""
def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True):
"""Initialize the query values."""
<|body_0|>
def get_params(self):
"""Return the list of query params."""
<|bo... | stack_v2_sparse_classes_75kplus_train_004342 | 1,819 | permissive | [
{
"docstring": "Initialize the query values.",
"name": "__init__",
"signature": "def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True)"
},
{
"docstring": "Return the list of query params.",
"name": "get_params",
"signature": "def g... | 2 | null | Implement the Python class `DisMax` described below.
Class description:
The dismax query.
Method signatures and docstrings:
- def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True): Initialize the query values.
- def get_params(self): Return the list of query pa... | Implement the Python class `DisMax` described below.
Class description:
The dismax query.
Method signatures and docstrings:
- def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True): Initialize the query values.
- def get_params(self): Return the list of query pa... | 2810f3202166b045a7f5f9a21b964c681bfd8136 | <|skeleton|>
class DisMax:
"""The dismax query."""
def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True):
"""Initialize the query values."""
<|body_0|>
def get_params(self):
"""Return the list of query params."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisMax:
"""The dismax query."""
def __init__(self, qf, alt=None, mm=None, pf=None, ps=None, qs=None, tie=None, bq=None, bf=None, edismax=True):
"""Initialize the query values."""
self.__qf = qf
if edismax:
self.__deftype = 'edismax'
else:
self.__def... | the_stack_v2_python_sparse | dopplr/solr/query/dismax.py | renatoaquino/dopplr | train | 1 |
f3cbc5f066ef73ab052df54cc39c16cdaceab545 | [
"nums.sort()\nmemo = {0: 1}\n\ndef dfs(target):\n if target in memo:\n return memo[target]\n res = 0\n for i in range(len(nums)):\n if target - nums[i] >= 0:\n res += dfs(target - nums[i])\n memo[target] = res\n return res\nreturn dfs(target)",
"nums.sort()\ndp = [0] * (tar... | <|body_start_0|>
nums.sort()
memo = {0: 1}
def dfs(target):
if target in memo:
return memo[target]
res = 0
for i in range(len(nums)):
if target - nums[i] >= 0:
res += dfs(target - nums[i])
memo[t... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum1(self, nums: List[int], target: int) -> int:
"""思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:"""
<|body_0|>
def combinationSum2(self, nums: List[int], target: int) -> int:
"""思路... | stack_v2_sparse_classes_75kplus_train_004343 | 2,145 | no_license | [
{
"docstring": "思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:",
"name": "combinationSum1",
"signature": "def combinationSum1(self, nums: List[int], target: int) -> int"
},
{
"docstring": "思路:动态规划法 1. 一般来说,记忆化递归和动态规划法都可以相互转换 @param nums... | 2 | stack_v2_sparse_classes_30k_train_053821 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum1(self, nums: List[int], target: int) -> int: 思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:
- def c... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum1(self, nums: List[int], target: int) -> int: 思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:
- def c... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def combinationSum1(self, nums: List[int], target: int) -> int:
"""思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:"""
<|body_0|>
def combinationSum2(self, nums: List[int], target: int) -> int:
"""思路... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combinationSum1(self, nums: List[int], target: int) -> int:
"""思路:记忆化递归 1. 普通递归超时,采用记忆化递归 2. memo[target]=res,表示组合数的和为target时情况有res种 @param nums: @param target: @return:"""
nums.sort()
memo = {0: 1}
def dfs(target):
if target in memo:
... | the_stack_v2_python_sparse | LeetCode/回溯法/377. 组合总和 Ⅳ.py | yiming1012/MyLeetCode | train | 2 | |
7e8fc52006e8f8350fe25bc83f5bc215df33f6b6 | [
"if not root:\n return 0\nself.res = 0\nself.__helper(root)\nreturn self.res",
"left = self.__helper(root.left) if root.left else -1\nright = self.__helper(root.right) if root.right else -1\npathLeft = left + 1 if left >= 0 and root.val == root.left.val else 0\npathRight = right + 1 if right >= 0 and root.val ... | <|body_start_0|>
if not root:
return 0
self.res = 0
self.__helper(root)
return self.res
<|end_body_0|>
<|body_start_1|>
left = self.__helper(root.left) if root.left else -1
right = self.__helper(root.right) if root.right else -1
pathLeft = left + 1 if... | SolutionT687 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionT687:
def longestUnivaluePath(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __helper(self, root):
"""先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都应该为0 由于地基条件中root.val == root.child.val已经先行过滤(同则增大, 异则置0), self.res 仍可以取单边路径较大者"""
... | stack_v2_sparse_classes_75kplus_train_004344 | 1,640 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "longestUnivaluePath",
"signature": "def longestUnivaluePath(self, root)"
},
{
"docstring": "先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都应该为0 由于地基条件中root.val == root.child.val已经先行过滤(同则增大, 异则置0), self.res 仍可以取单边路径较大者",
"nam... | 2 | null | Implement the Python class `SolutionT687` described below.
Class description:
Implement the SolutionT687 class.
Method signatures and docstrings:
- def longestUnivaluePath(self, root): :type root: TreeNode :rtype: int
- def __helper(self, root): 先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都应该为0 由于地基条件中root.... | Implement the Python class `SolutionT687` described below.
Class description:
Implement the SolutionT687 class.
Method signatures and docstrings:
- def longestUnivaluePath(self, root): :type root: TreeNode :rtype: int
- def __helper(self, root): 先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都应该为0 由于地基条件中root.... | eca21324d5d2db0addfa0efdf09fc0ffbd9a09e6 | <|skeleton|>
class SolutionT687:
def longestUnivaluePath(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __helper(self, root):
"""先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都应该为0 由于地基条件中root.val == root.child.val已经先行过滤(同则增大, 异则置0), self.res 仍可以取单边路径较大者"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionT687:
def longestUnivaluePath(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
self.res = 0
self.__helper(root)
return self.res
def __helper(self, root):
"""先将dfs的地基条件考虑清楚: 叶子结点 or 单边且值不同的结点 or 双边且值不同的结点, 此时路径长度都... | the_stack_v2_python_sparse | trees/LC687.py | zangkhun/leepy | train | 0 | |
d93f0cf5e6b7bdfbe18bcde7e9303801370bf350 | [
"to_visit = []\ncur = root\nlast_node = None\nres, path = ([], [])\nwhile cur or len(to_visit) != 0:\n if cur:\n to_visit.append(cur)\n path.append(cur.val)\n cur = cur.left\n else:\n top_node = to_visit[-1]\n if top_node.right and last_node != top_node.right:\n c... | <|body_start_0|>
to_visit = []
cur = root
last_node = None
res, path = ([], [])
while cur or len(to_visit) != 0:
if cur:
to_visit.append(cur)
path.append(cur.val)
cur = cur.left
else:
top_node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def FindPath(self, root, expectNumber):
"""非递归做法 :param root: :param expectNumber: :return:"""
<|body_0|>
def FindPath1(self, root, expectNumber):
"""递归做法 :param root: :param expectNumber: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004345 | 2,823 | no_license | [
{
"docstring": "非递归做法 :param root: :param expectNumber: :return:",
"name": "FindPath",
"signature": "def FindPath(self, root, expectNumber)"
},
{
"docstring": "递归做法 :param root: :param expectNumber: :return:",
"name": "FindPath1",
"signature": "def FindPath1(self, root, expectNumber)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def FindPath(self, root, expectNumber): 非递归做法 :param root: :param expectNumber: :return:
- def FindPath1(self, root, expectNumber): 递归做法 :param root: :param expectNumber: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def FindPath(self, root, expectNumber): 非递归做法 :param root: :param expectNumber: :return:
- def FindPath1(self, root, expectNumber): 递归做法 :param root: :param expectNumber: :return... | 17a9447343b6e8190fee6ea3520e76191e9017fa | <|skeleton|>
class Solution:
def FindPath(self, root, expectNumber):
"""非递归做法 :param root: :param expectNumber: :return:"""
<|body_0|>
def FindPath1(self, root, expectNumber):
"""递归做法 :param root: :param expectNumber: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def FindPath(self, root, expectNumber):
"""非递归做法 :param root: :param expectNumber: :return:"""
to_visit = []
cur = root
last_node = None
res, path = ([], [])
while cur or len(to_visit) != 0:
if cur:
to_visit.append(cur)
... | the_stack_v2_python_sparse | Get_Offer/25 FindPath.py | zhangjiahuan17/leetcodePython | train | 0 | |
8107ebc5309995400022752d5a651fd15a2e17c6 | [
"self.ai_setting = ai_setting\nself.reset_stats()\nself.game_active = False\nself.high_score = 0",
"self.ship_left = self.ai_setting.ship_limit\nself.score = 0\nself.level = 1"
] | <|body_start_0|>
self.ai_setting = ai_setting
self.reset_stats()
self.game_active = False
self.high_score = 0
<|end_body_0|>
<|body_start_1|>
self.ship_left = self.ai_setting.ship_limit
self.score = 0
self.level = 1
<|end_body_1|>
| Track statistics for Alien Invasion | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_setting):
"""Initialize statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004346 | 550 | no_license | [
{
"docstring": "Initialize statistics",
"name": "__init__",
"signature": "def __init__(self, ai_setting)"
},
{
"docstring": "Initialize statistics that can change during the game",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015090 | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion
Method signatures and docstrings:
- def __init__(self, ai_setting): Initialize statistics
- def reset_stats(self): Initialize statistics that can change during the game | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion
Method signatures and docstrings:
- def __init__(self, ai_setting): Initialize statistics
- def reset_stats(self): Initialize statistics that can change during the game
<|skeleton|>
class GameStats:
"""... | e85198ab8b95abbe43e9c9bde44661525bca8977 | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_setting):
"""Initialize statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_setting):
"""Initialize statistics"""
self.ai_setting = ai_setting
self.reset_stats()
self.game_active = False
self.high_score = 0
def reset_stats(self):
"""Initialize statistic... | the_stack_v2_python_sparse | pygame/game_stats.py | pratikv06/Python-Crash-Course | train | 2 |
25e009475d7ba1a7967f88e1c95959f141b40bcd | [
"Process.__init__(self)\nself.engine = engine\nself.updaters = {}",
"logging.info(u'Starting observer')\ntry:\n self.engine.set('observer.counter', 0)\n while self.engine.get('general.switch', 'on') == 'on':\n if not self.engine.fan:\n break\n if self.engine.fan.empty():\n ... | <|body_start_0|>
Process.__init__(self)
self.engine = engine
self.updaters = {}
<|end_body_0|>
<|body_start_1|>
logging.info(u'Starting observer')
try:
self.engine.set('observer.counter', 0)
while self.engine.get('general.switch', 'on') == 'on':
... | Dispatches inbound records to downwards updaters | Observer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Observer:
"""Dispatches inbound records to downwards updaters"""
def __init__(self, engine=None):
"""Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine"""
<|body_0|>
def run(self):
"""Continuously handle in... | stack_v2_sparse_classes_75kplus_train_004347 | 4,987 | permissive | [
{
"docstring": "Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine",
"name": "__init__",
"signature": "def __init__(self, engine=None)"
},
{
"docstring": "Continuously handle inbound records and commands This function is looping on items r... | 3 | stack_v2_sparse_classes_30k_train_022178 | Implement the Python class `Observer` described below.
Class description:
Dispatches inbound records to downwards updaters
Method signatures and docstrings:
- def __init__(self, engine=None): Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine
- def run(self): C... | Implement the Python class `Observer` described below.
Class description:
Dispatches inbound records to downwards updaters
Method signatures and docstrings:
- def __init__(self, engine=None): Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine
- def run(self): C... | daf64fbab4085d1591bf9a1aecd06b4fc615d132 | <|skeleton|>
class Observer:
"""Dispatches inbound records to downwards updaters"""
def __init__(self, engine=None):
"""Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine"""
<|body_0|>
def run(self):
"""Continuously handle in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Observer:
"""Dispatches inbound records to downwards updaters"""
def __init__(self, engine=None):
"""Dispatches inbound records to downwards updaters :param engine: the overarching engine :type engine: Engine"""
Process.__init__(self)
self.engine = engine
self.updaters = {... | the_stack_v2_python_sparse | shellbot/observer.py | romainkotarba/shellbot | train | 0 |
6387c095a5ec6b367f22e096f4b47a3f26ff66e7 | [
"self.nodes = []\nhead = point = ListNode(0)\nfor l in lists:\n while l:\n self.nodes.append(l.val)\n l = l.next\nfor x in sorted(self.nodes):\n point.next = ListNode(x)\n point = point.next\nreturn head.next",
"def merge(lis1, lis2):\n result = pt = ListNode(0)\n while lis1 and lis2:... | <|body_start_0|>
self.nodes = []
head = point = ListNode(0)
for l in lists:
while l:
self.nodes.append(l.val)
l = l.next
for x in sorted(self.nodes):
point.next = ListNode(x)
point = point.next
return head.next
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
def mergeKLists(self, lists):
""":type lists: List[L... | stack_v2_sparse_classes_75kplus_train_004348 | 2,864 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_049261 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeKLists(self, li... | 62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
def mergeKLists(self, lists):
""":type lists: List[L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
self.nodes = []
head = point = ListNode(0)
for l in lists:
while l:
self.nodes.append(l.val)
l = l.next
for x in sorted(self.nodes):
... | the_stack_v2_python_sparse | leetcode/solved/023_.py | usnnu/python_foundation | train | 0 | |
5a45485aa3bdd9ac2d7c3037e90a113e1c8da03a | [
"re = Trader(userLogin).addTrader(send_data['name'], send_data['parkName'], send_data['account'], send_data['couponName'], send_data['pwd'])\nresult = re\nself.save_data('account', send_data['account'])\nself.save_data('pwd', send_data['pwd'])\nAssertions().assert_in_text(result, expect['addTraderMessage'])",
"re... | <|body_start_0|>
re = Trader(userLogin).addTrader(send_data['name'], send_data['parkName'], send_data['account'], send_data['couponName'], send_data['pwd'])
result = re
self.save_data('account', send_data['account'])
self.save_data('pwd', send_data['pwd'])
Assertions().assert_in_... | 新增商户流程 | TestEditTraderPassword | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEditTraderPassword:
"""新增商户流程"""
def test_addTrader(self, userLogin, send_data, expect):
"""商户新增"""
<|body_0|>
def test_editTraderPwd(self, userLogin, send_data, expect):
"""修改密码"""
<|body_1|>
def test_disAbleLoginWeiXin(self, weiXinLogin, send_d... | stack_v2_sparse_classes_75kplus_train_004349 | 3,025 | no_license | [
{
"docstring": "商户新增",
"name": "test_addTrader",
"signature": "def test_addTrader(self, userLogin, send_data, expect)"
},
{
"docstring": "修改密码",
"name": "test_editTraderPwd",
"signature": "def test_editTraderPwd(self, userLogin, send_data, expect)"
},
{
"docstring": "旧密码商户不能操作微信客... | 6 | stack_v2_sparse_classes_30k_train_051165 | Implement the Python class `TestEditTraderPassword` described below.
Class description:
新增商户流程
Method signatures and docstrings:
- def test_addTrader(self, userLogin, send_data, expect): 商户新增
- def test_editTraderPwd(self, userLogin, send_data, expect): 修改密码
- def test_disAbleLoginWeiXin(self, weiXinLogin, send_data,... | Implement the Python class `TestEditTraderPassword` described below.
Class description:
新增商户流程
Method signatures and docstrings:
- def test_addTrader(self, userLogin, send_data, expect): 商户新增
- def test_editTraderPwd(self, userLogin, send_data, expect): 修改密码
- def test_disAbleLoginWeiXin(self, weiXinLogin, send_data,... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestEditTraderPassword:
"""新增商户流程"""
def test_addTrader(self, userLogin, send_data, expect):
"""商户新增"""
<|body_0|>
def test_editTraderPwd(self, userLogin, send_data, expect):
"""修改密码"""
<|body_1|>
def test_disAbleLoginWeiXin(self, weiXinLogin, send_d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestEditTraderPassword:
"""新增商户流程"""
def test_addTrader(self, userLogin, send_data, expect):
"""商户新增"""
re = Trader(userLogin).addTrader(send_data['name'], send_data['parkName'], send_data['account'], send_data['couponName'], send_data['pwd'])
result = re
self.save_data('a... | the_stack_v2_python_sparse | test_suite/parkingManage/businessCoupon/test_editTraderPassword.py | oyebino/pomp_api | train | 1 |
a08c3a72efe65833d82f927c705c7737c8349713 | [
"left = array[start:middle]\nright = array[middle:end]\nleft.append(sys.maxsize)\nright.append(sys.maxsize)\nleft_inx = 0\nright_inx = 0\nfor inx in range(start, end):\n if left[left_inx] <= right[right_inx]:\n array[inx] = left[left_inx]\n left_inx += 1\n else:\n array[inx] = right[right... | <|body_start_0|>
left = array[start:middle]
right = array[middle:end]
left.append(sys.maxsize)
right.append(sys.maxsize)
left_inx = 0
right_inx = 0
for inx in range(start, end):
if left[left_inx] <= right[right_inx]:
array[inx] = left[l... | Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54 | MergeSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeSort:
"""Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54"""
def merge(array, start, middle, end):
"""Merge of two pre sorted arrays left and right both arrays should be have common border :Parameters: array: *list* - array of elements to sort sta... | stack_v2_sparse_classes_75kplus_train_004350 | 2,707 | no_license | [
{
"docstring": "Merge of two pre sorted arrays left and right both arrays should be have common border :Parameters: array: *list* - array of elements to sort start: *number* - start index of left array middle: *number* - end of left array end; end: *number* - end right array",
"name": "merge",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_041250 | Implement the Python class `MergeSort` described below.
Class description:
Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54
Method signatures and docstrings:
- def merge(array, start, middle, end): Merge of two pre sorted arrays left and right both arrays should be have common border :... | Implement the Python class `MergeSort` described below.
Class description:
Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54
Method signatures and docstrings:
- def merge(array, start, middle, end): Merge of two pre sorted arrays left and right both arrays should be have common border :... | 8b3b1f146b7eac5dc15b16aaf837441069cf5989 | <|skeleton|>
class MergeSort:
"""Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54"""
def merge(array, start, middle, end):
"""Merge of two pre sorted arrays left and right both arrays should be have common border :Parameters: array: *list* - array of elements to sort sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeSort:
"""Implementation of merge sort Thomas H. Cormen Algorithms Unlocked (2013) page 54"""
def merge(array, start, middle, end):
"""Merge of two pre sorted arrays left and right both arrays should be have common border :Parameters: array: *list* - array of elements to sort start: *number* ... | the_stack_v2_python_sparse | sort/merge.py | shuvava/python_algorithms | train | 2 |
1d4f4e6f207fad81c4bca588960f3a2c7664535d | [
"if self.request.method in permissions.SAFE_METHODS:\n return (permissions.IsAuthenticated(),)\nif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nreturn (permissions.IsAuthenticated(), IsAdminOfTeam())",
"serializer = self.serializer_class(data=request.data)\nif serializer.is_vali... | <|body_start_0|>
if self.request.method in permissions.SAFE_METHODS:
return (permissions.IsAuthenticated(),)
if self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
return (permissions.IsAuthenticated(), IsAdminOfTeam())
<|end_body_0|>
<|body_start_1|>
... | TeamViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfT... | stack_v2_sparse_classes_75kplus_train_004351 | 14,739 | no_license | [
{
"docstring": "Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfTeam :return: :rtype:",
"name": "get_permissions... | 5 | stack_v2_sparse_classes_30k_train_049287 | Implement the Python class `TeamViewSet` described below.
Class description:
Implement the TeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The cre... | Implement the Python class `TeamViewSet` described below.
Class description:
Implement the TeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The cre... | 8f296850eeab1df4c52bb7b9df0681884449e761 | <|skeleton|>
class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfT... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfTeam :return: :... | the_stack_v2_python_sparse | src/web/teams/views.py | CiberRato/pei2015-ciberrato | train | 0 | |
a2bc12321e5148fbc36ff0b5038bf657180e1f50 | [
"super(AggregateCell, self).__init__()\nself.pre_transform = pre_transform\nself.concat = concat\nif self.pre_transform:\n self.branch_1 = conv_bn_relu(size_1, agg_size, 1, 1, 0)\n self.branch_2 = conv_bn_relu(size_2, agg_size, 1, 1, 0)\nif self.concat:\n self.conv1x1 = conv_bn_relu(agg_size * 2, agg_size,... | <|body_start_0|>
super(AggregateCell, self).__init__()
self.pre_transform = pre_transform
self.concat = concat
if self.pre_transform:
self.branch_1 = conv_bn_relu(size_1, agg_size, 1, 1, 0)
self.branch_2 = conv_bn_relu(size_2, agg_size, 1, 1, 0)
if self.co... | Aggregate two cells and sum or concat them up. | AggregateCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of agg... | stack_v2_sparse_classes_75kplus_train_004352 | 10,880 | permissive | [
{
"docstring": "Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of aggregated tensor :param pre_transform: whether to do a transform on two inputs :param concat: concat the result if set to True, otherwise add the result",
"name"... | 2 | null | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False): Construct AggregateCell. :param size_1: channel of first input :param size_2... | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False): Construct AggregateCell. :param size_1: channel of first input :param size_2... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of agg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of aggregated tenso... | the_stack_v2_python_sparse | zeus/modules/operators/cell.py | huawei-noah/xingtian | train | 308 |
464c654a0ae18ee66d9e782d1f3e129a672f0b97 | [
"self.Whf = np.random.normal(size=(i + h, h))\nself.Whb = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(2 * h, o))\nself.bhf = np.zeros((1, h))\nself.bhb = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"h_x = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.matmul(h_x, self.Whf) +... | <|body_start_0|>
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(2 * h, o))
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
... | Class that represent a bidirectional cell of an RNN | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
"""Class that represent a bidirectional cell of an RNN"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the outputs Creates the public instance attributes Whf, Whb, Wy, bh... | stack_v2_sparse_classes_75kplus_train_004353 | 2,203 | no_license | [
{
"docstring": "i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the outputs Creates the public instance attributes Whf, Whb, Wy, bhf, bhb, by that represent the weights and biases of the cell Whf and bhfare for the hidden states in the forward directio... | 3 | stack_v2_sparse_classes_30k_train_053586 | Implement the Python class `BidirectionalCell` described below.
Class description:
Class that represent a bidirectional cell of an RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the output... | Implement the Python class `BidirectionalCell` described below.
Class description:
Class that represent a bidirectional cell of an RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the output... | e8a98d85b3bfd5665cb04bec9ee8c3eb23d6bd58 | <|skeleton|>
class BidirectionalCell:
"""Class that represent a bidirectional cell of an RNN"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the outputs Creates the public instance attributes Whf, Whb, Wy, bh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BidirectionalCell:
"""Class that represent a bidirectional cell of an RNN"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden states o is the dimensionality of the outputs Creates the public instance attributes Whf, Whb, Wy, bhf, bhb, by th... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/6-bi_backward.py | AndrewMiranda/holbertonschool-machine_learning-1 | train | 0 |
b6ca720e8de5230623ed66b784ad30985bf34dcf | [
"Nature.__init__(self, x, y, window)\nself.image = pygame.image.load('Images/arcticdune.png')\nself.rect = self.image.get_rect()\nself.rect.x = x\nself.rect.y = y",
"if window.model.heat > 0:\n window.model.heat -= 0.01\nif window.model.wet > 0:\n window.model.wet -= 0.01"
] | <|body_start_0|>
Nature.__init__(self, x, y, window)
self.image = pygame.image.load('Images/arcticdune.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
<|end_body_0|>
<|body_start_1|>
if window.model.heat > 0:
window.model.heat -= 0.01
... | Arctic Desert dune object | ArcticDesertDune | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArcticDesertDune:
"""Arctic Desert dune object"""
def __init__(self, x, y, window):
"""replaces the default image with the arctic desert dune image"""
<|body_0|>
def effect(self, window):
"""makes the environment colder and drier"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_004354 | 4,149 | no_license | [
{
"docstring": "replaces the default image with the arctic desert dune image",
"name": "__init__",
"signature": "def __init__(self, x, y, window)"
},
{
"docstring": "makes the environment colder and drier",
"name": "effect",
"signature": "def effect(self, window)"
}
] | 2 | null | Implement the Python class `ArcticDesertDune` described below.
Class description:
Arctic Desert dune object
Method signatures and docstrings:
- def __init__(self, x, y, window): replaces the default image with the arctic desert dune image
- def effect(self, window): makes the environment colder and drier | Implement the Python class `ArcticDesertDune` described below.
Class description:
Arctic Desert dune object
Method signatures and docstrings:
- def __init__(self, x, y, window): replaces the default image with the arctic desert dune image
- def effect(self, window): makes the environment colder and drier
<|skeleton|... | dbe8fbd8825b47290d11d6e3d4a7199f668e7527 | <|skeleton|>
class ArcticDesertDune:
"""Arctic Desert dune object"""
def __init__(self, x, y, window):
"""replaces the default image with the arctic desert dune image"""
<|body_0|>
def effect(self, window):
"""makes the environment colder and drier"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArcticDesertDune:
"""Arctic Desert dune object"""
def __init__(self, x, y, window):
"""replaces the default image with the arctic desert dune image"""
Nature.__init__(self, x, y, window)
self.image = pygame.image.load('Images/arcticdune.png')
self.rect = self.image.get_rec... | the_stack_v2_python_sparse | environment.py | Greenlightrj/playgod | train | 0 |
dc920dbfe1692fcf35ebb8e811cf63c29296e6a0 | [
"if s_length < 2:\n return 0\nif s_length == 2:\n return 1\nif s_length == 3:\n return 2\nli = [0, 1, 2, 3]\nfor i in range(4, s_length + 1):\n max_num = 0\n for j in range(1, i):\n temp = li[j] * li[i - j]\n if temp > max_num:\n max_num = temp\n li.append(max_num)\nprint(... | <|body_start_0|>
if s_length < 2:
return 0
if s_length == 2:
return 1
if s_length == 3:
return 2
li = [0, 1, 2, 3]
for i in range(4, s_length + 1):
max_num = 0
for j in range(1, i):
temp = li[j] * li[i - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_cut_1(self, s_length):
"""动态规划"""
<|body_0|>
def max_cut_2(self, s_length):
"""贪婪算法,当n>=5时候尽可能的切成长度为3的绳子,n=4的时候尽可能切成2*2的绳子"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s_length < 2:
return 0
if s_length ==... | stack_v2_sparse_classes_75kplus_train_004355 | 1,978 | no_license | [
{
"docstring": "动态规划",
"name": "max_cut_1",
"signature": "def max_cut_1(self, s_length)"
},
{
"docstring": "贪婪算法,当n>=5时候尽可能的切成长度为3的绳子,n=4的时候尽可能切成2*2的绳子",
"name": "max_cut_2",
"signature": "def max_cut_2(self, s_length)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019371 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_cut_1(self, s_length): 动态规划
- def max_cut_2(self, s_length): 贪婪算法,当n>=5时候尽可能的切成长度为3的绳子,n=4的时候尽可能切成2*2的绳子 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_cut_1(self, s_length): 动态规划
- def max_cut_2(self, s_length): 贪婪算法,当n>=5时候尽可能的切成长度为3的绳子,n=4的时候尽可能切成2*2的绳子
<|skeleton|>
class Solution:
def max_cut_1(self, s_length):... | 3b8b36bcf8a983de4d8ce29734a85b6bfbe59fbc | <|skeleton|>
class Solution:
def max_cut_1(self, s_length):
"""动态规划"""
<|body_0|>
def max_cut_2(self, s_length):
"""贪婪算法,当n>=5时候尽可能的切成长度为3的绳子,n=4的时候尽可能切成2*2的绳子"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def max_cut_1(self, s_length):
"""动态规划"""
if s_length < 2:
return 0
if s_length == 2:
return 1
if s_length == 3:
return 2
li = [0, 1, 2, 3]
for i in range(4, s_length + 1):
max_num = 0
for j i... | the_stack_v2_python_sparse | TargetOffer/14、剪绳子.py | a625687551/Leetcode | train | 0 | |
050a876c19ae89300de35f8cc89fdfda8b72d872 | [
"skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Bottom', self, '')\nself.activateBottom = settings.... | <|body_start_0|>
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Bottom', self, '')
... | A class to handle the bottom settings. | BottomRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Bottom button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004356 | 6,865 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Bottom button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048756 | Implement the Python class `BottomRepository` described below.
Class description:
A class to handle the bottom settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Bottom button has been clicked. | Implement the Python class `BottomRepository` described below.
Class description:
A class to handle the bottom settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Bottom button has been clicked.
<|skeleton|>
class BottomR... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Bottom button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)
self.... | the_stack_v2_python_sparse | skeinforge_application/skeinforge_plugins/craft_plugins/bottom.py | amsler/skeinforge | train | 10 |
15ed22f7fffd066270fb8d0534cc859287a9c769 | [
"super().__init__(x, y)\nself.fill_color = QtCore.Qt.lightGray\nself.line_color = QtCore.Qt.darkGray\nself.dx = random.randint(1, 3) * random.choice([-1, 1])\nself.dy = random.randint(1, 3) * random.choice([-1, 1])",
"self.x += self.dx\nself.y += self.dy\nif self.x < 0 or self.x > w:\n self.dx *= -1\nif self.y... | <|body_start_0|>
super().__init__(x, y)
self.fill_color = QtCore.Qt.lightGray
self.line_color = QtCore.Qt.darkGray
self.dx = random.randint(1, 3) * random.choice([-1, 1])
self.dy = random.randint(1, 3) * random.choice([-1, 1])
<|end_body_0|>
<|body_start_1|>
self.x += se... | Class to represent a Dodo bird. | Dodo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dodo:
"""Class to represent a Dodo bird."""
def __init__(self, x, y):
"""Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):
"""A Do... | stack_v2_sparse_classes_75kplus_train_004357 | 13,878 | no_license | [
{
"docstring": "Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "A Dodo bird flies in straight lines and bounces off ... | 2 | stack_v2_sparse_classes_30k_train_020685 | Implement the Python class `Dodo` described below.
Class description:
Class to represent a Dodo bird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.
- def m... | Implement the Python class `Dodo` described below.
Class description:
Class to represent a Dodo bird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.
- def m... | 0e3470085083012f893adb22aa46d46039016965 | <|skeleton|>
class Dodo:
"""Class to represent a Dodo bird."""
def __init__(self, x, y):
"""Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):
"""A Do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dodo:
"""Class to represent a Dodo bird."""
def __init__(self, x, y):
"""Create a new Dodo with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
super().__init__(x, y)
self.fill_color = QtCore.Qt.lightGr... | the_stack_v2_python_sparse | CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py | JacobOrner/USAFA | train | 0 |
494149c262b07853f2afe481c755bb5321dfba05 | [
"commands = [{'name': _('Use'), 'cmd': 'use'}]\ncommands.extend(await super(MudderySkillBook, self).get_available_commands(caller))\nreturn commands",
"if not user:\n raise ValueError('User should not be None.')\nskill_key = self.const.skill\nskill_level = self.const.level\nif not skill_key:\n return (None,... | <|body_start_0|>
commands = [{'name': _('Use'), 'cmd': 'use'}]
commands.extend(await super(MudderySkillBook, self).get_available_commands(caller))
return commands
<|end_body_0|>
<|body_start_1|>
if not user:
raise ValueError('User should not be None.')
skill_key = se... | This is a skill book. Players can use it to learn a new skill. | MudderySkillBook | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MudderySkillBook:
"""This is a skill book. Players can use it to learn a new skill."""
async def get_available_commands(self, caller):
"""This returns a list of available commands. "args" must be a string without ' and ", usually it is self.id."""
<|body_0|>
async def ta... | stack_v2_sparse_classes_75kplus_train_004358 | 6,369 | permissive | [
{
"docstring": "This returns a list of available commands. \"args\" must be a string without ' and \", usually it is self.id.",
"name": "get_available_commands",
"signature": "async def get_available_commands(self, caller)"
},
{
"docstring": "Use this object. Args: user: (object) the object who ... | 2 | stack_v2_sparse_classes_30k_train_015921 | Implement the Python class `MudderySkillBook` described below.
Class description:
This is a skill book. Players can use it to learn a new skill.
Method signatures and docstrings:
- async def get_available_commands(self, caller): This returns a list of available commands. "args" must be a string without ' and ", usual... | Implement the Python class `MudderySkillBook` described below.
Class description:
This is a skill book. Players can use it to learn a new skill.
Method signatures and docstrings:
- async def get_available_commands(self, caller): This returns a list of available commands. "args" must be a string without ' and ", usual... | 5fa06b29bf800646dc4da5851fdf7a1f299f15a7 | <|skeleton|>
class MudderySkillBook:
"""This is a skill book. Players can use it to learn a new skill."""
async def get_available_commands(self, caller):
"""This returns a list of available commands. "args" must be a string without ' and ", usually it is self.id."""
<|body_0|>
async def ta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MudderySkillBook:
"""This is a skill book. Players can use it to learn a new skill."""
async def get_available_commands(self, caller):
"""This returns a list of available commands. "args" must be a string without ' and ", usually it is self.id."""
commands = [{'name': _('Use'), 'cmd': 'us... | the_stack_v2_python_sparse | muddery/server/elements/pocket_object.py | muddery/muddery | train | 139 |
db21072daadeca851cb0cb9fa33afafe62f53382 | [
"super(StandardSkillBuilder, self).__init__()\nself.table_name = table_name\nself.auto_create_table = auto_create_table\nself.partition_keygen = partition_keygen\nself.dynamodb_client = dynamodb_client",
"skill_config = super(StandardSkillBuilder, self).skill_configuration\nskill_config.api_client = DefaultApiCli... | <|body_start_0|>
super(StandardSkillBuilder, self).__init__()
self.table_name = table_name
self.auto_create_table = auto_create_table
self.partition_keygen = partition_keygen
self.dynamodb_client = dynamodb_client
<|end_body_0|>
<|body_start_1|>
skill_config = super(Stan... | Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default Api Client added to the :py:class:`ask_sdk_core.skill.Skill`. :param table_name: Name of... | StandardSkillBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StandardSkillBuilder:
"""Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default Api Client added to the :py:class:`ask_s... | stack_v2_sparse_classes_75kplus_train_004359 | 4,223 | permissive | [
{
"docstring": "Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default Api Client added to the :py:class:`ask_sdk_core.skill.Skill`. :p... | 2 | stack_v2_sparse_classes_30k_train_021651 | Implement the Python class `StandardSkillBuilder` described below.
Class description:
Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default A... | Implement the Python class `StandardSkillBuilder` described below.
Class description:
Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default A... | 7e13ca69b240985584dff6ec633a27598a154ca1 | <|skeleton|>
class StandardSkillBuilder:
"""Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default Api Client added to the :py:class:`ask_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StandardSkillBuilder:
"""Skill Builder with api client and db adapter coupling to Skill. Standard Skill Builder is an implementation of :py:class:`ask_sdk_core.skill_builder.SkillBuilder` with coupling of DynamoDb Persistence Adapter settings and a Default Api Client added to the :py:class:`ask_sdk_core.skill... | the_stack_v2_python_sparse | ask-sdk/ask_sdk/standard.py | alexa/alexa-skills-kit-sdk-for-python | train | 560 |
29abbd1ea85905caa5b284ecae65636de4d33fd3 | [
"if not secret_key:\n return None\nsigner_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)\nreturn URLSafeTimedSerializer(secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=signer_kwargs)",
"sscsi = SimpleSecureCookieSessionInterface()\nsigningSerializer = ... | <|body_start_0|>
if not secret_key:
return None
signer_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)
return URLSafeTimedSerializer(secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=signer_kwargs)
<|end_body_0|>
<|body_start_1... | SimpleSecureCookieSessionInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
<|body_0|>
def decodeFlaskCookie(self, secret_key, cookieValue):
"""Decode a base 64 encoded string"""
<|body_1|>
def encodeFlaskCookie(self,... | stack_v2_sparse_classes_75kplus_train_004360 | 2,701 | no_license | [
{
"docstring": "Used to check secret key",
"name": "get_signing_serializer",
"signature": "def get_signing_serializer(self, secret_key)"
},
{
"docstring": "Decode a base 64 encoded string",
"name": "decodeFlaskCookie",
"signature": "def decodeFlaskCookie(self, secret_key, cookieValue)"
... | 3 | stack_v2_sparse_classes_30k_train_054731 | Implement the Python class `SimpleSecureCookieSessionInterface` described below.
Class description:
Implement the SimpleSecureCookieSessionInterface class.
Method signatures and docstrings:
- def get_signing_serializer(self, secret_key): Used to check secret key
- def decodeFlaskCookie(self, secret_key, cookieValue):... | Implement the Python class `SimpleSecureCookieSessionInterface` described below.
Class description:
Implement the SimpleSecureCookieSessionInterface class.
Method signatures and docstrings:
- def get_signing_serializer(self, secret_key): Used to check secret key
- def decodeFlaskCookie(self, secret_key, cookieValue):... | 24e1e25d2e512105c9bf70b5e33b1afed4790f71 | <|skeleton|>
class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
<|body_0|>
def decodeFlaskCookie(self, secret_key, cookieValue):
"""Decode a base 64 encoded string"""
<|body_1|>
def encodeFlaskCookie(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
if not secret_key:
return None
signer_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)
return URLSafeTimedSerializer(s... | the_stack_v2_python_sparse | flask/app/config.py | InTheNou/InTheNou-Backend | train | 0 | |
a5a1ecda40626b4648c3ec80b6a0b03cb2768267 | [
"if len(probs) != len(rewards):\n raise Exception('获胜概率数组和回报数组长度不匹配!')\nself.probs = probs\nself.rewards = rewards",
"if np.random.rand() < self.probs[i]:\n return self.rewards[i]\nelse:\n return 0.0"
] | <|body_start_0|>
if len(probs) != len(rewards):
raise Exception('获胜概率数组和回报数组长度不匹配!')
self.probs = probs
self.rewards = rewards
<|end_body_0|>
<|body_start_1|>
if np.random.rand() < self.probs[i]:
return self.rewards[i]
else:
return 0.0
<|end_b... | 定义赌博机类 | Bandits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bandits:
"""定义赌博机类"""
def __init__(self, probs, rewards):
""":param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值"""
<|body_0|>
def pull(self, i):
"""从第i号赌博机上返回的奖励 :param i: int型数据,赌博机的编号 :return: float or None"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_004361 | 6,602 | no_license | [
{
"docstring": ":param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值",
"name": "__init__",
"signature": "def __init__(self, probs, rewards)"
},
{
"docstring": "从第i号赌博机上返回的奖励 :param i: int型数据,赌博机的编号 :return: float or None",
"name": "pull",
"signature": "def pull(self, i)"
}
... | 2 | stack_v2_sparse_classes_30k_val_000857 | Implement the Python class `Bandits` described below.
Class description:
定义赌博机类
Method signatures and docstrings:
- def __init__(self, probs, rewards): :param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值
- def pull(self, i): 从第i号赌博机上返回的奖励 :param i: int型数据,赌博机的编号 :return: float or None | Implement the Python class `Bandits` described below.
Class description:
定义赌博机类
Method signatures and docstrings:
- def __init__(self, probs, rewards): :param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值
- def pull(self, i): 从第i号赌博机上返回的奖励 :param i: int型数据,赌博机的编号 :return: float or None
<|skeleton|>
class... | e4b949a236fa52de0e199c69941bcbedd2c26897 | <|skeleton|>
class Bandits:
"""定义赌博机类"""
def __init__(self, probs, rewards):
""":param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值"""
<|body_0|>
def pull(self, i):
"""从第i号赌博机上返回的奖励 :param i: int型数据,赌博机的编号 :return: float or None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bandits:
"""定义赌博机类"""
def __init__(self, probs, rewards):
""":param probs: float数组,赌博机获胜的概率数组 :param rewards: float数组,获胜时的回报值"""
if len(probs) != len(rewards):
raise Exception('获胜概率数组和回报数组长度不匹配!')
self.probs = probs
self.rewards = rewards
def pull(self, i)... | the_stack_v2_python_sparse | kaikeba/RL_BOOK/Chapter12-Bandit/KArmedBandit.py | wangqiang79/learn | train | 2 |
2361b9a96d30fbe16752a84561bf8799304d433a | [
"super(MaskedWordPredictions, self).__init__()\nself.transform = BertPredictionHeadTransform(config)\nself.decoder = nn.Linear(in_features=config.hidden_size, out_features=config.vocab_size, bias=False)\nself.bias = nn.Parameter(torch.zeros(config.vocab_size))",
"hidden_states = self.transform(hidden_states)\nhid... | <|body_start_0|>
super(MaskedWordPredictions, self).__init__()
self.transform = BertPredictionHeadTransform(config)
self.decoder = nn.Linear(in_features=config.hidden_size, out_features=config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
<|end_body_0|>... | MaskedWordPredictions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskedWordPredictions:
def __init__(self, config):
"""事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。"""
<|body_0|>
def forward(self, hidden_states):
"""hidden_states:BERTからの出力[batch_size, seq_len, hidden_size]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_004362 | 30,882 | permissive | [
{
"docstring": "事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "hidden_states:BERTからの出力[batch_size, seq_len, hidden_size]",
"name": "forward",
"signature": "def forward(self, hi... | 2 | stack_v2_sparse_classes_30k_train_043242 | Implement the Python class `MaskedWordPredictions` described below.
Class description:
Implement the MaskedWordPredictions class.
Method signatures and docstrings:
- def __init__(self, config): 事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。
- def forward(self, hidden_states): hidden_state... | Implement the Python class `MaskedWordPredictions` described below.
Class description:
Implement the MaskedWordPredictions class.
Method signatures and docstrings:
- def __init__(self, config): 事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。
- def forward(self, hidden_states): hidden_state... | bada8e07bd7503ed6d7a371fafb7a29b52b06d62 | <|skeleton|>
class MaskedWordPredictions:
def __init__(self, config):
"""事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。"""
<|body_0|>
def forward(self, hidden_states):
"""hidden_states:BERTからの出力[batch_size, seq_len, hidden_size]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskedWordPredictions:
def __init__(self, config):
"""事前学習課題:Masked Language Model用のモジュール 元の[2]の実装では、BertLMPredictionHeadという名前です。"""
super(MaskedWordPredictions, self).__init__()
self.transform = BertPredictionHeadTransform(config)
self.decoder = nn.Linear(in_features=config.hi... | the_stack_v2_python_sparse | 8_nlp_sentiment_bert/utils/bert.py | YutaroOgawa/pytorch_advanced | train | 811 | |
0dbfa9d6cea73580bfcdfc592d6443642a5155d6 | [
"super().__init__(reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95])\nself.arias_stream = None\nself.result = self.get_arias()",
"arias_intensities = {}\narias_stream = StationStream([])\nfor trace in self.reduction_data:\n dt = trace.stats['delta']\n acc = trace... | <|body_start_0|>
super().__init__(reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95])
self.arias_stream = None
self.result = self.get_arias()
<|end_body_0|>
<|body_start_1|>
arias_intensities = {}
arias_stream = StationStream([])
... | Class for calculation of arias intensity. | Arias | [
"Unlicense",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arias:
"""Class for calculation of arias intensity."""
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95]):
"""Args: reduction_data (obspy.core.stream.Stream or numpy.ndarray): Intensity measurement component. bandwidth (... | stack_v2_sparse_classes_75kplus_train_004363 | 2,675 | permissive | [
{
"docstring": "Args: reduction_data (obspy.core.stream.Stream or numpy.ndarray): Intensity measurement component. bandwidth (float): Bandwidth for the smoothing operation. Default is None. percentile (float): Percentile for rotation calculations. Default is None. period (float): Period for smoothing (Fourier a... | 2 | stack_v2_sparse_classes_30k_train_049354 | Implement the Python class `Arias` described below.
Class description:
Class for calculation of arias intensity.
Method signatures and docstrings:
- def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95]): Args: reduction_data (obspy.core.stream.Stream or num... | Implement the Python class `Arias` described below.
Class description:
Class for calculation of arias intensity.
Method signatures and docstrings:
- def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95]): Args: reduction_data (obspy.core.stream.Stream or num... | 5c0395f2ae3608861cfd47f1cc3fbe9b2ed82a93 | <|skeleton|>
class Arias:
"""Class for calculation of arias intensity."""
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95]):
"""Args: reduction_data (obspy.core.stream.Stream or numpy.ndarray): Intensity measurement component. bandwidth (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Arias:
"""Class for calculation of arias intensity."""
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95]):
"""Args: reduction_data (obspy.core.stream.Stream or numpy.ndarray): Intensity measurement component. bandwidth (float): Bandw... | the_stack_v2_python_sparse | gmprocess/metrics/reduction/arias.py | mhearne-usgs/groundmotion-processing | train | 1 |
d4d5c3d783bd0d52bbaafec3659b89675f0e9449 | [
"self._apiUrl = 'https://ws.maniaplanet.com'\nself._userName = userName\nself._password = password\nself._enableAuth = True\nself._headers = {}\nself._accept = 'application/json'\nself._contentType = 'application/json'\nself._serializeCallback = json.dumps\nself._unserializeCallback = json.loads",
"url = self._ap... | <|body_start_0|>
self._apiUrl = 'https://ws.maniaplanet.com'
self._userName = userName
self._password = password
self._enableAuth = True
self._headers = {}
self._accept = 'application/json'
self._contentType = 'application/json'
self._serializeCallback = j... | rief The client will connect to the system and authenticate itself | HTTPClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPClient:
"""rief The client will connect to the system and authenticate itself"""
def __init__(self, userName=None, password=None):
"""rief Create a new client \\param userName The name of the user to authenticate \\param password His password"""
<|body_0|>
def exec... | stack_v2_sparse_classes_75kplus_train_004364 | 11,594 | no_license | [
{
"docstring": "\brief Create a new client \\\\param userName The name of the user to authenticate \\\\param password His password",
"name": "__init__",
"signature": "def __init__(self, userName=None, password=None)"
},
{
"docstring": "\brief Execute an HTML request \\\\param method The method t... | 2 | null | Implement the Python class `HTTPClient` described below.
Class description:
rief The client will connect to the system and authenticate itself
Method signatures and docstrings:
- def __init__(self, userName=None, password=None): rief Create a new client \\param userName The name of the user to authenticate \\param ... | Implement the Python class `HTTPClient` described below.
Class description:
rief The client will connect to the system and authenticate itself
Method signatures and docstrings:
- def __init__(self, userName=None, password=None): rief Create a new client \\param userName The name of the user to authenticate \\param ... | 9b143c686d445020ba27ac35e1c3e0df468dd1f8 | <|skeleton|>
class HTTPClient:
"""rief The client will connect to the system and authenticate itself"""
def __init__(self, userName=None, password=None):
"""rief Create a new client \\param userName The name of the user to authenticate \\param password His password"""
<|body_0|>
def exec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTTPClient:
"""rief The client will connect to the system and authenticate itself"""
def __init__(self, userName=None, password=None):
"""rief Create a new client \\param userName The name of the user to authenticate \\param password His password"""
self._apiUrl = 'https://ws.maniaplane... | the_stack_v2_python_sparse | ManiaConnect.py | schulmar/tmc | train | 3 |
3d513a1c8f53aa004d2421d649cbb5e3b41e4cf2 | [
"if cls.get_max_from_database:\n cls.seqnum = cls.machine_input_dao.get_max_seq_number_value()\n cls.get_max_from_database = False\nif cls.machine_input_dao.get_one_record():\n cls.__generate_machine_random_data()\n return {'seqnum': cls.seqnum, 'machineId': cls.machine_id, 'timestamp': cls.timestamp, '... | <|body_start_0|>
if cls.get_max_from_database:
cls.seqnum = cls.machine_input_dao.get_max_seq_number_value()
cls.get_max_from_database = False
if cls.machine_input_dao.get_one_record():
cls.__generate_machine_random_data()
return {'seqnum': cls.seqnum, 'ma... | MachineData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachineData:
def get_random_machine_data(cls) -> dict:
"""create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremented value machineId: 1, timestamp: 111111, # datetime now pickedLayers: 3 # random number from 1 to ... | stack_v2_sparse_classes_75kplus_train_004365 | 2,441 | no_license | [
{
"docstring": "create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremented value machineId: 1, timestamp: 111111, # datetime now pickedLayers: 3 # random number from 1 to 8 } :return: return dictionary with random machine data",
"nam... | 2 | stack_v2_sparse_classes_30k_train_035125 | Implement the Python class `MachineData` described below.
Class description:
Implement the MachineData class.
Method signatures and docstrings:
- def get_random_machine_data(cls) -> dict: create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremen... | Implement the Python class `MachineData` described below.
Class description:
Implement the MachineData class.
Method signatures and docstrings:
- def get_random_machine_data(cls) -> dict: create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremen... | ad06da559c673157ea1d20730eb1ea8320a87dd0 | <|skeleton|>
class MachineData:
def get_random_machine_data(cls) -> dict:
"""create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremented value machineId: 1, timestamp: 111111, # datetime now pickedLayers: 3 # random number from 1 to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MachineData:
def get_random_machine_data(cls) -> dict:
"""create a random machine data to send to machine metrics service. Send a dictionary with this structure: { seqnumber: 1, # incremented value machineId: 1, timestamp: 111111, # datetime now pickedLayers: 3 # random number from 1 to 8 } :return: r... | the_stack_v2_python_sparse | stacking_layers_machine/src/libs/machine_data.py | hugobranco/koerber | train | 0 | |
89f67c60f1b50e0e4a876628b0231090c038f511 | [
"if n == 0 or n == 1:\n return 1\nelse:\n return self.climbStairs(n - 1) + self.climbStairs(n - 2)",
"if n == 0 or n == 1:\n return 1\nelse:\n dp = [0] * (n + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\n return dp[-1]",
"if n == 0 or n =... | <|body_start_0|>
if n == 0 or n == 1:
return 1
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
<|end_body_0|>
<|body_start_1|>
if n == 0 or n == 1:
return 1
else:
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""Time: N/A Time limit exceeded Mem: N/A ^"""
<|body_0|>
def climbStairs(self, n):
"""Time: 24ms (96.94%) Mem: 12.7 MB (100%)"""
<|body_1|>
def climbStairs(self, n):
"""Time: 28ms (90.99%) Mem: 12.... | stack_v2_sparse_classes_75kplus_train_004366 | 1,874 | no_license | [
{
"docstring": "Time: N/A Time limit exceeded Mem: N/A ^",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "Time: 24ms (96.94%) Mem: 12.7 MB (100%)",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": "Tim... | 3 | stack_v2_sparse_classes_30k_train_014091 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: Time: N/A Time limit exceeded Mem: N/A ^
- def climbStairs(self, n): Time: 24ms (96.94%) Mem: 12.7 MB (100%)
- def climbStairs(self, n): Tim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: Time: N/A Time limit exceeded Mem: N/A ^
- def climbStairs(self, n): Time: 24ms (96.94%) Mem: 12.7 MB (100%)
- def climbStairs(self, n): Tim... | 5a40f53602d3a5f4d5478ac6ea2b41f3272420db | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""Time: N/A Time limit exceeded Mem: N/A ^"""
<|body_0|>
def climbStairs(self, n):
"""Time: 24ms (96.94%) Mem: 12.7 MB (100%)"""
<|body_1|>
def climbStairs(self, n):
"""Time: 28ms (90.99%) Mem: 12.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def climbStairs(self, n: int) -> int:
"""Time: N/A Time limit exceeded Mem: N/A ^"""
if n == 0 or n == 1:
return 1
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
def climbStairs(self, n):
"""Time: 24ms (96.94%) Mem: 12.7 MB... | the_stack_v2_python_sparse | coding-problems/leetcode/recursion/climb_stairs.py | BaoAdrian/interview-prep | train | 0 | |
f278d63da0acaadab646491a24872dda2c080f23 | [
"super(ConvMaxpool, self).__init__()\nfor kernel_size in kernel_sizes:\n assert kernel_size % 2 == 1, 'kernel size has to be odd numbers.'\nif isinstance(kernel_sizes, (list, tuple, int)):\n if isinstance(kernel_sizes, int) and isinstance(out_channels, int):\n out_channels = [out_channels]\n ker... | <|body_start_0|>
super(ConvMaxpool, self).__init__()
for kernel_size in kernel_sizes:
assert kernel_size % 2 == 1, 'kernel size has to be odd numbers.'
if isinstance(kernel_sizes, (list, tuple, int)):
if isinstance(kernel_sizes, int) and isinstance(out_channels, int):
... | 集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。 | ConvMaxpool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvMaxpool:
"""集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。"""
def __init__(self, in_channels, out_channels, kernel_sizes, acti... | stack_v2_sparse_classes_75kplus_train_004367 | 3,608 | permissive | [
{
"docstring": ":param int in_channels: 输入channel的大小,一般是embedding的维度; 或encoder的output维度 :param int,tuple(int) out_channels: 输出channel的数量。如果为list,则需要与kernel_sizes的数量保持一致 :param int,tuple(int) kernel_sizes: 输出channel的kernel大小。 :param str activation: Convolution后的结果将通过该activation后再经过max-pooling。支持relu, sigmoid, ta... | 2 | stack_v2_sparse_classes_30k_train_008045 | Implement the Python class `ConvMaxpool` described below.
Class description:
集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。
Method signatures and docstrings... | Implement the Python class `ConvMaxpool` described below.
Class description:
集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。
Method signatures and docstrings... | dffc7a06cdbff2671a3ca73d2398159d91a4a7db | <|skeleton|>
class ConvMaxpool:
"""集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。"""
def __init__(self, in_channels, out_channels, kernel_sizes, acti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvMaxpool:
"""集合了Convolution和Max-Pooling于一体的层。给定一个batch_size x max_len x input_size的输入,返回batch_size x sum(output_channels) 大小的matrix。在内部,是先使用CNN给输入做卷积,然后经过activation激活层,在通过在长度(max_len) 这一维进行max_pooling。最后得到每个sample的一个向量表示。"""
def __init__(self, in_channels, out_channels, kernel_sizes, activation='relu'... | the_stack_v2_python_sparse | phenobert/utils/fastNLP/modules/encoder/conv_maxpool.py | TianlabTech/PhenoBERT | train | 2 |
311c8f3a881de0e4dc9a145266bbad767e830452 | [
"parser = reqparse.RequestParser()\nparser.add_argument('key', type=str, required=True)\nreturn parser",
"parser = reqparse.RequestParser()\nparser.add_argument('documents', type=FileStorage, required=True, location='files', action='append')\nparser.add_argument('campaign_name', type=str, required=True)\nparser.a... | <|body_start_0|>
parser = reqparse.RequestParser()
parser.add_argument('key', type=str, required=True)
return parser
<|end_body_0|>
<|body_start_1|>
parser = reqparse.RequestParser()
parser.add_argument('documents', type=FileStorage, required=True, location='files', action='appe... | DocumentParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentParser:
def get_parser() -> reqparse.RequestParser:
"""Parse the get request"""
<|body_0|>
def post_parser() -> reqparse.RequestParser:
"""Parse the post request"""
<|body_1|>
def delete_parser() -> reqparse.RequestParser:
"""Parse the de... | stack_v2_sparse_classes_75kplus_train_004368 | 7,078 | no_license | [
{
"docstring": "Parse the get request",
"name": "get_parser",
"signature": "def get_parser() -> reqparse.RequestParser"
},
{
"docstring": "Parse the post request",
"name": "post_parser",
"signature": "def post_parser() -> reqparse.RequestParser"
},
{
"docstring": "Parse the delet... | 3 | stack_v2_sparse_classes_30k_train_023804 | Implement the Python class `DocumentParser` described below.
Class description:
Implement the DocumentParser class.
Method signatures and docstrings:
- def get_parser() -> reqparse.RequestParser: Parse the get request
- def post_parser() -> reqparse.RequestParser: Parse the post request
- def delete_parser() -> reqpa... | Implement the Python class `DocumentParser` described below.
Class description:
Implement the DocumentParser class.
Method signatures and docstrings:
- def get_parser() -> reqparse.RequestParser: Parse the get request
- def post_parser() -> reqparse.RequestParser: Parse the post request
- def delete_parser() -> reqpa... | 17b93889c6945db15ed8b57147def2ae89a07de5 | <|skeleton|>
class DocumentParser:
def get_parser() -> reqparse.RequestParser:
"""Parse the get request"""
<|body_0|>
def post_parser() -> reqparse.RequestParser:
"""Parse the post request"""
<|body_1|>
def delete_parser() -> reqparse.RequestParser:
"""Parse the de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentParser:
def get_parser() -> reqparse.RequestParser:
"""Parse the get request"""
parser = reqparse.RequestParser()
parser.add_argument('key', type=str, required=True)
return parser
def post_parser() -> reqparse.RequestParser:
"""Parse the post request"""
... | the_stack_v2_python_sparse | FiledInfluencer/Api/AWSDocuments/request_handler.py | jssellars/aniket_filed | train | 0 | |
89d2abb77bba966b4027cbed8649f19a85a05f83 | [
"self.ui = ui\nself.file_list_display = FileListDisplay.FileListDisplay(ui=ui)\nself.directory_display = DirectoryDisplay.DirectoryDisplay(ui=ui)\nself.image_display = ImageDisplay.ImageDisplay(ui=ui)\nself.save_image = SaveImage.SaveImage(ui=ui, image_display_object=self.image_display)\nself.stream_display = Strea... | <|body_start_0|>
self.ui = ui
self.file_list_display = FileListDisplay.FileListDisplay(ui=ui)
self.directory_display = DirectoryDisplay.DirectoryDisplay(ui=ui)
self.image_display = ImageDisplay.ImageDisplay(ui=ui)
self.save_image = SaveImage.SaveImage(ui=ui, image_display_object=... | NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data). | Slots | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slots:
"""NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data)."""
def __init__(self, ui: IPViewWindow):
"""Instantiation must be the last thi... | stack_v2_sparse_classes_75kplus_train_004369 | 4,194 | no_license | [
{
"docstring": "Instantiation must be the last thing the GUI does. :param ui: IPViewWindow object",
"name": "__init__",
"signature": "def __init__(self, ui: IPViewWindow)"
},
{
"docstring": "Slot method for next image called",
"name": "next_button_pushed",
"signature": "def next_button_p... | 4 | stack_v2_sparse_classes_30k_train_013078 | Implement the Python class `Slots` described below.
Class description:
NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data).
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `Slots` described below.
Class description:
NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data).
Method signatures and docstrings:
- def __init__(se... | 840ff86d2d0bce76f09a10af97276d77ef120586 | <|skeleton|>
class Slots:
"""NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data)."""
def __init__(self, ui: IPViewWindow):
"""Instantiation must be the last thi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Slots:
"""NOTE: Any method defined in here is a slot intended to control multiple functions in the program (i.e. the clear may operate on the image display, the directory display and the application data)."""
def __init__(self, ui: IPViewWindow):
"""Instantiation must be the last thing the GUI do... | the_stack_v2_python_sparse | ip_view_ui/signals_and_slots.py | nellyBoi/IPView | train | 0 |
67c697e2a82919a9469e2550ae43384f3adfe900 | [
"conn = kpdb.connect(schema=self.schema_name, catalog='hive')\nself.assertTrue(isinstance(conn, Connection))\nself.assertEqual(conn.schema, self.schema_name)\nself.assertEqual(conn.catalog, 'hive')",
"class SQLTest:\n\n def __init__(self, sql_test, params, sql_verify):\n self.sql_test = sql_test\n ... | <|body_start_0|>
conn = kpdb.connect(schema=self.schema_name, catalog='hive')
self.assertTrue(isinstance(conn, Connection))
self.assertEqual(conn.schema, self.schema_name)
self.assertEqual(conn.catalog, 'hive')
<|end_body_0|>
<|body_start_1|>
class SQLTest:
def __in... | TestPrestoDatabaseUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPrestoDatabaseUtils:
def test_connect(self):
"""Test connection to presto returns presto.dbapi.Connection instance"""
<|body_0|>
def test_sql_mogrify(self):
"""Test that sql_mogrify renders a syntactically correct SQL statement"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus_train_004370 | 4,165 | permissive | [
{
"docstring": "Test connection to presto returns presto.dbapi.Connection instance",
"name": "test_connect",
"signature": "def test_connect(self)"
},
{
"docstring": "Test that sql_mogrify renders a syntactically correct SQL statement",
"name": "test_sql_mogrify",
"signature": "def test_s... | 5 | stack_v2_sparse_classes_30k_train_053555 | Implement the Python class `TestPrestoDatabaseUtils` described below.
Class description:
Implement the TestPrestoDatabaseUtils class.
Method signatures and docstrings:
- def test_connect(self): Test connection to presto returns presto.dbapi.Connection instance
- def test_sql_mogrify(self): Test that sql_mogrify rende... | Implement the Python class `TestPrestoDatabaseUtils` described below.
Class description:
Implement the TestPrestoDatabaseUtils class.
Method signatures and docstrings:
- def test_connect(self): Test connection to presto returns presto.dbapi.Connection instance
- def test_sql_mogrify(self): Test that sql_mogrify rende... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class TestPrestoDatabaseUtils:
def test_connect(self):
"""Test connection to presto returns presto.dbapi.Connection instance"""
<|body_0|>
def test_sql_mogrify(self):
"""Test that sql_mogrify renders a syntactically correct SQL statement"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPrestoDatabaseUtils:
def test_connect(self):
"""Test connection to presto returns presto.dbapi.Connection instance"""
conn = kpdb.connect(schema=self.schema_name, catalog='hive')
self.assertTrue(isinstance(conn, Connection))
self.assertEqual(conn.schema, self.schema_name)
... | the_stack_v2_python_sparse | koku/koku/test_presto_db_utils.py | luisfdez/koku | train | 0 | |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')\nsuper().__init__(*args, **kwargs)\nif InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):\n self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attrs={'type': 'email', 'placeholder': _('Ema... | <|body_start_0|>
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):
self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attr... | Override to use dynamic settings. | CustomSignupForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_75kplus_train_004371 | 12,546 | permissive | [
{
"docstring": "Check settings to influence which fields are needed.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Make sure the supllied emails match if enabled in settings.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003118 | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if Inv... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
8e00a064e4c1962219e02a7dc9195d87a2d5da7c | [
"if not isinstance(xs, list):\n return SyntaxError\nif not all([isinstance(x, list) for x in xs]):\n result = ' '.join([str(x) for x in xs])\nelse:\n n = range(len(xs))\n ps = [len(str(x)) for x in xs[-1]]\n str_table_list = ['|'.join(line) for line in [['%*d' % v for v in zip(ps, xs[n])] for n in ra... | <|body_start_0|>
if not isinstance(xs, list):
return SyntaxError
if not all([isinstance(x, list) for x in xs]):
result = ' '.join([str(x) for x in xs])
else:
n = range(len(xs))
ps = [len(str(x)) for x in xs[-1]]
str_table_list = ['|'.jo... | TableShow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
<|body_0|>
def show(s... | stack_v2_sparse_classes_75kplus_train_004372 | 1,358 | no_license | [
{
"docstring": "リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)",
"name": "__init__",
"signature": "def __init__(self, *xs, index=None, column=None, mode=0)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_049156 | Implement the Python class `TableShow` described below.
Class description:
Implement the TableShow class.
Method signatures and docstrings:
- def __init__(self, *xs, index=None, column=None, mode=0): リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mo... | Implement the Python class `TableShow` described below.
Class description:
Implement the TableShow class.
Method signatures and docstrings:
- def __init__(self, *xs, index=None, column=None, mode=0): リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mo... | 2bf21081dd4803c7f4702b6cfccbaca3d2aa6f7b | <|skeleton|>
class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
<|body_0|>
def show(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TableShow:
def __init__(self, *xs, index=None, column=None, mode=0):
"""リストを表として整形する @param *xs 表示したいリスト(行の要素ごとをリストとする) @param index 1列目に表示するリスト(mode=1 指定なしで要素数) @param column 1行目に表示するリスト(mode=1 指定なしで要素数) @param mode indexとcolumnを含めるか(default=0 含めない)"""
if not isinstance(xs, list):
... | the_stack_v2_python_sparse | Python/201910/191010/TableShow00.py | 96no3/PythonStudy | train | 0 | |
7c9ff0b45db87c652e3861d436b59f59a5344f3d | [
"self.key = key\nself.subjectid = subjectid\nself.region_ids = set([])\nself.set_regions()",
"d = _dictp(JSON_FILE)\nregions = d.getp(self.key).get('regions')\nfor key, region in regions.items():\n assert isinstance(region, dict)\n if self.subjectid is None:\n self.region_ids.add(key)\n else:\n ... | <|body_start_0|>
self.key = key
self.subjectid = subjectid
self.region_ids = set([])
self.set_regions()
<|end_body_0|>
<|body_start_1|>
d = _dictp(JSON_FILE)
regions = d.getp(self.key).get('regions')
for key, region in regions.items():
assert isinstan... | really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject (fish) | Subject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject... | stack_v2_sparse_classes_75kplus_train_004373 | 28,538 | no_license | [
{
"docstring": "(str, str) Key is the unique key for the image, subjectid is set as an integer to uniquely identify a subject",
"name": "__init__",
"signature": "def __init__(self, key, subjectid=None)"
},
{
"docstring": "Checks all regions defined on the image, regions which are defined on the ... | 3 | stack_v2_sparse_classes_30k_train_032669 | Implement the Python class `Subject` described below.
Class description:
really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are t... | Implement the Python class `Subject` described below.
Class description:
really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are t... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject (fish)"""
... | the_stack_v2_python_sparse | opencvlib/imgpipes/vgg.py | gmonkman/python | train | 0 |
cef2b5861fa3e232f5a6574246b28a99cd53136e | [
"assert revision in self.blame_list\nfor i in range(0, len(self.blame_list)):\n if revision == self.blame_list[i]:\n return i + self.previous_build_commit_position + 1",
"length = len(self.blame_list)\nassert commit_position > self.commit_position - length and commit_position <= self.commit_position\nre... | <|body_start_0|>
assert revision in self.blame_list
for i in range(0, len(self.blame_list)):
if revision == self.blame_list[i]:
return i + self.previous_build_commit_position + 1
<|end_body_0|>
<|body_start_1|>
length = len(self.blame_list)
assert commit_posi... | DataPoint | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
<|body_0|>
def GetRevisionAtCommitP... | stack_v2_sparse_classes_75kplus_train_004374 | 11,733 | permissive | [
{
"docstring": "Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision.",
"name": "GetCommitPosition",
"signature": "def GetCommitPosition(self, revision)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_053794 | Implement the Python class `DataPoint` described below.
Class description:
Implement the DataPoint class.
Method signatures and docstrings:
- def GetCommitPosition(self, revision): Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int... | Implement the Python class `DataPoint` described below.
Class description:
Implement the DataPoint class.
Method signatures and docstrings:
- def GetCommitPosition(self, revision): Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
<|body_0|>
def GetRevisionAtCommitP... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataPoint:
def GetCommitPosition(self, revision):
"""Gets the commit position of a revision within blame_list. Args: revision (str): The revision to search for. Returns: commit_position (int): The calculated commit position of revision."""
assert revision in self.blame_list
for i in ra... | the_stack_v2_python_sparse | appengine/findit/model/flake/master_flake_analysis.py | mcgreevy/chromium-infra | train | 1 | |
88532568ed0803c04d93009566786ab833a27119 | [
"self.logger = logging.getLogger('Multivac')\nself.logger.addHandler(logging.StreamHandler())\nself.logger.setLevel(logging.DEBUG)\nassert environment_name in ENVIRONMENTS, '{} is not a valid environment name'.format(environment_name)\nassert agent_name in AGENTS, '{} is not a valid agent name'.format(agent_name)\n... | <|body_start_0|>
self.logger = logging.getLogger('Multivac')
self.logger.addHandler(logging.StreamHandler())
self.logger.setLevel(logging.DEBUG)
assert environment_name in ENVIRONMENTS, '{} is not a valid environment name'.format(environment_name)
assert agent_name in AGENTS, '{}... | The Multivac class starts an environment and an agent in that environment. | Multivac | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Multivac:
"""The Multivac class starts an environment and an agent in that environment."""
def __init__(self, environment_name, agent_name, num_steps, redis_port, video_fps=1, display_video=False):
"""Initialize the Multivac. This involves, 1. Open a redis client and setting up an ac... | stack_v2_sparse_classes_75kplus_train_004375 | 6,646 | permissive | [
{
"docstring": "Initialize the Multivac. This involves, 1. Open a redis client and setting up an action and observation buffer. This establishes an exchange protocol between the Multivac and a ConnectionClient 2. Gather an initial observation from the observation buffer to collect metadata information 3. Initia... | 3 | null | Implement the Python class `Multivac` described below.
Class description:
The Multivac class starts an environment and an agent in that environment.
Method signatures and docstrings:
- def __init__(self, environment_name, agent_name, num_steps, redis_port, video_fps=1, display_video=False): Initialize the Multivac. T... | Implement the Python class `Multivac` described below.
Class description:
The Multivac class starts an environment and an agent in that environment.
Method signatures and docstrings:
- def __init__(self, environment_name, agent_name, num_steps, redis_port, video_fps=1, display_video=False): Initialize the Multivac. T... | 27b5d490c015b68e268d4d44a0ff17b8ab519274 | <|skeleton|>
class Multivac:
"""The Multivac class starts an environment and an agent in that environment."""
def __init__(self, environment_name, agent_name, num_steps, redis_port, video_fps=1, display_video=False):
"""Initialize the Multivac. This involves, 1. Open a redis client and setting up an ac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Multivac:
"""The Multivac class starts an environment and an agent in that environment."""
def __init__(self, environment_name, agent_name, num_steps, redis_port, video_fps=1, display_video=False):
"""Initialize the Multivac. This involves, 1. Open a redis client and setting up an action and obse... | the_stack_v2_python_sparse | session/multivac.py | SirjanK/Multivac | train | 0 |
39f336e6c29a22692d3faffd57a848085d18d4e4 | [
"self.std = std\nself.mean = mean\nself.var = var\nself.sqmean = sqmean",
"self.mean += mean\nself.sqmean += mean ** 2\nself.var += var",
"self.mean /= n\nself.var /= n\nself.sqmean /= n\nself.std = self.var\nself.std += self.sqmean\nself.std -= self.mean ** 2\nself.std = np.sqrt(self.std)"
] | <|body_start_0|>
self.std = std
self.mean = mean
self.var = var
self.sqmean = sqmean
<|end_body_0|>
<|body_start_1|>
self.mean += mean
self.sqmean += mean ** 2
self.var += var
<|end_body_1|>
<|body_start_2|>
self.mean /= n
self.var /= n
s... | NormParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormParam:
def __init__(self, std=0, mean=0, var=0, sqmean=0):
"""Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, variance and square root of the mean value of a mapped feature stored in the hdf5 file. As the entire dat... | stack_v2_sparse_classes_75kplus_train_004376 | 7,713 | permissive | [
{
"docstring": "Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, variance and square root of the mean value of a mapped feature stored in the hdf5 file. As the entire data set is too large to fit in memory, the standard deviation of a given fea... | 3 | null | Implement the Python class `NormParam` described below.
Class description:
Implement the NormParam class.
Method signatures and docstrings:
- def __init__(self, std=0, mean=0, var=0, sqmean=0): Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, varianc... | Implement the Python class `NormParam` described below.
Class description:
Implement the NormParam class.
Method signatures and docstrings:
- def __init__(self, std=0, mean=0, var=0, sqmean=0): Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, varianc... | 6bc8d7e4893fc06f952d6e2b1edfc4e1c19bc671 | <|skeleton|>
class NormParam:
def __init__(self, std=0, mean=0, var=0, sqmean=0):
"""Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, variance and square root of the mean value of a mapped feature stored in the hdf5 file. As the entire dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NormParam:
def __init__(self, std=0, mean=0, var=0, sqmean=0):
"""Compute gaussian normalization for a given feature. This class allows to extract the standard deviation, mean value, variance and square root of the mean value of a mapped feature stored in the hdf5 file. As the entire data set is too l... | the_stack_v2_python_sparse | deeprank/generate/NormalizeData.py | DeepRank/deeprank | train | 140 | |
03aa21e900b598db057b70080027f69206b1eceb | [
"self.zs_train = zs\nself.ys_train = ys\nif online:\n self.prev_pred = np.zeros_like(ys[0])\nself.online = online",
"assert len(zs) == len(ys)\nself.zs_train += zs\nself.ys_train += ys",
"preds, _ = self.compute_pred(zs)\nif self.online:\n if np.linalg.norm(preds[-1]) < 1e-06:\n print('using prev p... | <|body_start_0|>
self.zs_train = zs
self.ys_train = ys
if online:
self.prev_pred = np.zeros_like(ys[0])
self.online = online
<|end_body_0|>
<|body_start_1|>
assert len(zs) == len(ys)
self.zs_train += zs
self.ys_train += ys
<|end_body_1|>
<|body_start... | Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory. | Predictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory."""
def __init__(self, zs=[], ys=[], online=False... | stack_v2_sparse_classes_75kplus_train_004377 | 11,255 | permissive | [
{
"docstring": "Create a predictor.",
"name": "__init__",
"signature": "def __init__(self, zs=[], ys=[], online=False)"
},
{
"docstring": "Add data to the predictor. Parameters ---------- zs : list Observations to add. ys : list Corresponding labels.",
"name": "add_data",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_003004 | Implement the Python class `Predictor` described below.
Class description:
Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory.
Method signat... | Implement the Python class `Predictor` described below.
Class description:
Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory.
Method signat... | 4afd0001897044a45e682ccb2db4bb19f20cb738 | <|skeleton|>
class Predictor:
"""Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory."""
def __init__(self, zs=[], ys=[], online=False... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Predictor:
"""Base class for predictors. Parameters ---------- zs_train : list List of training observations. ys_train : list List of training measurements. online : boolean Flag to determine whether prediction should incorporate basic memory."""
def __init__(self, zs=[], ys=[], online=False):
""... | the_stack_v2_python_sparse | python/predictors.py | modestyachts/certainty_equiv_perception_control | train | 3 |
e261ee90ac21f193058a3a9581da3dc8b8eef0ec | [
"for group in self:\n if group.match(environments):\n return group\nreturn None",
"ret = set()\nfor group in self:\n for env in group.environments:\n ret.add(HashableEnvironment(name=env.name, typename=env.environmentType.name))\nreturn sorted(ret, key=lambda e: e.typename)"
] | <|body_start_0|>
for group in self:
if group.match(environments):
return group
return None
<|end_body_0|>
<|body_start_1|>
ret = set()
for group in self:
for env in group.environments:
ret.add(HashableEnvironment(name=env.name, typ... | BaseEnvironmentGroupList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEnvironmentGroupList:
def match(self, environments):
"""If the given set of ``environments`` match any environment group in this environment group list, return that environment group. Else return None."""
<|body_0|>
def environments(self):
"""Return a list of all... | stack_v2_sparse_classes_75kplus_train_004378 | 8,477 | no_license | [
{
"docstring": "If the given set of ``environments`` match any environment group in this environment group list, return that environment group. Else return None.",
"name": "match",
"signature": "def match(self, environments)"
},
{
"docstring": "Return a list of all unique environments in this en... | 2 | stack_v2_sparse_classes_30k_train_027034 | Implement the Python class `BaseEnvironmentGroupList` described below.
Class description:
Implement the BaseEnvironmentGroupList class.
Method signatures and docstrings:
- def match(self, environments): If the given set of ``environments`` match any environment group in this environment group list, return that enviro... | Implement the Python class `BaseEnvironmentGroupList` described below.
Class description:
Implement the BaseEnvironmentGroupList class.
Method signatures and docstrings:
- def match(self, environments): If the given set of ``environments`` match any environment group in this environment group list, return that enviro... | deb6b22ed417740bf947e86938710bd5fa2ee2e7 | <|skeleton|>
class BaseEnvironmentGroupList:
def match(self, environments):
"""If the given set of ``environments`` match any environment group in this environment group list, return that environment group. Else return None."""
<|body_0|>
def environments(self):
"""Return a list of all... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseEnvironmentGroupList:
def match(self, environments):
"""If the given set of ``environments`` match any environment group in this environment group list, return that environment group. Else return None."""
for group in self:
if group.match(environments):
return g... | the_stack_v2_python_sparse | ccui/environments/models.py | camd/caseconductor-ui | train | 0 | |
eac9947fe8db536ca3633fdd7bb41f100c38b9dd | [
"super().__init__()\nself.attention = Attention(**attention)\nself.feedforward = nn.Sequential(nn.Linear(features, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, features))\nself.attention_norm = nn.LayerNorm(features)\nself.feedforward_norm = nn.LayerNorm(features, elementwise_affine=False)",
"X = self.attention_... | <|body_start_0|>
super().__init__()
self.attention = Attention(**attention)
self.feedforward = nn.Sequential(nn.Linear(features, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, features))
self.attention_norm = nn.LayerNorm(features)
self.feedforward_norm = nn.LayerNorm(features, el... | Layer based on the original Attention is All You Need paper and is usable in graph network setups | AttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the... | stack_v2_sparse_classes_75kplus_train_004379 | 1,534 | permissive | [
{
"docstring": "features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the feedforward network",
"name": "__init__",
"signature": "def __init__(self, features, hidden_dim, attention)"
},
{
"docstring": "X - data tensor, torch.FloatTensor(batch_si... | 2 | stack_v2_sparse_classes_30k_train_047561 | Implement the Python class `AttentionLayer` described below.
Class description:
Layer based on the original Attention is All You Need paper and is usable in graph network setups
Method signatures and docstrings:
- def __init__(self, features, hidden_dim, attention): features - the number of features the layer has at ... | Implement the Python class `AttentionLayer` described below.
Class description:
Layer based on the original Attention is All You Need paper and is usable in graph network setups
Method signatures and docstrings:
- def __init__(self, features, hidden_dim, attention): features - the number of features the layer has at ... | 327844cea18a6dfe35e0dc8f5de0832343487366 | <|skeleton|>
class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttentionLayer:
"""Layer based on the original Attention is All You Need paper and is usable in graph network setups"""
def __init__(self, features, hidden_dim, attention):
"""features - the number of features the layer has at input and output hidden_dim - the hidden dimension of the feedforward ... | the_stack_v2_python_sparse | neuralDX7/models/attention/attention_layer.py | jGambit/NeuralDX7 | train | 0 |
b658698b670d72a91e53e311eed5a5eaeb83727f | [
"for account in cloud_accounts:\n rc, rsp = cal.get_image_list(RwcalYang.YangData_RwProject_Project_CloudAccounts_CloudAccountList.from_dict(account.as_dict()))\n assert rc == RwTypes.RwStatus.SUCCESS\n if rsp is not None:\n for image in rsp.imageinfo_list:\n if random_image_name in image... | <|body_start_0|>
for account in cloud_accounts:
rc, rsp = cal.get_image_list(RwcalYang.YangData_RwProject_Project_CloudAccounts_CloudAccountList.from_dict(account.as_dict()))
assert rc == RwTypes.RwStatus.SUCCESS
if rsp is not None:
for image in rsp.imageinfo_... | TestNsrTeardown | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
<|body_0|>
def test_terminate_nsr(self, rwvnfr_proxy, rwnsr_proxy... | stack_v2_sparse_classes_75kplus_train_004380 | 26,676 | no_license | [
{
"docstring": "Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images",
"name": "test_delete_embedded_images",
"signature": "def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal)"
},
{
"docstring": "Terminate the insta... | 3 | stack_v2_sparse_classes_30k_test_002408 | Implement the Python class `TestNsrTeardown` described below.
Class description:
Implement the TestNsrTeardown class.
Method signatures and docstrings:
- def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal): Deletes images embedded in VNF from VIM. It only deletes additional images, not the F... | Implement the Python class `TestNsrTeardown` described below.
Class description:
Implement the TestNsrTeardown class.
Method signatures and docstrings:
- def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal): Deletes images embedded in VNF from VIM. It only deletes additional images, not the F... | cdd0abe80a76d533d08a51c7970d8ded06624b7d | <|skeleton|>
class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
<|body_0|>
def test_terminate_nsr(self, rwvnfr_proxy, rwnsr_proxy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNsrTeardown:
def test_delete_embedded_images(self, random_image_name, cloud_accounts, cal):
"""Deletes images embedded in VNF from VIM. It only deletes additional images, not the Fedora ping pong images"""
for account in cloud_accounts:
rc, rsp = cal.get_image_list(RwcalYang.Ya... | the_stack_v2_python_sparse | osm/SO/rwlaunchpad/ra/pytest/ns/test_onboard.py | dennis-me/Pishahang | train | 2 | |
2c9de69a49f13f14a8e37bb4b44036914a38c7c6 | [
"cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)\nresponse = create_response(200)\nif cert_setting.count() > 0:\n response.data = {'flag': True}\nelse:\n response.data = {'flag': False}\nreturn response.get_response()",
"cert_setting = WxCertSettings.objects.filter(owner_id=request... | <|body_start_0|>
cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)
response = create_response(200)
if cert_setting.count() > 0:
response.data = {'flag': True}
else:
response.data = {'flag': False}
return response.get_response()
<|en... | Group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
def api_get(request):
"""响应GET"""
<|body_0|>
def get(request):
"""响应GET"""
<|body_1|>
def api_put(request):
"""响应PUT"""
<|body_2|>
def api_post(request):
"""响应POST"""
<|body_3|>
def api_delete(request):
... | stack_v2_sparse_classes_75kplus_train_004381 | 4,576 | no_license | [
{
"docstring": "响应GET",
"name": "api_get",
"signature": "def api_get(request)"
},
{
"docstring": "响应GET",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "响应PUT",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "响应POST",
... | 5 | stack_v2_sparse_classes_30k_train_031044 | Implement the Python class `Group` described below.
Class description:
Implement the Group class.
Method signatures and docstrings:
- def api_get(request): 响应GET
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE | Implement the Python class `Group` described below.
Class description:
Implement the Group class.
Method signatures and docstrings:
- def api_get(request): 响应GET
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE
<|skeleton|>
class Group:
... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Group:
def api_get(request):
"""响应GET"""
<|body_0|>
def get(request):
"""响应GET"""
<|body_1|>
def api_put(request):
"""响应PUT"""
<|body_2|>
def api_post(request):
"""响应POST"""
<|body_3|>
def api_delete(request):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Group:
def api_get(request):
"""响应GET"""
cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)
response = create_response(200)
if cert_setting.count() > 0:
response.data = {'flag': True}
else:
response.data = {'flag': False}
... | the_stack_v2_python_sparse | weapp/apps/customerized_apps/group/group.py | chengdg/weizoom | train | 1 | |
546d1cad439b7d937cb6f663332ab6e877374028 | [
"params = kwargs.get('params')\nheaders = kwargs.get('headers')\nurl = kwargs.get('url')\ntry:\n result = requests.get(url=url, params=params, headers=headers)\n return result\nexcept Exception as e:\n print('get请求错误: %s' % e)",
"log = Log()\nparams = kwargs.get('params')\ndata = kwargs.get('data')\njson... | <|body_start_0|>
params = kwargs.get('params')
headers = kwargs.get('headers')
url = kwargs.get('url')
try:
result = requests.get(url=url, params=params, headers=headers)
return result
except Exception as e:
print('get请求错误: %s' % e)
<|end_body_... | Test_Requests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Requests:
def get(self, **kwargs):
"""封装get方法"""
<|body_0|>
def post(self, url, **kwargs):
"""封装yyj方法"""
<|body_1|>
def run_main(self, method, **kwargs):
"""判断请求类型 :param method: 请求接口类型 :param kwargs: 填参数 :return: 接口返回内容"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_004382 | 1,537 | no_license | [
{
"docstring": "封装get方法",
"name": "get",
"signature": "def get(self, **kwargs)"
},
{
"docstring": "封装yyj方法",
"name": "post",
"signature": "def post(self, url, **kwargs)"
},
{
"docstring": "判断请求类型 :param method: 请求接口类型 :param kwargs: 填参数 :return: 接口返回内容",
"name": "run_main",
... | 3 | stack_v2_sparse_classes_30k_train_018738 | Implement the Python class `Test_Requests` described below.
Class description:
Implement the Test_Requests class.
Method signatures and docstrings:
- def get(self, **kwargs): 封装get方法
- def post(self, url, **kwargs): 封装yyj方法
- def run_main(self, method, **kwargs): 判断请求类型 :param method: 请求接口类型 :param kwargs: 填参数 :retur... | Implement the Python class `Test_Requests` described below.
Class description:
Implement the Test_Requests class.
Method signatures and docstrings:
- def get(self, **kwargs): 封装get方法
- def post(self, url, **kwargs): 封装yyj方法
- def run_main(self, method, **kwargs): 判断请求类型 :param method: 请求接口类型 :param kwargs: 填参数 :retur... | 7719674278d1324aad283f381e62199cfecb0178 | <|skeleton|>
class Test_Requests:
def get(self, **kwargs):
"""封装get方法"""
<|body_0|>
def post(self, url, **kwargs):
"""封装yyj方法"""
<|body_1|>
def run_main(self, method, **kwargs):
"""判断请求类型 :param method: 请求接口类型 :param kwargs: 填参数 :return: 接口返回内容"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_Requests:
def get(self, **kwargs):
"""封装get方法"""
params = kwargs.get('params')
headers = kwargs.get('headers')
url = kwargs.get('url')
try:
result = requests.get(url=url, params=params, headers=headers)
return result
except Exception... | the_stack_v2_python_sparse | yyyTest/common/TestRequests.py | luoyangcheng/luoyc | train | 1 | |
31e4556dbf4f84186b1a20b03300fbf10e10504a | [
"self.ip = 'forward.xdaili.cn'\nself.port = '80'\nself.orderno = 'ZF2018***********'\nself.secert = '**********************************'",
"manifest_json = '\\n {\\n \"version\": \"1.0.0\",\\n \"manifest_version\": 2,\\n \"name\": \"Xdaili Proxy\",\\n ... | <|body_start_0|>
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert = '**********************************'
<|end_body_0|>
<|body_start_1|>
manifest_json = '\n {\n "version": "1.0.0",\n "manifest_... | Xdaili | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""构造代理 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert... | stack_v2_sparse_classes_75kplus_train_004383 | 2,357 | no_license | [
{
"docstring": "初始化信息",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "构造代理 :return:",
"name": "auth",
"signature": "def auth(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012031 | Implement the Python class `Xdaili` described below.
Class description:
Implement the Xdaili class.
Method signatures and docstrings:
- def __init__(self): 初始化信息
- def auth(self): 构造代理 :return: | Implement the Python class `Xdaili` described below.
Class description:
Implement the Xdaili class.
Method signatures and docstrings:
- def __init__(self): 初始化信息
- def auth(self): 构造代理 :return:
<|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""... | 87cbae60f7a5b033851b0056dff741a3d5980d06 | <|skeleton|>
class Xdaili:
def __init__(self):
"""初始化信息"""
<|body_0|>
def auth(self):
"""构造代理 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Xdaili:
def __init__(self):
"""初始化信息"""
self.ip = 'forward.xdaili.cn'
self.port = '80'
self.orderno = 'ZF2018***********'
self.secert = '**********************************'
def auth(self):
"""构造代理 :return:"""
manifest_json = '\n {\n ... | the_stack_v2_python_sparse | 04-Selenium_Taobao/xdaili.py | Northxw/Python3_WebSpider | train | 545 | |
467e48ec41e543d21ee3258f1a9251b88fb3ebf4 | [
"left, right, valid = (0, 0, 0)\nneeds = {}\nwindow = {}\nfor c in s1:\n if c in needs:\n needs[c] += 1\n else:\n needs[c] = 1\nwhile right < len(s2):\n c = s2[right]\n right += 1\n if c in needs:\n if c in window:\n window[c] += 1\n else:\n window[c]... | <|body_start_0|>
left, right, valid = (0, 0, 0)
needs = {}
window = {}
for c in s1:
if c in needs:
needs[c] += 1
else:
needs[c] = 1
while right < len(s2):
c = s2[right]
right += 1
if c in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right, valid = ... | stack_v2_sparse_classes_75kplus_train_004384 | 2,383 | no_license | [
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "checkInclusion",
"signature": "def checkInclusion(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "checkInclusion",
"signature": "def checkInclusion(self, s1, s2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Soluti... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
left, right, valid = (0, 0, 0)
needs = {}
window = {}
for c in s1:
if c in needs:
needs[c] += 1
else:
needs[c] = 1
... | the_stack_v2_python_sparse | 0567_Permutation_in_String.py | bingli8802/leetcode | train | 0 | |
46395e9a5a7ac24af41612ca86dbc80425e84b42 | [
"self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself._THRESHOLD = 60000\nself.osint_obj = OSINT(debug=debug)",
"if pkt.haslayer(scapy.IP) and pkt.haslayer(scapy.ICMP):\n if pkt.haslayer(scapy.Raw):\n load_len = len(pkt[scapy.Raw].load)\n if load_len >= self._THRESHOLD:\n ... | <|body_start_0|>
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self._THRESHOLD = 60000
self.osint_obj = OSINT(debug=debug)
<|end_body_0|>
<|body_start_1|>
if pkt.haslayer(scapy.IP) and pkt.haslayer(scapy.ICMP):
if pkt.haslayer(scapy.Raw):
load_l... | PingOfDeath class. | PingOfDeath | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PingOfDeath:
"""PingOfDeath class."""
def __init__(self, debug=False):
"""Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect(self, pkt):
"""Detect ping of death attack by calculating load thresho... | stack_v2_sparse_classes_75kplus_train_004385 | 2,228 | permissive | [
{
"docstring": "Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Detect ping of death attack by calculating load threshold. Args: pkt (scapy_object): Packet to dis... | 2 | stack_v2_sparse_classes_30k_train_047271 | Implement the Python class `PingOfDeath` described below.
Class description:
PingOfDeath class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect(self, pkt): Detect ping of death attack by cal... | Implement the Python class `PingOfDeath` described below.
Class description:
PingOfDeath class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect(self, pkt): Detect ping of death attack by cal... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class PingOfDeath:
"""PingOfDeath class."""
def __init__(self, debug=False):
"""Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect(self, pkt):
"""Detect ping of death attack by calculating load thresho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PingOfDeath:
"""PingOfDeath class."""
def __init__(self, debug=False):
"""Initialize PingOfDeath. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self._THRESHOLD = 60000
self.osint_obj = O... | the_stack_v2_python_sparse | securetea/lib/ids/r2l_rules/ping_of_death.py | rejahrehim/SecureTea-Project | train | 1 |
e5f6aa134be72f17bcaf5de0c6ff7ece0e1318f7 | [
"knownVariables = {}\nfor i in range(0, len(values)):\n a = equations[i][0]\n b = equations[i][1]\n if a not in knownVariables:\n knownVariables[a] = {}\n knownVariables[a][b] = values[i]\n if b not in knownVariables:\n knownVariables[b] = {}\n knownVariables[b][a] = 1 / values[i]\nr... | <|body_start_0|>
knownVariables = {}
for i in range(0, len(values)):
a = equations[i][0]
b = equations[i][1]
if a not in knownVariables:
knownVariables[a] = {}
knownVariables[a][b] = values[i]
if b not in knownVariables:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calcEquation(self, equations, values, queries):
""":type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]"""
<|body_0|>
def solve(self, numerator, denominator, knownVariables):
""":type numerator: s... | stack_v2_sparse_classes_75kplus_train_004386 | 3,056 | permissive | [
{
"docstring": ":type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]",
"name": "calcEquation",
"signature": "def calcEquation(self, equations, values, queries)"
},
{
"docstring": ":type numerator: str :type denominator: str :type seed: int... | 2 | stack_v2_sparse_classes_30k_train_023896 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calcEquation(self, equations, values, queries): :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]
- def solve(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calcEquation(self, equations, values, queries): :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]
- def solve(self... | 9217d1dddbb7171134854a27023ea79ccfaf80d6 | <|skeleton|>
class Solution:
def calcEquation(self, equations, values, queries):
""":type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]"""
<|body_0|>
def solve(self, numerator, denominator, knownVariables):
""":type numerator: s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calcEquation(self, equations, values, queries):
""":type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]"""
knownVariables = {}
for i in range(0, len(values)):
a = equations[i][0]
b = equation... | the_stack_v2_python_sparse | leetcode/src/evaluate-division.py | chadccollins/algo | train | 0 | |
70aabd6683ba8213f7a634d55b8f376177250505 | [
"url = reverse('category-list')\ndata = {'category': 'S'}\nresponse = self.client.post(url, data, format='json')\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(Category.objects.count(), 1)\nself.assertEqual(Category.objects.get().category, 'S')",
"url = reverse('category-list')... | <|body_start_0|>
url = reverse('category-list')
data = {'category': 'S'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Category.objects.count(), 1)
self.assertEqual(Category.objects.g... | CategoryRegistrationAPIViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
<|body_0|>
def test_error_category(self):
"""Test to verify that a bad post call with category"""
<|body_1|>
def test_two_category(self)... | stack_v2_sparse_classes_75kplus_train_004387 | 1,595 | no_license | [
{
"docstring": "Test to verify that a post call with category",
"name": "test_one_category",
"signature": "def test_one_category(self)"
},
{
"docstring": "Test to verify that a bad post call with category",
"name": "test_error_category",
"signature": "def test_error_category(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_007828 | Implement the Python class `CategoryRegistrationAPIViewTestCase` described below.
Class description:
Implement the CategoryRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_one_category(self): Test to verify that a post call with category
- def test_error_category(self): Test to verify t... | Implement the Python class `CategoryRegistrationAPIViewTestCase` described below.
Class description:
Implement the CategoryRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_one_category(self): Test to verify that a post call with category
- def test_error_category(self): Test to verify t... | 6b2296994b6db3a828715d2f47b340d84e5b4c84 | <|skeleton|>
class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
<|body_0|>
def test_error_category(self):
"""Test to verify that a bad post call with category"""
<|body_1|>
def test_two_category(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
url = reverse('category-list')
data = {'category': 'S'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, sta... | the_stack_v2_python_sparse | app/categories/tests.py | sergiii24/FitHaus_Backend | train | 0 | |
2da01db8b824caf2e796f347a9242e93e4df598c | [
"user_agent = request.META.get('HTTP_USER_AGENT')\nif user_agent is not None:\n for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n if user_agent_regex.search(user_agent):\n raise PermissionDenied('Forbidden user agent')\nhost = request.get_host()\nif settings.PREPEND_WWW and host and (n... | <|body_start_0|>
user_agent = request.META.get('HTTP_USER_AGENT')
if user_agent is not None:
for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
if user_agent_regex.search(user_agent):
raise PermissionDenied('Forbidden user agent')
host = requ... | "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a sla... | CommonMiddleware | [
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-1.0-or-later",
"Python-2.0.1",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonMiddleware:
""""Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is se... | stack_v2_sparse_classes_75kplus_train_004388 | 7,648 | permissive | [
{
"docstring": "Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Return True if settings.APPEND_SLASH is True and appending a slash to the req... | 4 | stack_v2_sparse_classes_30k_train_023108 | Implement the Python class `CommonMiddleware` described below.
Class description:
"Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends m... | Implement the Python class `CommonMiddleware` described below.
Class description:
"Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends m... | c74a6fad5475495756a5bdb18b2cab2b68d429bc | <|skeleton|>
class CommonMiddleware:
""""Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonMiddleware:
""""Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the ini... | the_stack_v2_python_sparse | django/middleware/common.py | django/django | train | 73,530 |
6028af31c5379cc2052c35fe9db46305deefd329 | [
"n = len(init_val)\nself.segfunc = segfunc\nself.ide_ele = ide_ele\nself.num = 1 << (n - 1).bit_length()\nself.tree = [ide_ele for i in range(2 * self.num)]\nfor i in range(n):\n self.tree[self.num + i] = init_val[i]\nfor i in range(self.num - 1, 0, -1):\n self.tree[i] = self.segfunc(self.tree[2 * i], self.tr... | <|body_start_0|>
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele for i in range(2 * self.num)]
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - ... | init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) | SegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-ind... | stack_v2_sparse_classes_75kplus_train_004389 | 5,112 | no_license | [
{
"docstring": "init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)",
"name": "__init__",
"signature": "def __init__(self, init_val, segfunc, ide_ele)"
},
{
"docstring": "k番目の値をxに更新 k: index(0-index) x: update value",
"name": "update",
"signatur... | 3 | null | Implement the Python class `SegmentTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作... | Implement the Python class `SegmentTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作... | 39f6f6f4cc893e794d99c514f2e5adc9009ee8ca | <|skeleton|>
class SegmentTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-ind... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SegmentTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"""
... | the_stack_v2_python_sparse | abc/abc239/E.py | cocoinit23/atcoder | train | 1 |
b14c241912377e20b9cd05c7dbf38419fc272ab7 | [
"l = height\nsize = 0\nfor i in range(len(l)):\n for j in range(i, len(l)):\n print(l[i], l[j])\n if l[i] < l[j]:\n size = max(size, l[i] * (j - i))\n else:\n size = max(size, l[j] * (j - i))\nreturn size",
"head = 0\ntail = len(height) - 1\nsize = 0\nwhile head < tai... | <|body_start_0|>
l = height
size = 0
for i in range(len(l)):
for j in range(i, len(l)):
print(l[i], l[j])
if l[i] < l[j]:
size = max(size, l[i] * (j - i))
else:
size = max(size, l[j] * (j - i))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = height
size = 0
for ... | stack_v2_sparse_classes_75kplus_train_004390 | 1,118 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxAreaBrute",
"signature": "def maxAreaBrute(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012630 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(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 maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxAre... | 673fb7bb900e65844b68b5826a259eb6932c5fc4 | <|skeleton|>
class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
l = height
size = 0
for i in range(len(l)):
for j in range(i, len(l)):
print(l[i], l[j])
if l[i] < l[j]:
size = max(size, l[i] * (... | the_stack_v2_python_sparse | 11. Container With Most Water.py | MysticEEEE/LeetCodeProblems | train | 0 | |
1f8a744a0c5495ded77df7737fd33081dcbf90e7 | [
"filing_effective_date = filing_effective_date.replace(tzinfo=None)\nregistrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.strptime(x['endDate'], '%Y-%m-... | <|body_start_0|>
filing_effective_date = filing_effective_date.replace(tzinfo=None)
registrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.str... | Utility to get the relevant registrar info for a filing. | RegistrarInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
<|body_0|>
def encode_registrar_signature(signature_image) -> str:
"""Return the encoded ... | stack_v2_sparse_classes_75kplus_train_004391 | 3,514 | permissive | [
{
"docstring": "Return the registrar for a filing.",
"name": "get_registrar_info",
"signature": "def get_registrar_info(filing_effective_date) -> dict"
},
{
"docstring": "Return the encoded registrar signature.",
"name": "encode_registrar_signature",
"signature": "def encode_registrar_si... | 2 | stack_v2_sparse_classes_30k_train_046888 | Implement the Python class `RegistrarInfo` described below.
Class description:
Utility to get the relevant registrar info for a filing.
Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str... | Implement the Python class `RegistrarInfo` described below.
Class description:
Utility to get the relevant registrar info for a filing.
Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
<|body_0|>
def encode_registrar_signature(signature_image) -> str:
"""Return the encoded ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
filing_effective_date = filing_effective_date.replace(tzinfo=None)
registrar = [x for x in RegistrarInfo.re... | the_stack_v2_python_sparse | legal-api/src/legal_api/reports/registrar_meta.py | bcgov/lear | train | 13 |
20562acdfab1a81284ac4ae7146ce8ce20882e14 | [
"BaseSceneObject.__init__(self)\nself.kill_when_finished = kill_when_finished\nself.dead_remove_from_scene = False\nself.root_mesh = root_mesh\nself.angles = {}\nself.rots = {}\nfor i in self.root_mesh.get_names():\n a = math3d.Vector(self.root_mesh.get_obj_by_name(i).base_pos)\n x, y, z = (a.x, a.y, a.z)\n ... | <|body_start_0|>
BaseSceneObject.__init__(self)
self.kill_when_finished = kill_when_finished
self.dead_remove_from_scene = False
self.root_mesh = root_mesh
self.angles = {}
self.rots = {}
for i in self.root_mesh.get_names():
a = math3d.Vector(self.root... | A simple class to explode/dismember a mesh object. | Exploder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exploder:
"""A simple class to explode/dismember a mesh object."""
def __init__(self, root_mesh, speed=0.025, frame_duration=10, kill_when_finished=True):
"""Create the exploder root_mesh must be a BasicMesh object to explode speed is how fast you want each piece to move/rotate frame... | stack_v2_sparse_classes_75kplus_train_004392 | 27,021 | permissive | [
{
"docstring": "Create the exploder root_mesh must be a BasicMesh object to explode speed is how fast you want each piece to move/rotate frame_duration is how many times it will update before dying kill_when_finished indicates whether the exploder should be removed from the scene when it ends",
"name": "__i... | 3 | null | Implement the Python class `Exploder` described below.
Class description:
A simple class to explode/dismember a mesh object.
Method signatures and docstrings:
- def __init__(self, root_mesh, speed=0.025, frame_duration=10, kill_when_finished=True): Create the exploder root_mesh must be a BasicMesh object to explode s... | Implement the Python class `Exploder` described below.
Class description:
A simple class to explode/dismember a mesh object.
Method signatures and docstrings:
- def __init__(self, root_mesh, speed=0.025, frame_duration=10, kill_when_finished=True): Create the exploder root_mesh must be a BasicMesh object to explode s... | 756bb6d27939bed3c2834222d03096e90f05a788 | <|skeleton|>
class Exploder:
"""A simple class to explode/dismember a mesh object."""
def __init__(self, root_mesh, speed=0.025, frame_duration=10, kill_when_finished=True):
"""Create the exploder root_mesh must be a BasicMesh object to explode speed is how fast you want each piece to move/rotate frame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Exploder:
"""A simple class to explode/dismember a mesh object."""
def __init__(self, root_mesh, speed=0.025, frame_duration=10, kill_when_finished=True):
"""Create the exploder root_mesh must be a BasicMesh object to explode speed is how fast you want each piece to move/rotate frame_duration is ... | the_stack_v2_python_sparse | pyggel/mesh.py | DeadZombie14/chillMagicCarPygame | train | 0 |
9aa67eebd904f7a639e5ea3f0c9717466fd6a7aa | [
"body_dict = super(RelatedEntity, self).to_body_dict()\nbody_dict['_relatedFields'] = []\nfor attrname, field in six.iteritems(self._meta._related_fields):\n body_dict['_relatedFields'].append(attrname)\nreturn body_dict",
"attributes = {}\nauthors = [author for author in getattr(self, 'authors', []) if author... | <|body_start_0|>
body_dict = super(RelatedEntity, self).to_body_dict()
body_dict['_relatedFields'] = []
for attrname, field in six.iteritems(self._meta._related_fields):
body_dict['_relatedFields'].append(attrname)
return body_dict
<|end_body_0|>
<|body_start_1|>
att... | Model for entities related to projects. | RelatedEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelatedEntity:
"""Model for entities related to projects."""
def to_body_dict(self):
"""Serialize to Agave's REST API payload JSON."""
<|body_0|>
def to_datacite_json(self):
"""Serialize object to datacite JSON. Every entity subclassing this class should add a `a... | stack_v2_sparse_classes_75kplus_train_004393 | 27,672 | no_license | [
{
"docstring": "Serialize to Agave's REST API payload JSON.",
"name": "to_body_dict",
"signature": "def to_body_dict(self)"
},
{
"docstring": "Serialize object to datacite JSON. Every entity subclassing this class should add a `attributes['types']['resourceType']` e.g. ``attributes['types']['res... | 2 | stack_v2_sparse_classes_30k_train_003579 | Implement the Python class `RelatedEntity` described below.
Class description:
Model for entities related to projects.
Method signatures and docstrings:
- def to_body_dict(self): Serialize to Agave's REST API payload JSON.
- def to_datacite_json(self): Serialize object to datacite JSON. Every entity subclassing this ... | Implement the Python class `RelatedEntity` described below.
Class description:
Model for entities related to projects.
Method signatures and docstrings:
- def to_body_dict(self): Serialize to Agave's REST API payload JSON.
- def to_datacite_json(self): Serialize object to datacite JSON. Every entity subclassing this ... | 040e0d88eac6037703a6128d6f4644b5a99ea11b | <|skeleton|>
class RelatedEntity:
"""Model for entities related to projects."""
def to_body_dict(self):
"""Serialize to Agave's REST API payload JSON."""
<|body_0|>
def to_datacite_json(self):
"""Serialize object to datacite JSON. Every entity subclassing this class should add a `a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelatedEntity:
"""Model for entities related to projects."""
def to_body_dict(self):
"""Serialize to Agave's REST API payload JSON."""
body_dict = super(RelatedEntity, self).to_body_dict()
body_dict['_relatedFields'] = []
for attrname, field in six.iteritems(self._meta._re... | the_stack_v2_python_sparse | designsafe/apps/projects/models/agave/base.py | DesignSafe-CI/portal | train | 12 |
c75fb2483b9159215950960d67feb10f05c5db98 | [
"self.input = '([])(){}(())()()'\nself.output = True\nreturn (self.input, self.output)",
"input_val, output_val = self.SetUp()\nmethod_output = balancedBrackets(input_val)\nself.assertEqual(method_output, output_val)"
] | <|body_start_0|>
self.input = '([])(){}(())()()'
self.output = True
return (self.input, self.output)
<|end_body_0|>
<|body_start_1|>
input_val, output_val = self.SetUp()
method_output = balancedBrackets(input_val)
self.assertEqual(method_output, output_val)
<|end_body_1|... | Class with unittests for BalancedBrackets.py | test_BalancedBrackets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_BalancedBrackets:
"""Class with unittests for BalancedBrackets.py"""
def SetUp(self):
"""Set Up input matrix."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_75kplus_train_004394 | 890 | no_license | [
{
"docstring": "Set Up input matrix.",
"name": "SetUp",
"signature": "def SetUp(self)"
},
{
"docstring": "Checks if output is correct.",
"name": "test_Iterative_method",
"signature": "def test_Iterative_method(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003878 | Implement the Python class `test_BalancedBrackets` described below.
Class description:
Class with unittests for BalancedBrackets.py
Method signatures and docstrings:
- def SetUp(self): Set Up input matrix.
- def test_Iterative_method(self): Checks if output is correct. | Implement the Python class `test_BalancedBrackets` described below.
Class description:
Class with unittests for BalancedBrackets.py
Method signatures and docstrings:
- def SetUp(self): Set Up input matrix.
- def test_Iterative_method(self): Checks if output is correct.
<|skeleton|>
class test_BalancedBrackets:
"... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_BalancedBrackets:
"""Class with unittests for BalancedBrackets.py"""
def SetUp(self):
"""Set Up input matrix."""
<|body_0|>
def test_Iterative_method(self):
"""Checks if output is correct."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_BalancedBrackets:
"""Class with unittests for BalancedBrackets.py"""
def SetUp(self):
"""Set Up input matrix."""
self.input = '([])(){}(())()()'
self.output = True
return (self.input, self.output)
def test_Iterative_method(self):
"""Checks if output is co... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/BalancedBrackets/test_BalancedBrackets.py | JakubKazimierski/PythonPortfolio | train | 9 |
dcc3cf3baf252c3c94fbd7d0dcfcad7192ebffb6 | [
"try:\n self.minimum_realizations = int(minimum_realizations)\nexcept TypeError:\n if minimum_realizations is not None:\n raise\n self.minimum_realizations = None\nself.new_name = new_name\nself.broadcast = broadcast\nself.cell_method_coordinate = cell_method_coordinate\nself.expand_bound = expand_b... | <|body_start_0|>
try:
self.minimum_realizations = int(minimum_realizations)
except TypeError:
if minimum_realizations is not None:
raise
self.minimum_realizations = None
self.new_name = new_name
self.broadcast = broadcast
self.c... | Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. expanding time for accumulations / max in period) the upper bound of the new ... | Combine | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Combine:
"""Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. expanding time for accumulations / max in ... | stack_v2_sparse_classes_75kplus_train_004395 | 23,529 | permissive | [
{
"docstring": "Args: operation (str): An operation to use in combining input cubes. One of: +, -, \\\\*, add, subtract, multiply, min, max, mean broadcast (str): If specified, broadcast input cubes to the stated coord prior to combining - the coord must already exist on the first input cube. minimum_realizatio... | 2 | stack_v2_sparse_classes_30k_train_050809 | Implement the Python class `Combine` described below.
Class description:
Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. exp... | Implement the Python class `Combine` described below.
Class description:
Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. exp... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Combine:
"""Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. expanding time for accumulations / max in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Combine:
"""Combine input cubes. Combine the input cubes into a single cube using the requested operation. The first cube in the input list provides the template for output metadata. If coordinates are expanded as a result of this combine operation (e.g. expanding time for accumulations / max in period) the u... | the_stack_v2_python_sparse | improver/cube_combiner.py | metoppv/improver | train | 101 |
235eb64785ce8d66ab796d609bc19a5680f415db | [
"self.wtr = csv.DictWriter(target, WriteNoStop.heading)\nself.wtr.writeheader()\nself.count = 0",
"row = report.as_dict()\nrow['status'] = status\nif dist_fit:\n row.update(prefix_dict('candidate_1', dist_fit))\nif time_fit:\n row.update(prefix_dict('candidate_2', time_fit))\nself.wtr.writerow(row)\nself.co... | <|body_start_0|>
self.wtr = csv.DictWriter(target, WriteNoStop.heading)
self.wtr.writeheader()
self.count = 0
<|end_body_0|>
<|body_start_1|>
row = report.as_dict()
row['status'] = status
if dist_fit:
row.update(prefix_dict('candidate_1', dist_fit))
i... | A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. :: with open( args.reject, 'wb') as no_stop_file: no_stop= NoStop( no_stop_file ... | WriteNoStop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteNoStop:
"""A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. :: with open( args.reject, 'wb') as no_st... | stack_v2_sparse_classes_75kplus_train_004396 | 25,200 | no_license | [
{
"docstring": "Create the CSV writer around the target file. :param target: file-like object suitable to CSV writer.",
"name": "__init__",
"signature": "def __init__(self, target=None)"
},
{
"docstring": "Write a row to the no-stop file. :param message: Short string explanation :param report: :... | 2 | stack_v2_sparse_classes_30k_train_023550 | Implement the Python class `WriteNoStop` described below.
Class description:
A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. ::... | Implement the Python class `WriteNoStop` described below.
Class description:
A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. ::... | 2b2c721d55ecaadd745b3a0bba43730501820d64 | <|skeleton|>
class WriteNoStop:
"""A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. :: with open( args.reject, 'wb') as no_st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriteNoStop:
"""A callable writer for reports that have been matched to a stop. This creates a CSV-format file attributes from :class:`caravel.report.Report` and the stop definitions. How to create an object usable a callback with :func:`arrival_at_stop`. :: with open( args.reject, 'wb') as no_stop_file: no_s... | the_stack_v2_python_sparse | spike/arrival_at_stop.py | slott56/Caravel-Transit | train | 0 |
7b006546a8c8f9992d0c0bc24001f513ea0cb2ae | [
"jwt_value = self.get_jwt_value(request)\nif jwt_value is None:\n return None\ntry:\n payload = jwt_decode_handler(jwt_value)\nexcept jwt.ExpiredSignature:\n msg = _('Signature has expired.')\n raise exceptions.AuthenticationFailed(msg)\nexcept jwt.DecodeError:\n msg = _('Error decoding signature.')\... | <|body_start_0|>
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg... | CustomJSONWebTokenAuthentication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomJSONWebTokenAuthentication:
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
<|body_0|>
def authenticate_credentials(self, payload):
"... | stack_v2_sparse_classes_75kplus_train_004397 | 3,111 | no_license | [
{
"docstring": "Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Returns an active user that matches the payload's u... | 2 | stack_v2_sparse_classes_30k_train_050908 | Implement the Python class `CustomJSONWebTokenAuthentication` described below.
Class description:
Implement the CustomJSONWebTokenAuthentication class.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based au... | Implement the Python class `CustomJSONWebTokenAuthentication` described below.
Class description:
Implement the CustomJSONWebTokenAuthentication class.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based au... | 92dc7736c1a89d13a6c024fe7c5a5e04ad6d6e11 | <|skeleton|>
class CustomJSONWebTokenAuthentication:
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
<|body_0|>
def authenticate_credentials(self, payload):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomJSONWebTokenAuthentication:
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
re... | the_stack_v2_python_sparse | utils/authentication.py | tientaitu97/Custom_login | train | 0 | |
d8ecd574c4c88ec43fd4559438d58e766ba0e03b | [
"self.sys_n = sys_n\nif x0 is not None:\n self.x0 = x0\nelse:\n self.x0 = np.zeros(sys_n)\nself.n_2_diag = sys_n\nself.n_2_off = int((sys_n ** 2 - sys_n) / 2)\nself.n_2 = +self.n_2_diag + self.n_2_off\nself.n_1 = sys_n\nself.n_0 = 1\nself.n = int(self.n_2 + self.n_1 + self.n_0)",
"phi = np.zeros(self.n)\nx ... | <|body_start_0|>
self.sys_n = sys_n
if x0 is not None:
self.x0 = x0
else:
self.x0 = np.zeros(sys_n)
self.n_2_diag = sys_n
self.n_2_off = int((sys_n ** 2 - sys_n) / 2)
self.n_2 = +self.n_2_diag + self.n_2_off
self.n_1 = sys_n
self.n_... | QuadraticFunctionApproximator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticFunctionApproximator:
def __init__(self, sys_n=2, x0=None):
"""J_hat = C + B x + x' A x = w' phi"""
<|body_0|>
def compute_kernel(self, x):
"""return approx a state x"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sys_n = sys_n
... | stack_v2_sparse_classes_75kplus_train_004398 | 9,392 | permissive | [
{
"docstring": "J_hat = C + B x + x' A x = w' phi",
"name": "__init__",
"signature": "def __init__(self, sys_n=2, x0=None)"
},
{
"docstring": "return approx a state x",
"name": "compute_kernel",
"signature": "def compute_kernel(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033745 | Implement the Python class `QuadraticFunctionApproximator` described below.
Class description:
Implement the QuadraticFunctionApproximator class.
Method signatures and docstrings:
- def __init__(self, sys_n=2, x0=None): J_hat = C + B x + x' A x = w' phi
- def compute_kernel(self, x): return approx a state x | Implement the Python class `QuadraticFunctionApproximator` described below.
Class description:
Implement the QuadraticFunctionApproximator class.
Method signatures and docstrings:
- def __init__(self, sys_n=2, x0=None): J_hat = C + B x + x' A x = w' phi
- def compute_kernel(self, x): return approx a state x
<|skelet... | baed84610d6090d42b814183931709fcdf61d012 | <|skeleton|>
class QuadraticFunctionApproximator:
def __init__(self, sys_n=2, x0=None):
"""J_hat = C + B x + x' A x = w' phi"""
<|body_0|>
def compute_kernel(self, x):
"""return approx a state x"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuadraticFunctionApproximator:
def __init__(self, sys_n=2, x0=None):
"""J_hat = C + B x + x' A x = w' phi"""
self.sys_n = sys_n
if x0 is not None:
self.x0 = x0
else:
self.x0 = np.zeros(sys_n)
self.n_2_diag = sys_n
self.n_2_off = int((sys_... | the_stack_v2_python_sparse | dev/reinforcement_learning/approximate_dp_tests/functionapproximation.py | SherbyRobotics/pyro | train | 35 | |
f30497be13679db52d80358c553ceabc0ae00929 | [
"self.nums = nums\nself.pairs = {}\nfor i in range(0, len(nums), 1):\n self.pairs[i] = nums[i]",
"for index, value in self.pairs.items():\n self.nums[index] = value\nreturn self.nums",
"temp = self.pairs\nnew = {}\ncurrent = set()\ncounter = 0\nwhile len(current) != len(self.nums):\n index = random.ran... | <|body_start_0|>
self.nums = nums
self.pairs = {}
for i in range(0, len(nums), 1):
self.pairs[i] = nums[i]
<|end_body_0|>
<|body_start_1|>
for index, value in self.pairs.items():
self.nums[index] = value
return self.nums
<|end_body_1|>
<|body_start_2|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]"""
<|body_1|>
def shuffle(self):
"""Returns a random shuffling of the a... | stack_v2_sparse_classes_75kplus_train_004399 | 1,281 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "Resets the array to its original configuration and return it. :rtype: List[int]",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "Returns a ra... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def reset(self): Resets the array to its original configuration and return it. :rtype: List[int]
- def shuffle(self): Returns a ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def reset(self): Resets the array to its original configuration and return it. :rtype: List[int]
- def shuffle(self): Returns a ... | e836343be5185f8843bb77197fccff250e9a77e3 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]"""
<|body_1|>
def shuffle(self):
"""Returns a random shuffling of the a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
self.pairs = {}
for i in range(0, len(nums), 1):
self.pairs[i] = nums[i]
def reset(self):
"""Resets the array to its original configuration and return it. :rtype: List[int]... | the_stack_v2_python_sparse | leetcode/shuffle_an_array.py | rishabhranawat/challenge | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.