blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
790398f78e2b4dfe4ee2b1529cbc034cf1012e49 | [
"self.states = states\nself.default_state = self.states[0]\nsuper().__init__(self.default_state)\nself.eval_stab = v.Btn(children=['Check stability'], color='primary')\nfor s in states:\n self.item_list.children.append(self.create_item(s))\nself.item_list.notify_change({'name': 'children', 'type': 'change'})\nse... | <|body_start_0|>
self.states = states
self.default_state = self.states[0]
super().__init__(self.default_state)
self.eval_stab = v.Btn(children=['Check stability'], color='primary')
for s in states:
self.item_list.children.append(self.create_item(s))
self.item_... | StateWidget | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateWidget:
def __init__(self, states):
"""Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the test case."""
<|body_0|>
def create_item(self, state=None):
"""Create a new state ... | stack_v2_sparse_classes_36k_train_012800 | 13,491 | permissive | [
{
"docstring": "Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the test case.",
"name": "__init__",
"signature": "def __init__(self, states)"
},
{
"docstring": "Create a new state item into the list. Parame... | 4 | stack_v2_sparse_classes_30k_val_000276 | Implement the Python class `StateWidget` described below.
Class description:
Implement the StateWidget class.
Method signatures and docstrings:
- def __init__(self, states): Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the tes... | Implement the Python class `StateWidget` described below.
Class description:
Implement the StateWidget class.
Method signatures and docstrings:
- def __init__(self, states): Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the tes... | 45c862669d8d4e72c95f6b278819379a1c1e68d4 | <|skeleton|>
class StateWidget:
def __init__(self, states):
"""Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the test case."""
<|body_0|>
def create_item(self, state=None):
"""Create a new state ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateWidget:
def __init__(self, states):
"""Create a list of state items and a plus button to add new states. Parameter ========= states: list The list of default states defined by the test case."""
self.states = states
self.default_state = self.states[0]
super().__init__(self.... | the_stack_v2_python_sparse | pylbm_ui/widgets/stability.py | gouarin/pylbm_ui | train | 0 | |
9695975bae2180f8cb6d9978e15886d5cee448dd | [
"show = ['{}) {}\\n'.format(n, i) for n, i in enumerate(inp)]\nshow = ''.join(show)\nshow = message + show\nprint(show)\nselection = int(input())\nresult = inp[selection]\nreturn result",
"book = xlrd.open_workbook(file_name)\nif book.nsheets > 1:\n selected_sheet = cls.list_choice_cli(book.sheet_names())\n ... | <|body_start_0|>
show = ['{}) {}\n'.format(n, i) for n, i in enumerate(inp)]
show = ''.join(show)
show = message + show
print(show)
selection = int(input())
result = inp[selection]
return result
<|end_body_0|>
<|body_start_1|>
book = xlrd.open_workbook(fi... | Command Line Interface Tools. | CLITools | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLITools:
"""Command Line Interface Tools."""
def list_choice_cli(inp, message='Choose from the following:\n'):
"""Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result : string"""
<|body_0|>
def read_excel_cli(c... | stack_v2_sparse_classes_36k_train_012801 | 2,522 | permissive | [
{
"docstring": "Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result : string",
"name": "list_choice_cli",
"signature": "def list_choice_cli(inp, message='Choose from the following:\\n')"
},
{
"docstring": "Return a DataFrame from the s... | 2 | stack_v2_sparse_classes_30k_train_001200 | Implement the Python class `CLITools` described below.
Class description:
Command Line Interface Tools.
Method signatures and docstrings:
- def list_choice_cli(inp, message='Choose from the following:\n'): Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result... | Implement the Python class `CLITools` described below.
Class description:
Command Line Interface Tools.
Method signatures and docstrings:
- def list_choice_cli(inp, message='Choose from the following:\n'): Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result... | bedb36eafe681401c11d562f8d7117aad3d758d7 | <|skeleton|>
class CLITools:
"""Command Line Interface Tools."""
def list_choice_cli(inp, message='Choose from the following:\n'):
"""Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result : string"""
<|body_0|>
def read_excel_cli(c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLITools:
"""Command Line Interface Tools."""
def list_choice_cli(inp, message='Choose from the following:\n'):
"""Return the users selection from a list. Parameters ---------- inp : list message : string Returns ------- result : string"""
show = ['{}) {}\n'.format(n, i) for n, i in enume... | the_stack_v2_python_sparse | omin/cli/utils.py | dmpio/omin | train | 0 |
de97932b394e3fda4fa7c784466d232c7704a599 | [
"super().__init__()\nself.n = layer_num\nself.linear = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])\nself.gate = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])\nself.relu = nn.ReLU()",
"for i in range(self.n):\n gate = F.sigmoid(self.gate[i](x))\n nonlinear = self.relu(self.l... | <|body_start_0|>
super().__init__()
self.n = layer_num
self.linear = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])
self.gate = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])
self.relu = nn.ReLU()
<|end_body_0|>
<|body_start_1|>
for i in ran... | Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>> print(y.size()) | Highway | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>>... | stack_v2_sparse_classes_36k_train_012802 | 38,467 | no_license | [
{
"docstring": ":param layer_num: number of highway transform layers :param size: size of the last dimension of input",
"name": "__init__",
"signature": "def __init__(self, layer_num, size)"
},
{
"docstring": ":Input: (N, *, size) * means any number of additional dimensions. :Output: (N, *, size... | 2 | stack_v2_sparse_classes_30k_train_017557 | Implement the Python class `Highway` described below.
Class description:
Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = to... | Implement the Python class `Highway` described below.
Class description:
Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = to... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>> print(y.size... | the_stack_v2_python_sparse | generated/test_BangLiu_QANet_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 |
70269cadb84db8f8ef8a2abeb63c03ad728f0d79 | [
"parser.add_argument('--variantset-id', type=str, required=True, help='The ID of the destination variant set.')\nparser.add_argument('--source-uris', type=arg_parsers.ArgList(min_length=1), required=True, help='A comma-delimited list of URI patterns referencing existing VCF or MasterVar files in Google Cloud Storag... | <|body_start_0|>
parser.add_argument('--variantset-id', type=str, required=True, help='The ID of the destination variant set.')
parser.add_argument('--source-uris', type=arg_parsers.ArgList(min_length=1), required=True, help='A comma-delimited list of URI patterns referencing existing VCF or MasterVar f... | Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage. | Import | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Import:
"""Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user r... | stack_v2_sparse_classes_36k_train_012803 | 5,489 | 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: an ImportVa... | 2 | stack_v2_sparse_classes_30k_train_002452 | Implement the Python class `Import` described below.
Class description:
Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets c... | Implement the Python class `Import` described below.
Class description:
Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets c... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class Import:
"""Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Import:
"""Imports variants into Google Genomics. Import variants from VCF or MasterVar files that are in Google Cloud Storage."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('--variantset-id', type=str, required=True, help='The ID of the destination varia... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/surface/genomics/variants/import.py | KaranToor/MA450 | train | 1 |
dac4788e378b440d069141a83a1f3bfbb19f9363 | [
"super().__init__()\nself.layers = nn.ModuleList()\nself.layers.append(rnn_cells.ConvGRUCell(in_channels, hidden_channels, conv_dim=2, kernel_size=3, dilation=1, bias=False))\nfor _ in range(n_convs):\n self.layers.append(conv_layers.ConvNonlinear(hidden_channels, hidden_channels, conv_dim=2, kernel_size=3, dila... | <|body_start_0|>
super().__init__()
self.layers = nn.ModuleList()
self.layers.append(rnn_cells.ConvGRUCell(in_channels, hidden_channels, conv_dim=2, kernel_size=3, dilation=1, bias=False))
for _ in range(n_convs):
self.layers.append(conv_layers.ConvNonlinear(hidden_channels, ... | Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic MR Image Reconstruction," in IEEE Transactions on Medical Imaging, vol. 38, n... | GRUConv2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUConv2d:
"""Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic MR Image Reconstruction," in IEEE Transa... | stack_v2_sparse_classes_36k_train_012804 | 3,131 | permissive | [
{
"docstring": "Inits Conv2d. Parameters ---------- in_channels: Number of input channels. int out_channels: Number of output channels. int hidden_channels: Number of hidden channels. int n_convs: Number of convolutional layers. int activation: Activation function. torch.nn.Module batchnorm: If True a batch nor... | 2 | null | Implement the Python class `GRUConv2d` described below.
Class description:
Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic M... | Implement the Python class `GRUConv2d` described below.
Class description:
Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic M... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class GRUConv2d:
"""Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic MR Image Reconstruction," in IEEE Transa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUConv2d:
"""Implementation of a GRU followed by a number of 2D convolutions inspired by [1]_. References ---------- .. [1] C. Qin, J. Schlemper, J. Caballero, A. N. Price, J. V. Hajnal and D. Rueckert, "Convolutional Recurrent Neural Networks for Dynamic MR Image Reconstruction," in IEEE Transactions on Med... | the_stack_v2_python_sparse | mridc/collections/reconstruction/models/conv/gruconv2d.py | wdika/mridc | train | 40 |
52a2535b1f6f1258409a3ae4590c1904a982814d | [
"if not n:\n return 1.0\nif n < 0:\n return 1 / self.myPow(x, -n)\nif n % 2:\n return x * self.myPow(x, n - 1)\nreturn self.myPow(x * x, n / 2)",
"if x == 0.0:\n return 0.0\nrst = 1\nif n < 0:\n x, n = (1 / x, -n)\nwhile n:\n if n & 1:\n rst *= x\n x *= x\n n >>= 1\nreturn rst"
] | <|body_start_0|>
if not n:
return 1.0
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n / 2)
<|end_body_0|>
<|body_start_1|>
if x == 0.0:
return 0.0
rst = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x: float, n: int) -> float:
"""思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2"""
<|body_0|>
def myPow_iter(self, x, n):
"""思路:利用迭代优化空间复杂度 位运算: - 边界条件 x<=0, n =0 - n < 0 时跳出循环 - 当 x 为奇数时 乘以 ... | stack_v2_sparse_classes_36k_train_012805 | 1,553 | no_license | [
{
"docstring": "思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2",
"name": "myPow",
"signature": "def myPow(self, x: float, n: int) -> float"
},
{
"docstring": "思路:利用迭代优化空间复杂度 位运算: - 边界条件 x<=0, n =0 - n < 0 时跳出循环 - 当 x 为奇数时 乘以 x= rst*x, n-1, 位运算 ... | 2 | stack_v2_sparse_classes_30k_train_010840 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x: float, n: int) -> float: 思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2
- def myPow_iter(self, x, n): 思路:利用... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x: float, n: int) -> float: 思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2
- def myPow_iter(self, x, n): 思路:利用... | 4994b8b19abcdbcc0bda2944350e325242fadfd1 | <|skeleton|>
class Solution:
def myPow(self, x: float, n: int) -> float:
"""思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2"""
<|body_0|>
def myPow_iter(self, x, n):
"""思路:利用迭代优化空间复杂度 位运算: - 边界条件 x<=0, n =0 - n < 0 时跳出循环 - 当 x 为奇数时 乘以 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow(self, x: float, n: int) -> float:
"""思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2"""
if not n:
return 1.0
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2:
return x * se... | the_stack_v2_python_sparse | Week_03/myPow.py | NanZhang715/AlgorithmCHUNZHAO | train | 0 | |
2b8a21124a357217d1f3f1183ce4c836f4cb657c | [
"try:\n stream.write(json.dumps(data, indent=2))\nexcept Exception as e:\n raise SerDeError('JSON dump error') from e",
"try:\n return json.load(stream)\nexcept Exception as e:\n raise SerDeError('JSON load error') from e"
] | <|body_start_0|>
try:
stream.write(json.dumps(data, indent=2))
except Exception as e:
raise SerDeError('JSON dump error') from e
<|end_body_0|>
<|body_start_1|>
try:
return json.load(stream)
except Exception as e:
raise SerDeError('JSON lo... | A Json Serializer/deserializer. | JsonSerDe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonSerDe:
"""A Json Serializer/deserializer."""
def serialize_to_stream(self, data: Any, stream: TextIO) -> None:
"""Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an error occurred during writing or serialization"""
<|b... | stack_v2_sparse_classes_36k_train_012806 | 1,197 | no_license | [
{
"docstring": "Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an error occurred during writing or serialization",
"name": "serialize_to_stream",
"signature": "def serialize_to_stream(self, data: Any, stream: TextIO) -> None"
},
{
"docstring... | 2 | null | Implement the Python class `JsonSerDe` described below.
Class description:
A Json Serializer/deserializer.
Method signatures and docstrings:
- def serialize_to_stream(self, data: Any, stream: TextIO) -> None: Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an erro... | Implement the Python class `JsonSerDe` described below.
Class description:
A Json Serializer/deserializer.
Method signatures and docstrings:
- def serialize_to_stream(self, data: Any, stream: TextIO) -> None: Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an erro... | 3da2161c3c9e0652c2cfc78ab514359bcf2e436b | <|skeleton|>
class JsonSerDe:
"""A Json Serializer/deserializer."""
def serialize_to_stream(self, data: Any, stream: TextIO) -> None:
"""Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an error occurred during writing or serialization"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonSerDe:
"""A Json Serializer/deserializer."""
def serialize_to_stream(self, data: Any, stream: TextIO) -> None:
"""Write serialized data as Json into a stream. Args: data: data stream: a stream Raises: SerDeError: if an error occurred during writing or serialization"""
try:
... | the_stack_v2_python_sparse | ywh2bt/core/serializers/json.py | yeswehack/ywh2bugtracker | train | 10 |
3431a82db2f3101739038a4e92529a1b825a25ca | [
"connection_created.connect(self.activate_pragmas_per_connection)\nself.activate_pragmas_on_start()\nlogger.info('Running Kolibri with the following settings: {settings}'.format(settings=os.environ['DJANGO_SETTINGS_MODULE']))\nself.check_redis_settings()\nfrom morango.models import UUIDField\nFilterSet.FILTER_DEFAU... | <|body_start_0|>
connection_created.connect(self.activate_pragmas_per_connection)
self.activate_pragmas_on_start()
logger.info('Running Kolibri with the following settings: {settings}'.format(settings=os.environ['DJANGO_SETTINGS_MODULE']))
self.check_redis_settings()
from morango... | KolibriCoreConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KolibriCoreConfig:
def ready(self):
"""Sets up PRAGMAs."""
<|body_0|>
def activate_pragmas_per_connection(sender, connection, **kwargs):
"""Activate SQLite3 PRAGMAs that apply on a per-connection basis. A no-op right now, but kept around as infrastructure if we ever ... | stack_v2_sparse_classes_36k_train_012807 | 7,006 | permissive | [
{
"docstring": "Sets up PRAGMAs.",
"name": "ready",
"signature": "def ready(self)"
},
{
"docstring": "Activate SQLite3 PRAGMAs that apply on a per-connection basis. A no-op right now, but kept around as infrastructure if we ever want to add PRAGMAs in the future.",
"name": "activate_pragmas_... | 4 | stack_v2_sparse_classes_30k_train_002227 | Implement the Python class `KolibriCoreConfig` described below.
Class description:
Implement the KolibriCoreConfig class.
Method signatures and docstrings:
- def ready(self): Sets up PRAGMAs.
- def activate_pragmas_per_connection(sender, connection, **kwargs): Activate SQLite3 PRAGMAs that apply on a per-connection b... | Implement the Python class `KolibriCoreConfig` described below.
Class description:
Implement the KolibriCoreConfig class.
Method signatures and docstrings:
- def ready(self): Sets up PRAGMAs.
- def activate_pragmas_per_connection(sender, connection, **kwargs): Activate SQLite3 PRAGMAs that apply on a per-connection b... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class KolibriCoreConfig:
def ready(self):
"""Sets up PRAGMAs."""
<|body_0|>
def activate_pragmas_per_connection(sender, connection, **kwargs):
"""Activate SQLite3 PRAGMAs that apply on a per-connection basis. A no-op right now, but kept around as infrastructure if we ever ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KolibriCoreConfig:
def ready(self):
"""Sets up PRAGMAs."""
connection_created.connect(self.activate_pragmas_per_connection)
self.activate_pragmas_on_start()
logger.info('Running Kolibri with the following settings: {settings}'.format(settings=os.environ['DJANGO_SETTINGS_MODULE'... | the_stack_v2_python_sparse | kolibri/core/apps.py | learningequality/kolibri | train | 689 | |
474e4dabbd2ade85f1a861cf7352dc5e4f04ce6c | [
"n = len(nums)\n\n@lru_cache(None)\ndef helper(i):\n \"\"\"True if we can arrive last when we start at i\"\"\"\n if i == n - 1:\n return True\n if i < 0 or i >= n:\n return False\n for j in range(1, nums[i] + 1):\n if helper(i + j):\n return True\n return False\nreturn... | <|body_start_0|>
n = len(nums)
@lru_cache(None)
def helper(i):
"""True if we can arrive last when we start at i"""
if i == n - 1:
return True
if i < 0 or i >= n:
return False
for j in range(1, nums[i] + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE"""
<|body_0|>
def canJump(self, nums: List[int]) -> bool:
"""Down-Top DP, Time: O(n^2), Space: O(n), TLE"""
<|body_1|>
def canJump(self, nu... | stack_v2_sparse_classes_36k_train_012808 | 1,569 | no_license | [
{
"docstring": "Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE",
"name": "canJump",
"signature": "def canJump(self, nums: List[int]) -> bool"
},
{
"docstring": "Down-Top DP, Time: O(n^2), Space: O(n), TLE",
"name": "canJump",
"signature": "def canJump(self, nums: List[int]) ->... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE
- def canJump(self, nums: List[int]) -> bool: Down-Top DP, Time: O(n^2), Spa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE
- def canJump(self, nums: List[int]) -> bool: Down-Top DP, Time: O(n^2), Spa... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE"""
<|body_0|>
def canJump(self, nums: List[int]) -> bool:
"""Down-Top DP, Time: O(n^2), Space: O(n), TLE"""
<|body_1|>
def canJump(self, nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums: List[int]) -> bool:
"""Top-Down with Memoization, Time: O(n^2), Space: O(n), TLE"""
n = len(nums)
@lru_cache(None)
def helper(i):
"""True if we can arrive last when we start at i"""
if i == n - 1:
return... | the_stack_v2_python_sparse | python/55-Jump Game.py | cwza/leetcode | train | 0 | |
e40ff04e83b425bb0e4116a2b3307c82727f2117 | [
"super(TransformerDecoder, self).__init__()\nself._hidden_size = opts.hidden_size\nself._output_size = opts.embedding_dim\nself.layers = nn.ModuleList([TransformerDecoderLayer(opts, size=opts.hidden_size, ff_size=opts.ff_size, num_heads=opts.num_heads, dropout=opts.dropout) for _ in range(opts.num_layers)])\nself.p... | <|body_start_0|>
super(TransformerDecoder, self).__init__()
self._hidden_size = opts.hidden_size
self._output_size = opts.embedding_dim
self.layers = nn.ModuleList([TransformerDecoderLayer(opts, size=opts.hidden_size, ff_size=opts.ff_size, num_heads=opts.num_heads, dropout=opts.dropout) ... | A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future. | TransformerDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoder:
"""A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future."""
def __init__(self, opts, freeze: bool=False, **kwargs):
"""Initialize a Transformer decoder. :param num_layers: number of Transformer layer... | stack_v2_sparse_classes_36k_train_012809 | 4,320 | no_license | [
{
"docstring": "Initialize a Transformer decoder. :param num_layers: number of Transformer layers :param num_heads: number of heads for each layer :param hidden_size: hidden size :param ff_size: position-wise feed-forward size :param dropout: dropout probability (1-keep) :param emb_dropout: dropout probability ... | 2 | stack_v2_sparse_classes_30k_train_008128 | Implement the Python class `TransformerDecoder` described below.
Class description:
A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future.
Method signatures and docstrings:
- def __init__(self, opts, freeze: bool=False, **kwargs): Initialize a Transforme... | Implement the Python class `TransformerDecoder` described below.
Class description:
A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future.
Method signatures and docstrings:
- def __init__(self, opts, freeze: bool=False, **kwargs): Initialize a Transforme... | e213665be8d3820fa2fc0aa9afe9949fd2e3d488 | <|skeleton|>
class TransformerDecoder:
"""A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future."""
def __init__(self, opts, freeze: bool=False, **kwargs):
"""Initialize a Transformer decoder. :param num_layers: number of Transformer layer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDecoder:
"""A transformer decoder with N masked layers. Decoder layers are masked so that an attention head cannot see the future."""
def __init__(self, opts, freeze: bool=False, **kwargs):
"""Initialize a Transformer decoder. :param num_layers: number of Transformer layers :param num_... | the_stack_v2_python_sparse | modules/transformer_decoder.py | zqp111/transformer_ar | train | 1 |
f68951a622bd8da57112afacba69267399f69997 | [
"ans = list()\nwhile integer > 0:\n integer, reminder = divmod(integer, base_x)\n ans.append(reminder)\nans = list(reversed(ans))\nans = list(map(lambda x: BaseXConverter.DICT[x], ans))\nans = ''.join(ans)\nreturn ans",
"l = list(reversed(list(map(lambda x: BaseXConverter.DICT.index(x), string))))\nans = 0\... | <|body_start_0|>
ans = list()
while integer > 0:
integer, reminder = divmod(integer, base_x)
ans.append(reminder)
ans = list(reversed(ans))
ans = list(map(lambda x: BaseXConverter.DICT[x], ans))
ans = ''.join(ans)
return ans
<|end_body_0|>
<|body_... | BaseXConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseXConverter:
def encode(integer, base_x=62):
"""convert base 10 integer to base x string :integer: base 10 integer :returns: base x string"""
<|body_0|>
def decode(string, base_x=62):
"""@todo: Docstring for decode. :string: base x string :returns: base 10 integer... | stack_v2_sparse_classes_36k_train_012810 | 2,058 | no_license | [
{
"docstring": "convert base 10 integer to base x string :integer: base 10 integer :returns: base x string",
"name": "encode",
"signature": "def encode(integer, base_x=62)"
},
{
"docstring": "@todo: Docstring for decode. :string: base x string :returns: base 10 integer",
"name": "decode",
... | 2 | stack_v2_sparse_classes_30k_train_019865 | Implement the Python class `BaseXConverter` described below.
Class description:
Implement the BaseXConverter class.
Method signatures and docstrings:
- def encode(integer, base_x=62): convert base 10 integer to base x string :integer: base 10 integer :returns: base x string
- def decode(string, base_x=62): @todo: Doc... | Implement the Python class `BaseXConverter` described below.
Class description:
Implement the BaseXConverter class.
Method signatures and docstrings:
- def encode(integer, base_x=62): convert base 10 integer to base x string :integer: base 10 integer :returns: base x string
- def decode(string, base_x=62): @todo: Doc... | 9f6595340bc8e915ffcd18e4c26c8367386c87e9 | <|skeleton|>
class BaseXConverter:
def encode(integer, base_x=62):
"""convert base 10 integer to base x string :integer: base 10 integer :returns: base x string"""
<|body_0|>
def decode(string, base_x=62):
"""@todo: Docstring for decode. :string: base x string :returns: base 10 integer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseXConverter:
def encode(integer, base_x=62):
"""convert base 10 integer to base x string :integer: base 10 integer :returns: base x string"""
ans = list()
while integer > 0:
integer, reminder = divmod(integer, base_x)
ans.append(reminder)
ans = list(r... | the_stack_v2_python_sparse | python/base_x_converter/base_x_converter.py | richard-ma/playground | train | 0 | |
9c0c3b64e469c154e4385b71e27e8bd3a22eebf6 | [
"ret = {}\nsds = self.db.Status\nquery = {'component': component}\nlogging.debug(f'MONGO-START: db.Status.find(filter={query}, projection={REMOVE_ID})')\nasync for row in sds.find(filter=query, projection=REMOVE_ID):\n name = row['name']\n del row['component']\n del row['name']\n update_dict = {name: ro... | <|body_start_0|>
ret = {}
sds = self.db.Status
query = {'component': component}
logging.debug(f'MONGO-START: db.Status.find(filter={query}, projection={REMOVE_ID})')
async for row in sds.find(filter=query, projection=REMOVE_ID):
name = row['name']
del row[... | StatusComponentHandler is a BaseLTAHandler that handles component status routes. | StatusComponentHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusComponentHandler:
"""StatusComponentHandler is a BaseLTAHandler that handles component status routes."""
async def get(self, component: str) -> None:
"""Get the detailed status of components of a given type. This handles the route: GET /status/{component-type} In MongoDB, we st... | stack_v2_sparse_classes_36k_train_012811 | 42,572 | permissive | [
{
"docstring": "Get the detailed status of components of a given type. This handles the route: GET /status/{component-type} In MongoDB, we store the status records like this: { \"component\": \"picker\" \"name\": \"picker-node001\" keys: values } But the response to GET /status/picker should be like this: { \"p... | 2 | stack_v2_sparse_classes_30k_val_000172 | Implement the Python class `StatusComponentHandler` described below.
Class description:
StatusComponentHandler is a BaseLTAHandler that handles component status routes.
Method signatures and docstrings:
- async def get(self, component: str) -> None: Get the detailed status of components of a given type. This handles ... | Implement the Python class `StatusComponentHandler` described below.
Class description:
StatusComponentHandler is a BaseLTAHandler that handles component status routes.
Method signatures and docstrings:
- async def get(self, component: str) -> None: Get the detailed status of components of a given type. This handles ... | 12719efa84be2281debe98a18c69bbe7a6d0f399 | <|skeleton|>
class StatusComponentHandler:
"""StatusComponentHandler is a BaseLTAHandler that handles component status routes."""
async def get(self, component: str) -> None:
"""Get the detailed status of components of a given type. This handles the route: GET /status/{component-type} In MongoDB, we st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatusComponentHandler:
"""StatusComponentHandler is a BaseLTAHandler that handles component status routes."""
async def get(self, component: str) -> None:
"""Get the detailed status of components of a given type. This handles the route: GET /status/{component-type} In MongoDB, we store the statu... | the_stack_v2_python_sparse | lta/rest_server.py | blinkdog/lta | train | 0 |
6f71c2deab88200bf7b2d0aeb8a492d90b8fb51b | [
"self.baseurl = baseurl\nself.key = key\nself.safety = safety",
"if not self.safety:\n return params\nparams = {} if params is None else params\nreturn token.generate(params, self.key)",
"url = self.baseurl + path\nparams = self._token(params)\nresp = requests.get(url, params=params, **kwargs).json()\nif res... | <|body_start_0|>
self.baseurl = baseurl
self.key = key
self.safety = safety
<|end_body_0|>
<|body_start_1|>
if not self.safety:
return params
params = {} if params is None else params
return token.generate(params, self.key)
<|end_body_1|>
<|body_start_2|>
... | remote rpc base class | Rpc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rpc:
"""remote rpc base class"""
def __init__(self, baseurl: str, key: str, safety: bool):
"""init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param safety: bool, enable safety key verification with True"""
... | stack_v2_sparse_classes_36k_train_012812 | 12,542 | no_license | [
{
"docstring": "init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param safety: bool, enable safety key verification with True",
"name": "__init__",
"signature": "def __init__(self, baseurl: str, key: str, safety: bool)"
},
{... | 4 | null | Implement the Python class `Rpc` described below.
Class description:
remote rpc base class
Method signatures and docstrings:
- def __init__(self, baseurl: str, key: str, safety: bool): init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param sa... | Implement the Python class `Rpc` described below.
Class description:
remote rpc base class
Method signatures and docstrings:
- def __init__(self, baseurl: str, key: str, safety: bool): init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param sa... | 1adf3df582bd07f748181faf29d7795cc14f07ea | <|skeleton|>
class Rpc:
"""remote rpc base class"""
def __init__(self, baseurl: str, key: str, safety: bool):
"""init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param safety: bool, enable safety key verification with True"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rpc:
"""remote rpc base class"""
def __init__(self, baseurl: str, key: str, safety: bool):
"""init rpc :param baseurl: str, base url for remote http service :param key: str, private key for safety verification or None :param safety: bool, enable safety key verification with True"""
self.b... | the_stack_v2_python_sparse | app/svc/app/atm/remote/tms.py | soldiers1989/trade-1 | train | 0 |
96db47a667161ad1c4651637aec0fea3238c2d73 | [
"if not remote_user:\n return\nusername = self.clean_username(remote_user)\nif self.create_unknown_user:\n user, created = User.objects.get_or_create(username=username)\n if created:\n user = self.configure_user(user)\nelse:\n try:\n user = User.objects.get(user)\n except User.DoesNotEx... | <|body_start_0|>
if not remote_user:
return
username = self.clean_username(remote_user)
if self.create_unknown_user:
user, created = User.objects.get_or_create(username=username)
if created:
user = self.configure_user(user)
else:
... | WindowsIntegratedAuthenticationBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsIntegratedAuthenticationBackend:
def authenticate(self, remote_user):
"""The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Ret... | stack_v2_sparse_classes_36k_train_012813 | 7,564 | permissive | [
{
"docstring": "The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given u... | 3 | null | Implement the Python class `WindowsIntegratedAuthenticationBackend` described below.
Class description:
Implement the WindowsIntegratedAuthenticationBackend class.
Method signatures and docstrings:
- def authenticate(self, remote_user): The username passed as ``remote_user`` is considered trusted. This method simply ... | Implement the Python class `WindowsIntegratedAuthenticationBackend` described below.
Class description:
Implement the WindowsIntegratedAuthenticationBackend class.
Method signatures and docstrings:
- def authenticate(self, remote_user): The username passed as ``remote_user`` is considered trusted. This method simply ... | ba11d39a07382b11394aaffd0df692b4ddc6239b | <|skeleton|>
class WindowsIntegratedAuthenticationBackend:
def authenticate(self, remote_user):
"""The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsIntegratedAuthenticationBackend:
def authenticate(self, remote_user):
"""The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if `... | the_stack_v2_python_sparse | qatrack/accounts/backends.py | randlet/qatrackplus-ci | train | 4 | |
bc4a7c860872fc7080cc1d2e28bc77f932e18acb | [
"homedir = os.environ.get('HOME', None)\nif homedir is None:\n print('ERROR: Home ENV is not set')\n return\nself.__orca_config = os.path.join(homedir, '.aws/orcaenv.yaml')\ntry:\n fp = open(self.__orca_config)\nexcept IOError as ioerr:\n print('ERROR: Failed to open [%s] [%s]' % (self.__orca_config, io... | <|body_start_0|>
homedir = os.environ.get('HOME', None)
if homedir is None:
print('ERROR: Home ENV is not set')
return
self.__orca_config = os.path.join(homedir, '.aws/orcaenv.yaml')
try:
fp = open(self.__orca_config)
except IOError as ioerr:
... | The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml). | OrcaConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrcaConfig:
"""The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml)."""
def __init__(self):
"""Initialize."""
<|body_0|>
def get_regions(self):
"""Return the region list ... | stack_v2_sparse_classes_36k_train_012814 | 3,402 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return the region list from the orcaenv config file",
"name": "get_regions",
"signature": "def get_regions(self)"
},
{
"docstring": "Return the tag list from the orcaenv config ... | 4 | stack_v2_sparse_classes_30k_train_010922 | Implement the Python class `OrcaConfig` described below.
Class description:
The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml).
Method signatures and docstrings:
- def __init__(self): Initialize.
- def get_regions(self): Re... | Implement the Python class `OrcaConfig` described below.
Class description:
The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml).
Method signatures and docstrings:
- def __init__(self): Initialize.
- def get_regions(self): Re... | c74662c963542eb52b4d88ede9c6ff5b21ce3016 | <|skeleton|>
class OrcaConfig:
"""The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml)."""
def __init__(self):
"""Initialize."""
<|body_0|>
def get_regions(self):
"""Return the region list ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrcaConfig:
"""The class reads/manages the orcaenv.yaml file. Ideally the file should be located in the same place as your aws config file (~/.aws/orcaenv.yaml)."""
def __init__(self):
"""Initialize."""
homedir = os.environ.get('HOME', None)
if homedir is None:
print('... | the_stack_v2_python_sparse | orcalib/aws_config.py | bdastur/orca | train | 3 |
a38edfb4d11a8be7b8b782cd0d8b2d74dcbd878a | [
"try:\n book = BookInfo.objects.get(pk=pk)\nexcept:\n return Http404('数据不存在')\nbook_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}\nreturn JsonResponse(book_dict)",
"param_dict = json.loads(request.body.decode())\nbtitle = param_dict.get('btitle')\nbpub_date = param_dict.get('bpu... | <|body_start_0|>
try:
book = BookInfo.objects.get(pk=pk)
except:
return Http404('数据不存在')
book_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}
return JsonResponse(book_dict)
<|end_body_0|>
<|body_start_1|>
param_dict = json.loads... | BookView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
<|body_0|>
def put(self, request, pk):
"""修改指定主键的对象"""
<|body_1|>
def delete(self, request, pk):
"""删除指定主键的对象"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_012815 | 3,452 | permissive | [
{
"docstring": "根据主键查询一个对象",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "修改指定主键的对象",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "删除指定主键的对象",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
... | 3 | stack_v2_sparse_classes_30k_train_016922 | Implement the Python class `BookView` described below.
Class description:
Implement the BookView class.
Method signatures and docstrings:
- def get(self, request, pk): 根据主键查询一个对象
- def put(self, request, pk): 修改指定主键的对象
- def delete(self, request, pk): 删除指定主键的对象 | Implement the Python class `BookView` described below.
Class description:
Implement the BookView class.
Method signatures and docstrings:
- def get(self, request, pk): 根据主键查询一个对象
- def put(self, request, pk): 修改指定主键的对象
- def delete(self, request, pk): 删除指定主键的对象
<|skeleton|>
class BookView:
def get(self, request... | 63ae6891d3be243c5c46329e65fcf47133c5890f | <|skeleton|>
class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
<|body_0|>
def put(self, request, pk):
"""修改指定主键的对象"""
<|body_1|>
def delete(self, request, pk):
"""删除指定主键的对象"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookView:
def get(self, request, pk):
"""根据主键查询一个对象"""
try:
book = BookInfo.objects.get(pk=pk)
except:
return Http404('数据不存在')
book_dict = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date}
return JsonResponse(book_dict)
def... | the_stack_v2_python_sparse | pro_drf/demo1/booktest/views.py | yongfang117/pro_useful_code | train | 0 | |
599471fca4ccb4ca24191a09dc5ffa6db27b94f2 | [
"super().__init__(validate)\nself._discriminator = discriminators\nself._n_circs = 0\nself._n_shots = 0\nself._n_slots = 0\nself._n_iq = 0",
"self._n_shots = 0\ntry:\n self._n_circs, self._n_shots, self._n_slots, self._n_iq = data.shape\nexcept ValueError as ex:\n raise DataProcessorError(f'The data given t... | <|body_start_0|>
super().__init__(validate)
self._discriminator = discriminators
self._n_circs = 0
self._n_shots = 0
self._n_slots = 0
self._n_iq = 0
<|end_body_0|>
<|body_start_1|>
self._n_shots = 0
try:
self._n_circs, self._n_shots, self._n_... | A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list of lists and returns a list of labels. Crucial... | DiscriminatorNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list o... | stack_v2_sparse_classes_36k_train_012816 | 42,185 | permissive | [
{
"docstring": "Initialize the node with an object that can discriminate. Args: discriminators: The entity that will perform the discrimination. This needs to be a :class:`.BaseDiscriminator` or a list thereof that takes as input a list of lists and returns a list of labels. If a list of discriminators is given... | 3 | stack_v2_sparse_classes_30k_train_007120 | Implement the Python class `DiscriminatorNode` described below.
Class description:
A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predi... | Implement the Python class `DiscriminatorNode` described below.
Class description:
A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predi... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscriminatorNode:
"""A class to discriminate kerneled data, e.g., IQ data, to produce counts. This node integrates into the data processing chain a serializable :class:`.BaseDiscriminator` subclass instance which must have a :meth:`~.BaseDiscriminator.predict` method that takes as input a list of lists and r... | the_stack_v2_python_sparse | qiskit_experiments/data_processing/nodes.py | oliverdial/qiskit-experiments | train | 0 |
e97eb67e6c1ea5928ed34600ace5d480f2e25a1b | [
"if 'email' not in recover_request:\n raise ValidationError('Missing email!')\nif re.match('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$)', recover_request['email']) is None:\n raise ValidationError('Invalid email format provided!')",
"recover_request = json.loads(request.body.decode('utf-8'))\nAuth... | <|body_start_0|>
if 'email' not in recover_request:
raise ValidationError('Missing email!')
if re.match('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)', recover_request['email']) is None:
raise ValidationError('Invalid email format provided!')
<|end_body_0|>
<|body_start_1... | Reset password endpoint and validator | AuthRecoverView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthRecoverView:
"""Reset password endpoint and validator"""
def validate_recover_request(recover_request):
"""Validates the recover password information received in the request body :param recover_request: Recover password information received in the request"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_012817 | 2,018 | no_license | [
{
"docstring": "Validates the recover password information received in the request body :param recover_request: Recover password information received in the request",
"name": "validate_recover_request",
"signature": "def validate_recover_request(recover_request)"
},
{
"docstring": "Action when c... | 2 | null | Implement the Python class `AuthRecoverView` described below.
Class description:
Reset password endpoint and validator
Method signatures and docstrings:
- def validate_recover_request(recover_request): Validates the recover password information received in the request body :param recover_request: Recover password inf... | Implement the Python class `AuthRecoverView` described below.
Class description:
Reset password endpoint and validator
Method signatures and docstrings:
- def validate_recover_request(recover_request): Validates the recover password information received in the request body :param recover_request: Recover password inf... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class AuthRecoverView:
"""Reset password endpoint and validator"""
def validate_recover_request(recover_request):
"""Validates the recover password information received in the request body :param recover_request: Recover password information received in the request"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthRecoverView:
"""Reset password endpoint and validator"""
def validate_recover_request(recover_request):
"""Validates the recover password information received in the request body :param recover_request: Recover password information received in the request"""
if 'email' not in recover_... | the_stack_v2_python_sparse | backend/martin_helder/views/auth_recover_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
6dbbb0165a3e7b4a8f5c1900e13b0dda93327c4f | [
"super(Group_RDB, self).__init__()\nself.InChan = InChannel\nself.OutChan = OutChannel\nself.G = growRate\nself.C = nConvLayers\nif self.InChan != self.G:\n self.InConv = ops.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)\nif self.OutChan != self.G and self.OutChan != self.InChan:\n self.OutConv = ops.Co... | <|body_start_0|>
super(Group_RDB, self).__init__()
self.InChan = InChannel
self.OutChan = OutChannel
self.G = growRate
self.C = nConvLayers
if self.InChan != self.G:
self.InConv = ops.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)
if self.OutChan ... | Group residual dense block. | Group_RDB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group_RDB:
"""Group residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRat... | stack_v2_sparse_classes_36k_train_012818 | 14,306 | permissive | [
{
"docstring": "Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rate of block :type growRate: int :param nConvLayers: the number of convlution layer :type nConvLayers: int :param kSize: ker... | 2 | null | Implement the Python class `Group_RDB` described below.
Class description:
Group residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: chan... | Implement the Python class `Group_RDB` described below.
Class description:
Group residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: chan... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Group_RDB:
"""Group residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Group_RDB:
"""Group residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rat... | the_stack_v2_python_sparse | zeus/networks/erdb_esr.py | huawei-noah/xingtian | train | 308 |
3d6a200e21cb9bef71325024b4fdf607625153e3 | [
"attendance_students = self.get_queryset().filter(attendance=attendance)\nattendance_students_list_data = []\nif attendance_students.exists():\n for attendance_student in attendance_students:\n attendance_students_data = {'id': attendance_student.student.id, 'name': attendance_student.student.user.full_na... | <|body_start_0|>
attendance_students = self.get_queryset().filter(attendance=attendance)
attendance_students_list_data = []
if attendance_students.exists():
for attendance_student in attendance_students:
attendance_students_data = {'id': attendance_student.student.id,... | Override the attendance manager. | AttendanceReportManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttendanceReportManager:
"""Override the attendance manager."""
def get_attendance_students_list_data(self, attendance):
"""Take attendance object. Get list of students' attendance of this attendance object."""
<|body_0|>
def get_attendance_reports_list_data(self, attend... | stack_v2_sparse_classes_36k_train_012819 | 4,035 | no_license | [
{
"docstring": "Take attendance object. Get list of students' attendance of this attendance object.",
"name": "get_attendance_students_list_data",
"signature": "def get_attendance_students_list_data(self, attendance)"
},
{
"docstring": "Take student and attendance object. Get list of students' a... | 2 | stack_v2_sparse_classes_30k_train_000297 | Implement the Python class `AttendanceReportManager` described below.
Class description:
Override the attendance manager.
Method signatures and docstrings:
- def get_attendance_students_list_data(self, attendance): Take attendance object. Get list of students' attendance of this attendance object.
- def get_attendanc... | Implement the Python class `AttendanceReportManager` described below.
Class description:
Override the attendance manager.
Method signatures and docstrings:
- def get_attendance_students_list_data(self, attendance): Take attendance object. Get list of students' attendance of this attendance object.
- def get_attendanc... | 2c53f81a55fe631406b642365a68de19501c0f17 | <|skeleton|>
class AttendanceReportManager:
"""Override the attendance manager."""
def get_attendance_students_list_data(self, attendance):
"""Take attendance object. Get list of students' attendance of this attendance object."""
<|body_0|>
def get_attendance_reports_list_data(self, attend... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttendanceReportManager:
"""Override the attendance manager."""
def get_attendance_students_list_data(self, attendance):
"""Take attendance object. Get list of students' attendance of this attendance object."""
attendance_students = self.get_queryset().filter(attendance=attendance)
... | the_stack_v2_python_sparse | attendance/models.py | OmarFateh/student-management-system | train | 0 |
a8fc39d4c595b3829992f6ee4fbab9648b01373c | [
"if os.path.isfile(Config.CR_CONFIG_FULL_PATH):\n log.log_debug('Configuration file: Found. Reading it.')\n self.read_config_file()\nelse:\n log.log_info('Configuration file: Not found. Creating it.')\n self.write_config_file()",
"log.log_debug('Reading the config file...')\nConfig.config.read(Config.... | <|body_start_0|>
if os.path.isfile(Config.CR_CONFIG_FULL_PATH):
log.log_debug('Configuration file: Found. Reading it.')
self.read_config_file()
else:
log.log_info('Configuration file: Not found. Creating it.')
self.write_config_file()
<|end_body_0|>
<|bod... | Manages CentralReport configuration. | Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Manages CentralReport configuration."""
def __init__(self):
"""Constructor"""
<|body_0|>
def read_config_file(self):
"""Reads the configuration file."""
<|body_1|>
def write_config_file(self):
"""Writes the actual configuration int... | stack_v2_sparse_classes_36k_train_012820 | 6,426 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Reads the configuration file.",
"name": "read_config_file",
"signature": "def read_config_file(self)"
},
{
"docstring": "Writes the actual configuration into the config file.",
... | 5 | stack_v2_sparse_classes_30k_train_002246 | Implement the Python class `Config` described below.
Class description:
Manages CentralReport configuration.
Method signatures and docstrings:
- def __init__(self): Constructor
- def read_config_file(self): Reads the configuration file.
- def write_config_file(self): Writes the actual configuration into the config fi... | Implement the Python class `Config` described below.
Class description:
Manages CentralReport configuration.
Method signatures and docstrings:
- def __init__(self): Constructor
- def read_config_file(self): Reads the configuration file.
- def write_config_file(self): Writes the actual configuration into the config fi... | 421447f31d07321f65198c5b5746baa16c9d9725 | <|skeleton|>
class Config:
"""Manages CentralReport configuration."""
def __init__(self):
"""Constructor"""
<|body_0|>
def read_config_file(self):
"""Reads the configuration file."""
<|body_1|>
def write_config_file(self):
"""Writes the actual configuration int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Manages CentralReport configuration."""
def __init__(self):
"""Constructor"""
if os.path.isfile(Config.CR_CONFIG_FULL_PATH):
log.log_debug('Configuration file: Found. Reading it.')
self.read_config_file()
else:
log.log_info('Configura... | the_stack_v2_python_sparse | centralreport/cr/tools.py | haiyangd/CentralReport | train | 0 |
e4e0075fd82a9e6b5e0310956b9b5406ba7681b5 | [
"del mock_cloud_build, mock_google_auth\nmock_upload_log.return_value = True\nbuilds = [{'build_id': '1', 'finishTime': 'test_time', 'status': 'SUCCESS'}]\nmock_get_build = MockGetBuild(builds)\nupdate_build_status.BuildGetter.get_build = mock_get_build.get_build\nexpected_projects = {'history': [{'build_id': '1', ... | <|body_start_0|>
del mock_cloud_build, mock_google_auth
mock_upload_log.return_value = True
builds = [{'build_id': '1', 'finishTime': 'test_time', 'status': 'SUCCESS'}]
mock_get_build = MockGetBuild(builds)
update_build_status.BuildGetter.get_build = mock_get_build.get_build
... | Unit tests for get_build_history. | TestGetBuildHistory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetBuildHistory:
"""Unit tests for get_build_history."""
def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth):
"""Test for get_build_steps."""
<|body_0|>
def test_get_build_history_no_last_success(self, mock_upload_log, mock_cloud_bui... | stack_v2_sparse_classes_36k_train_012821 | 10,717 | permissive | [
{
"docstring": "Test for get_build_steps.",
"name": "test_get_build_history",
"signature": "def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth)"
},
{
"docstring": "Test when there is no last successful build.",
"name": "test_get_build_history_no_last_success... | 2 | stack_v2_sparse_classes_30k_train_019206 | Implement the Python class `TestGetBuildHistory` described below.
Class description:
Unit tests for get_build_history.
Method signatures and docstrings:
- def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth): Test for get_build_steps.
- def test_get_build_history_no_last_success(self,... | Implement the Python class `TestGetBuildHistory` described below.
Class description:
Unit tests for get_build_history.
Method signatures and docstrings:
- def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth): Test for get_build_steps.
- def test_get_build_history_no_last_success(self,... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class TestGetBuildHistory:
"""Unit tests for get_build_history."""
def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth):
"""Test for get_build_steps."""
<|body_0|>
def test_get_build_history_no_last_success(self, mock_upload_log, mock_cloud_bui... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetBuildHistory:
"""Unit tests for get_build_history."""
def test_get_build_history(self, mock_upload_log, mock_cloud_build, mock_google_auth):
"""Test for get_build_steps."""
del mock_cloud_build, mock_google_auth
mock_upload_log.return_value = True
builds = [{'build_... | the_stack_v2_python_sparse | infra/build/build_status/update_build_status_test.py | google/oss-fuzz | train | 9,438 |
a35d3a41f2dea035a4a0fcf14d787b82de5a6eae | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuditEvent()",
"from .audit_actor import AuditActor\nfrom .audit_resource import AuditResource\nfrom .entity import Entity\nfrom .audit_actor import AuditActor\nfrom .audit_resource import AuditResource\nfrom .entity import Entity\nfie... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AuditEvent()
<|end_body_0|>
<|body_start_1|>
from .audit_actor import AuditActor
from .audit_resource import AuditResource
from .entity import Entity
from .audit_actor im... | A class containing the properties for Audit Event. | AuditEvent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditEvent:
"""A class containing the properties for Audit Event."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditEvent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to rea... | stack_v2_sparse_classes_36k_train_012822 | 4,862 | 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: AuditEvent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pa... | 3 | null | Implement the Python class `AuditEvent` described below.
Class description:
A class containing the properties for Audit Event.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditEvent: Creates a new instance of the appropriate class based on discrimin... | Implement the Python class `AuditEvent` described below.
Class description:
A class containing the properties for Audit Event.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditEvent: Creates a new instance of the appropriate class based on discrimin... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AuditEvent:
"""A class containing the properties for Audit Event."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditEvent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to rea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditEvent:
"""A class containing the properties for Audit Event."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditEvent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrim... | the_stack_v2_python_sparse | msgraph/generated/models/audit_event.py | microsoftgraph/msgraph-sdk-python | train | 135 |
e0b070d2827cd8fdec9e9b9fd371e60d1ce13882 | [
"temp = []\nfor num in nums:\n if not temp:\n temp.append([num])\n continue\n for t in temp:\n add = []\n index = bisect.bisect_left(t, num)\n if index == len(t):\n t.append(num)\n elif index == len(t) - 1:\n t[-1] = num\n else:\n ... | <|body_start_0|>
temp = []
for num in nums:
if not temp:
temp.append([num])
continue
for t in temp:
add = []
index = bisect.bisect_left(t, num)
if index == len(t):
t.append(num)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
temp = []
for num in nums:
... | stack_v2_sparse_classes_36k_train_012823 | 1,108 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS0",
"signature": "def lengthOfLIS0(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS0(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(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 lengthOfLIS0(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOfLI... | 64747eb172c2ecb3c889830246f3282669516e10 | <|skeleton|>
class Solution:
def lengthOfLIS0(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS0(self, nums):
""":type nums: List[int] :rtype: int"""
temp = []
for num in nums:
if not temp:
temp.append([num])
continue
for t in temp:
add = []
index = bisect.bisect_left... | the_stack_v2_python_sparse | LC/300.py | szhu3210/LeetCode_Solutions | train | 2 | |
878a79bfa100fcce35c90ca8d9ecbe8ebfcc8085 | [
"self.capacity = capacity\nself.cache = {}\nself.last_time_dic = {}\nself.used_size = 0\nself.last_time = 0\nself.lru = deque()",
"value = self.cache.get(key, -1)\nif value != -1:\n self.lru.append((key, self.last_time))\n self.last_time_dic[key] = self.last_time\n self.last_time += 1\nreturn value",
"... | <|body_start_0|>
self.capacity = capacity
self.cache = {}
self.last_time_dic = {}
self.used_size = 0
self.last_time = 0
self.lru = deque()
<|end_body_0|>
<|body_start_1|>
value = self.cache.get(key, -1)
if value != -1:
self.lru.append((key, se... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_012824 | 3,050 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = {}
self.last_time_dic = {}
self.used_size = 0
self.last_time = 0
self.lru = deque()
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | 146-LRU_cache.py | WweiL/LeetCode | train | 0 | |
d26853fcde64caa99ea77eebb61008b57593c741 | [
"self.backup_run = backup_run\nself.copy_runs = copy_runs\nself.protection_job = protection_job",
"if dictionary is None:\n return None\nbackup_run = cohesity_management_sdk.models.backup_run.BackupRun.from_dictionary(dictionary.get('backupRun')) if dictionary.get('backupRun') else None\ncopy_runs = None\nif d... | <|body_start_0|>
self.backup_run = backup_run
self.copy_runs = copy_runs
self.protection_job = protection_job
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
backup_run = cohesity_management_sdk.models.backup_run.BackupRun.from_dictionary(dictionar... | Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of type kRegular. Attributes: backup_run (BackupRun): Specifies details about the last Backup task. A Ba... | ProtectionJobSummaryForPolicies | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionJobSummaryForPolicies:
"""Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of type kRegular. Attributes: backup_run (Bac... | stack_v2_sparse_classes_36k_train_012825 | 2,885 | permissive | [
{
"docstring": "Constructor for the ProtectionJobSummaryForPolicies class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, copy_runs=None, protection_job=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona... | 2 | stack_v2_sparse_classes_30k_train_015382 | Implement the Python class `ProtectionJobSummaryForPolicies` described below.
Class description:
Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of typ... | Implement the Python class `ProtectionJobSummaryForPolicies` described below.
Class description:
Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of typ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionJobSummaryForPolicies:
"""Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of type kRegular. Attributes: backup_run (Bac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectionJobSummaryForPolicies:
"""Implementation of the 'ProtectionJobSummaryForPolicies' model. ProtectionJobSummaryForPolicies is the summary of a Protection Jobs associated with the Specified Protection Policy. This is only populated for a policy of type kRegular. Attributes: backup_run (BackupRun): Spec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_job_summary_for_policies.py | cohesity/management-sdk-python | train | 24 |
2308b67facec3a4b1a03249d751bebe9a5e8a003 | [
"self.data = data\nself.next = None\nreturn",
"if self.data == value:\n return True\nelse:\n return False"
] | <|body_start_0|>
self.data = data
self.next = None
return
<|end_body_0|>
<|body_start_1|>
if self.data == value:
return True
else:
return False
<|end_body_1|>
| ListNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListNode:
def __init__(self, data):
"""constructor to initiate this object"""
<|body_0|>
def has_value(self, value):
"""method to compare the value with the node data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = data
self.next... | stack_v2_sparse_classes_36k_train_012826 | 2,771 | no_license | [
{
"docstring": "constructor to initiate this object",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "method to compare the value with the node data",
"name": "has_value",
"signature": "def has_value(self, value)"
}
] | 2 | null | Implement the Python class `ListNode` described below.
Class description:
Implement the ListNode class.
Method signatures and docstrings:
- def __init__(self, data): constructor to initiate this object
- def has_value(self, value): method to compare the value with the node data | Implement the Python class `ListNode` described below.
Class description:
Implement the ListNode class.
Method signatures and docstrings:
- def __init__(self, data): constructor to initiate this object
- def has_value(self, value): method to compare the value with the node data
<|skeleton|>
class ListNode:
def ... | d5efcfdaf7e632e1f0cb8b21c505c0c0a5325eb0 | <|skeleton|>
class ListNode:
def __init__(self, data):
"""constructor to initiate this object"""
<|body_0|>
def has_value(self, value):
"""method to compare the value with the node data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListNode:
def __init__(self, data):
"""constructor to initiate this object"""
self.data = data
self.next = None
return
def has_value(self, value):
"""method to compare the value with the node data"""
if self.data == value:
return True
el... | the_stack_v2_python_sparse | Linked_Lists/Linked_Lists_singly_linked_list_basic_2.py | zjxpirate/Daily-Upload-Python | train | 2 | |
b3b787d4270d945bfac527f6aa7bcb7e796d327c | [
"access_token = session.query(AccessToken).filter(AccessToken.access_token == access_token).one()\nentity = AccessTokenMapper.to_entity(record=access_token)\nraise Return(entity)",
"access_tokens = session.query(AccessToken).filter(AccessToken.user_id == user_id).all()\nentities = [AccessTokenMapper.to_entity(rec... | <|body_start_0|>
access_token = session.query(AccessToken).filter(AccessToken.access_token == access_token).one()
entity = AccessTokenMapper.to_entity(record=access_token)
raise Return(entity)
<|end_body_0|>
<|body_start_1|>
access_tokens = session.query(AccessToken).filter(AccessToken.... | AccessTokenRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessTokenRepository:
def read_one(access_token, session):
""":param access_token: :param Session session: :return: :raises NoResultFound:"""
<|body_0|>
def read_many(user_id, session):
""":param user_id: :param session: :return:"""
<|body_1|>
def upser... | stack_v2_sparse_classes_36k_train_012827 | 2,771 | no_license | [
{
"docstring": ":param access_token: :param Session session: :return: :raises NoResultFound:",
"name": "read_one",
"signature": "def read_one(access_token, session)"
},
{
"docstring": ":param user_id: :param session: :return:",
"name": "read_many",
"signature": "def read_many(user_id, se... | 4 | stack_v2_sparse_classes_30k_train_020946 | Implement the Python class `AccessTokenRepository` described below.
Class description:
Implement the AccessTokenRepository class.
Method signatures and docstrings:
- def read_one(access_token, session): :param access_token: :param Session session: :return: :raises NoResultFound:
- def read_many(user_id, session): :pa... | Implement the Python class `AccessTokenRepository` described below.
Class description:
Implement the AccessTokenRepository class.
Method signatures and docstrings:
- def read_one(access_token, session): :param access_token: :param Session session: :return: :raises NoResultFound:
- def read_many(user_id, session): :pa... | fd759c16b9864f6b1b47b1ba3f1af77f8d08af20 | <|skeleton|>
class AccessTokenRepository:
def read_one(access_token, session):
""":param access_token: :param Session session: :return: :raises NoResultFound:"""
<|body_0|>
def read_many(user_id, session):
""":param user_id: :param session: :return:"""
<|body_1|>
def upser... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessTokenRepository:
def read_one(access_token, session):
""":param access_token: :param Session session: :return: :raises NoResultFound:"""
access_token = session.query(AccessToken).filter(AccessToken.access_token == access_token).one()
entity = AccessTokenMapper.to_entity(record=ac... | the_stack_v2_python_sparse | ParkingFinder/repositories/access_token_repository.py | Big-Lemon/ParkingFinder | train | 2 | |
5ceb61f96618915d1e80309f7b0b443090c4250b | [
"for thread in queryset:\n thread.save()\nself.message_user(request, _('The selected threads have been successfully updated.'))",
"count = 0\nfor thread in queryset:\n count += 1 if thread.lock() else 0\nself.message_user(request, _('{count} threads have been locked.').format(count=count))",
"count = 0\nf... | <|body_start_0|>
for thread in queryset:
thread.save()
self.message_user(request, _('The selected threads have been successfully updated.'))
<|end_body_0|>
<|body_start_1|>
count = 0
for thread in queryset:
count += 1 if thread.lock() else 0
self.message_... | Administration de forum | ThreadAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadAdmin:
"""Administration de forum"""
def resave(self, request, queryset):
"""Sauvegarder à nouveau le contenu pour mettre à jour les informations"""
<|body_0|>
def lock(self, request, queryset):
"""Verrouiller les fils"""
<|body_1|>
def hide(se... | stack_v2_sparse_classes_36k_train_012828 | 1,813 | no_license | [
{
"docstring": "Sauvegarder à nouveau le contenu pour mettre à jour les informations",
"name": "resave",
"signature": "def resave(self, request, queryset)"
},
{
"docstring": "Verrouiller les fils",
"name": "lock",
"signature": "def lock(self, request, queryset)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_007386 | Implement the Python class `ThreadAdmin` described below.
Class description:
Administration de forum
Method signatures and docstrings:
- def resave(self, request, queryset): Sauvegarder à nouveau le contenu pour mettre à jour les informations
- def lock(self, request, queryset): Verrouiller les fils
- def hide(self, ... | Implement the Python class `ThreadAdmin` described below.
Class description:
Administration de forum
Method signatures and docstrings:
- def resave(self, request, queryset): Sauvegarder à nouveau le contenu pour mettre à jour les informations
- def lock(self, request, queryset): Verrouiller les fils
- def hide(self, ... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class ThreadAdmin:
"""Administration de forum"""
def resave(self, request, queryset):
"""Sauvegarder à nouveau le contenu pour mettre à jour les informations"""
<|body_0|>
def lock(self, request, queryset):
"""Verrouiller les fils"""
<|body_1|>
def hide(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadAdmin:
"""Administration de forum"""
def resave(self, request, queryset):
"""Sauvegarder à nouveau le contenu pour mettre à jour les informations"""
for thread in queryset:
thread.save()
self.message_user(request, _('The selected threads have been successfully up... | the_stack_v2_python_sparse | scoop/forum/admin/thread.py | artscoop/scoop | 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_36k_train_012829 | 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 | null | 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_36k | data/stack_v2_sparse_classes_30k | 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 | |
87c34a5ceb0c54dde76385d13c44a47e4f08876a | [
"username = 'test@test.com'\npassword = 'toto'\nself.client.post(reverse(register), {'username': username, 'password': password})\nresponse = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json')\nself.token = json.loads(response.content)['token']",
"self.client... | <|body_start_0|>
username = 'test@test.com'
password = 'toto'
self.client.post(reverse(register), {'username': username, 'password': password})
response = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json')
self.token = json.l... | Test access to API for users with API rights. | TestAPIAccess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAPIAccess:
"""Test access to API for users with API rights."""
def setUp(self):
"""First register a user (automatically registered to free plan)."""
<|body_0|>
def test_api_access_ok(self):
"""Test API access by looking up for siemens.com."""
<|body_1... | stack_v2_sparse_classes_36k_train_012830 | 8,751 | no_license | [
{
"docstring": "First register a user (automatically registered to free plan).",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test API access by looking up for siemens.com.",
"name": "test_api_access_ok",
"signature": "def test_api_access_ok(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_009681 | Implement the Python class `TestAPIAccess` described below.
Class description:
Test access to API for users with API rights.
Method signatures and docstrings:
- def setUp(self): First register a user (automatically registered to free plan).
- def test_api_access_ok(self): Test API access by looking up for siemens.com... | Implement the Python class `TestAPIAccess` described below.
Class description:
Test access to API for users with API rights.
Method signatures and docstrings:
- def setUp(self): First register a user (automatically registered to free plan).
- def test_api_access_ok(self): Test API access by looking up for siemens.com... | 9c0027b84d8dee6044ff28362e2b2b90c1759b90 | <|skeleton|>
class TestAPIAccess:
"""Test access to API for users with API rights."""
def setUp(self):
"""First register a user (automatically registered to free plan)."""
<|body_0|>
def test_api_access_ok(self):
"""Test API access by looking up for siemens.com."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAPIAccess:
"""Test access to API for users with API rights."""
def setUp(self):
"""First register a user (automatically registered to free plan)."""
username = 'test@test.com'
password = 'toto'
self.client.post(reverse(register), {'username': username, 'password': pass... | the_stack_v2_python_sparse | django_project/api_core/tests.py | juliensalinas/python-django-api-reactjs-frontend-slate-documentation-various-client-libs | train | 3 |
8cc1c8a2dae587a063583e1e4e18d86634c71db1 | [
"if not kwargs.get('no_django', False):\n overrides = dict([(k, getattr(middleware, k, None)) for k in django_variables])\n overrides['lookup'] = overrides['lookup']['main']\n kwargs.update(overrides)\nsuper(Template, self).__init__(*args, **kwargs)",
"context_dictionary = {}\nif middleware.requestcontex... | <|body_start_0|>
if not kwargs.get('no_django', False):
overrides = dict([(k, getattr(middleware, k, None)) for k in django_variables])
overrides['lookup'] = overrides['lookup']['main']
kwargs.update(overrides)
super(Template, self).__init__(*args, **kwargs)
<|end_bod... | This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand. | Template | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Template:
"""This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand."""
def __init__(self, *args, **kwargs):
"""Overrides base __init__ to provi... | stack_v2_sparse_classes_36k_train_012831 | 2,563 | no_license | [
{
"docstring": "Overrides base __init__ to provide django variable overrides",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "This takes a render call with a context (from Django) and translates it to a render call on the mako template.",
"name": "r... | 2 | stack_v2_sparse_classes_30k_train_003465 | Implement the Python class `Template` described below.
Class description:
This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand.
Method signatures and docstrings:
- def __init__... | Implement the Python class `Template` described below.
Class description:
This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand.
Method signatures and docstrings:
- def __init__... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class Template:
"""This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand."""
def __init__(self, *args, **kwargs):
"""Overrides base __init__ to provi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Template:
"""This bridges the gap between a Mako template and a djano template. It can be rendered like it is a django template because the arguments are transformed in a way that MakoTemplate can understand."""
def __init__(self, *args, **kwargs):
"""Overrides base __init__ to provide django var... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/template.py | vivekaxl/LexisNexis | train | 9 |
bcd4d6e2376db993b02e17bb6129c7dd5d660a48 | [
"if not loginattempt.username:\n logger.info(u'Authentication failure, address=%s, no username supplied.', loginattempt.source_address)\n raise ValidationError(self.text, code='invalid_login')\nif not password:\n logger.info(u'Authentication failure, username=%s, address=%s, no password supplied.', loginat... | <|body_start_0|>
if not loginattempt.username:
logger.info(u'Authentication failure, address=%s, no username supplied.', loginattempt.source_address)
raise ValidationError(self.text, code='invalid_login')
if not password:
logger.info(u'Authentication failure, username... | Handle basich checks. | AuthenticationBasicChecks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationBasicChecks:
"""Handle basich checks."""
def pre_auth_check(self, loginattempt, password):
"""Pre check."""
<|body_0|>
def post_auth_check(self, loginattempt):
"""Post login check."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if... | stack_v2_sparse_classes_36k_train_012832 | 3,976 | no_license | [
{
"docstring": "Pre check.",
"name": "pre_auth_check",
"signature": "def pre_auth_check(self, loginattempt, password)"
},
{
"docstring": "Post login check.",
"name": "post_auth_check",
"signature": "def post_auth_check(self, loginattempt)"
}
] | 2 | null | Implement the Python class `AuthenticationBasicChecks` described below.
Class description:
Handle basich checks.
Method signatures and docstrings:
- def pre_auth_check(self, loginattempt, password): Pre check.
- def post_auth_check(self, loginattempt): Post login check. | Implement the Python class `AuthenticationBasicChecks` described below.
Class description:
Handle basich checks.
Method signatures and docstrings:
- def pre_auth_check(self, loginattempt, password): Pre check.
- def post_auth_check(self, loginattempt): Post login check.
<|skeleton|>
class AuthenticationBasicChecks:
... | cb392be0402543acf074425fcaf8edf054269012 | <|skeleton|>
class AuthenticationBasicChecks:
"""Handle basich checks."""
def pre_auth_check(self, loginattempt, password):
"""Pre check."""
<|body_0|>
def post_auth_check(self, loginattempt):
"""Post login check."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticationBasicChecks:
"""Handle basich checks."""
def pre_auth_check(self, loginattempt, password):
"""Pre check."""
if not loginattempt.username:
logger.info(u'Authentication failure, address=%s, no username supplied.', loginattempt.source_address)
raise Vali... | the_stack_v2_python_sparse | cpovc_access/authentication.py | uonafya/cpims-2.3beta | train | 4 |
8d0e270b14786e0563414c2e978f6de07d7eb6a5 | [
"permission = super().has_change_permission(request, obj)\nif obj is not None:\n permission &= obj.owner == request.user or request.user.is_superuser\nreturn permission",
"permission = super().has_delete_permission(request, obj)\nif obj is not None:\n permission &= obj.owner == request.user or request.user.... | <|body_start_0|>
permission = super().has_change_permission(request, obj)
if obj is not None:
permission &= obj.owner == request.user or request.user.is_superuser
return permission
<|end_body_0|>
<|body_start_1|>
permission = super().has_delete_permission(request, obj)
... | ApplicationAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
<|body_0|>
def has_delete_permission(self, request, obj=None) -> bool:
"""Does the user have permission to delete this object?"""
... | stack_v2_sparse_classes_36k_train_012833 | 1,225 | permissive | [
{
"docstring": "Does the user have permission to change this object?",
"name": "has_change_permission",
"signature": "def has_change_permission(self, request, obj=None) -> bool"
},
{
"docstring": "Does the user have permission to delete this object?",
"name": "has_delete_permission",
"si... | 3 | stack_v2_sparse_classes_30k_val_000065 | Implement the Python class `ApplicationAdmin` described below.
Class description:
Implement the ApplicationAdmin class.
Method signatures and docstrings:
- def has_change_permission(self, request, obj=None) -> bool: Does the user have permission to change this object?
- def has_delete_permission(self, request, obj=No... | Implement the Python class `ApplicationAdmin` described below.
Class description:
Implement the ApplicationAdmin class.
Method signatures and docstrings:
- def has_change_permission(self, request, obj=None) -> bool: Does the user have permission to change this object?
- def has_delete_permission(self, request, obj=No... | 25a111ac7cf4b23fee50ad8eac6ea21564954859 | <|skeleton|>
class ApplicationAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
<|body_0|>
def has_delete_permission(self, request, obj=None) -> bool:
"""Does the user have permission to delete this object?"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplicationAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
permission = super().has_change_permission(request, obj)
if obj is not None:
permission &= obj.owner == request.user or request.user.is_s... | the_stack_v2_python_sparse | applications/admin.py | PEDASI/PEDASI | train | 0 | |
50fb49cac282e110febff50f23cc5961885bc2bc | [
"npts = len(pts)\nh = ncfs // 2\ncfs = {}\nfor n in range(-h, h + 1):\n cn = 0\n for iw in range(npts):\n w = iw / npts\n fw = complex(*pts[iw])\n cn += fw * cmath.exp(-1j * n * w * wo)\n cn /= npts\n cfs[n] = cn\nreturn cfs",
"ncfs = len(cfs)\nh = npts // 2\npts = []\nfor it in r... | <|body_start_0|>
npts = len(pts)
h = ncfs // 2
cfs = {}
for n in range(-h, h + 1):
cn = 0
for iw in range(npts):
w = iw / npts
fw = complex(*pts[iw])
cn += fw * cmath.exp(-1j * n * w * wo)
cn /= npts
... | Fourier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
<|body_0|>
def inverseTransform(cfs, npts, wo=2 * math.pi):
"""Apply the true fourier inverse transform by returning the list of t... | stack_v2_sparse_classes_36k_train_012834 | 17,065 | permissive | [
{
"docstring": "Apply the true fourier transform by returning a dictionary of the coefficients.",
"name": "transform",
"signature": "def transform(pts, ncfs, wo=2 * math.pi)"
},
{
"docstring": "Apply the true fourier inverse transform by returning the list of the points.",
"name": "inverseTr... | 3 | stack_v2_sparse_classes_30k_train_011811 | Implement the Python class `Fourier` described below.
Class description:
Implement the Fourier class.
Method signatures and docstrings:
- def transform(pts, ncfs, wo=2 * math.pi): Apply the true fourier transform by returning a dictionary of the coefficients.
- def inverseTransform(cfs, npts, wo=2 * math.pi): Apply t... | Implement the Python class `Fourier` described below.
Class description:
Implement the Fourier class.
Method signatures and docstrings:
- def transform(pts, ncfs, wo=2 * math.pi): Apply the true fourier transform by returning a dictionary of the coefficients.
- def inverseTransform(cfs, npts, wo=2 * math.pi): Apply t... | 61abbbeac0fd351253e06b19736d9939fd5b316e | <|skeleton|>
class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
<|body_0|>
def inverseTransform(cfs, npts, wo=2 * math.pi):
"""Apply the true fourier inverse transform by returning the list of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
npts = len(pts)
h = ncfs // 2
cfs = {}
for n in range(-h, h + 1):
cn = 0
for iw in range(npts):
... | the_stack_v2_python_sparse | pygame_geometry/demos/myfouriervf.py | MarcPartensky/Pygame-Geometry | train | 7 | |
c617f04672fad8564a6935c73a1c8b5bb90d4c4a | [
"logic = AssociationLogic(self.auth, sid)\nlogic.association = logic.get_association(aid)\nif self.VERSION:\n check_login(lambda x: True)(self)\n return Result(data=logic.get_config().version_dict, association_id=self.auth.get_association_id())\nlogic.account = logic.get_association_account(throw=True)\nretur... | <|body_start_0|>
logic = AssociationLogic(self.auth, sid)
logic.association = logic.get_association(aid)
if self.VERSION:
check_login(lambda x: True)(self)
return Result(data=logic.get_config().version_dict, association_id=self.auth.get_association_id())
logic.acc... | AssociationInfoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssociationInfoView:
def get(self, request, sid, aid):
"""获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid):
"""创建协会 :param request: :param sid: :return:"""
<|body_1|>
def put(self, request, si... | stack_v2_sparse_classes_36k_train_012835 | 7,404 | no_license | [
{
"docstring": "获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, aid)"
},
{
"docstring": "创建协会 :param request: :param sid: :return:",
"name": "post",
"signature": "def post(self, request, sid)"
},
{
"do... | 4 | stack_v2_sparse_classes_30k_train_009440 | Implement the Python class `AssociationInfoView` described below.
Class description:
Implement the AssociationInfoView class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:
- def post(self, request, sid): 创建协会 :param request: :... | Implement the Python class `AssociationInfoView` described below.
Class description:
Implement the AssociationInfoView class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:
- def post(self, request, sid): 创建协会 :param request: :... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class AssociationInfoView:
def get(self, request, sid, aid):
"""获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid):
"""创建协会 :param request: :param sid: :return:"""
<|body_1|>
def put(self, request, si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssociationInfoView:
def get(self, request, sid, aid):
"""获取协会信息 or 获取评优版本信息 :param request: :param sid: :param aid: :return:"""
logic = AssociationLogic(self.auth, sid)
logic.association = logic.get_association(aid)
if self.VERSION:
check_login(lambda x: True)(self... | the_stack_v2_python_sparse | LittlePigHoHo/server/association/views/info.py | shoogoome/hoho | train | 1 | |
aa0d0ffb29b9cac455fb4456495142ce112c01e3 | [
"self.controller_bus_number = controller_bus_number\nself.controller_type = controller_type\nself.disk_id = disk_id\nself.unit_number = unit_number",
"if dictionary is None:\n return None\ncontroller_bus_number = dictionary.get('controllerBusNumber')\ncontroller_type = dictionary.get('controllerType')\ndisk_id... | <|body_start_0|>
self.controller_bus_number = controller_bus_number
self.controller_type = controller_type
self.disk_id = disk_id
self.unit_number = unit_number
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
controller_bus_number = diction... | Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in question. controller_type (string): Controller's type (SCSI, IDE etc). disk_id (... | VirtualDiskId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDiskId:
"""Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in question. controller_type (string): Con... | stack_v2_sparse_classes_36k_train_012836 | 2,454 | permissive | [
{
"docstring": "Constructor for the VirtualDiskId class",
"name": "__init__",
"signature": "def __init__(self, controller_bus_number=None, controller_type=None, disk_id=None, unit_number=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): ... | 2 | null | Implement the Python class `VirtualDiskId` described below.
Class description:
Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in ... | Implement the Python class `VirtualDiskId` described below.
Class description:
Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VirtualDiskId:
"""Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in question. controller_type (string): Con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualDiskId:
"""Implementation of the 'VirtualDiskId' model. This message defines the proto that can be used to identify the disks in different environments. Attributes: controller_bus_number (long|int): Controller's bus-id controlling the virtual disk in question. controller_type (string): Controller's typ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/virtual_disk_id.py | cohesity/management-sdk-python | train | 24 |
8085854a252884539616552943b3abe2ca63800c | [
"self.prefix = prefix\nself.species = species\nself.epigenome = epigenome\nself.yml_data = dict(species=self.species, epigenome=self.epigenome, bigwigs=None, fastqs=None, model=False, gene_sets=None, sample_number=sample_number, cluster=cluster, only_newhdf5=only_newhdf5, web=web, prefix=self.prefix, clean=clean)",... | <|body_start_0|>
self.prefix = prefix
self.species = species
self.epigenome = epigenome
self.yml_data = dict(species=self.species, epigenome=self.epigenome, bigwigs=None, fastqs=None, model=False, gene_sets=None, sample_number=sample_number, cluster=cluster, only_newhdf5=only_newhdf5, we... | LISA pipeline for processing multiple files | LisaPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LisaPipeline:
"""LISA pipeline for processing multiple files"""
def __init__(self, prefix, species, epigenome, cluster, only_newhdf5=False, sample_number=10, web=False, clean=False):
"""species: the species of gene_sets, epigenome: a list of marks, e.g. ['H3K4me3', 'H3K27ac'], for mu... | stack_v2_sparse_classes_36k_train_012837 | 5,099 | permissive | [
{
"docstring": "species: the species of gene_sets, epigenome: a list of marks, e.g. ['H3K4me3', 'H3K27ac'], for multiple_bigwig2hdf, this can be covariates, such as `GC` gene_sets: a list of path to gene list file, the file contains a gene per line.",
"name": "__init__",
"signature": "def __init__(self,... | 4 | stack_v2_sparse_classes_30k_train_010985 | Implement the Python class `LisaPipeline` described below.
Class description:
LISA pipeline for processing multiple files
Method signatures and docstrings:
- def __init__(self, prefix, species, epigenome, cluster, only_newhdf5=False, sample_number=10, web=False, clean=False): species: the species of gene_sets, epigen... | Implement the Python class `LisaPipeline` described below.
Class description:
LISA pipeline for processing multiple files
Method signatures and docstrings:
- def __init__(self, prefix, species, epigenome, cluster, only_newhdf5=False, sample_number=10, web=False, clean=False): species: the species of gene_sets, epigen... | 9fef7cb682264bdef5cca6847d09acf6c92a08f2 | <|skeleton|>
class LisaPipeline:
"""LISA pipeline for processing multiple files"""
def __init__(self, prefix, species, epigenome, cluster, only_newhdf5=False, sample_number=10, web=False, clean=False):
"""species: the species of gene_sets, epigenome: a list of marks, e.g. ['H3K4me3', 'H3K27ac'], for mu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LisaPipeline:
"""LISA pipeline for processing multiple files"""
def __init__(self, prefix, species, epigenome, cluster, only_newhdf5=False, sample_number=10, web=False, clean=False):
"""species: the species of gene_sets, epigenome: a list of marks, e.g. ['H3K4me3', 'H3K27ac'], for multiple_bigwig... | the_stack_v2_python_sparse | bin/lisa | qinqian/lisa | train | 27 |
350652045fbaa57dfe7b38a93a11d750a3601951 | [
"if self.path == '/del_config' or self.path == '/del_config/':\n self.server.config = dict()\n self.log_message('Reset Server Configuration.')\n self.send_response(200)\nelse:\n self.send_response(404)",
"self.log_message(f'Youtube provider received GET request to path {self.path}')\nif 'get_config' i... | <|body_start_0|>
if self.path == '/del_config' or self.path == '/del_config/':
self.server.config = dict()
self.log_message('Reset Server Configuration.')
self.send_response(200)
else:
self.send_response(404)
<|end_body_0|>
<|body_start_1|>
self.l... | A handler for Youtube GET requests. | StubYouTubeHandler | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StubYouTubeHandler:
"""A handler for Youtube GET requests."""
def do_DELETE(self):
"""Allow callers to delete all the server configurations using the /del_config URL."""
<|body_0|>
def do_GET(self):
"""Handle a GET request from the client and sends response back.... | stack_v2_sparse_classes_36k_train_012838 | 6,207 | permissive | [
{
"docstring": "Allow callers to delete all the server configurations using the /del_config URL.",
"name": "do_DELETE",
"signature": "def do_DELETE(self)"
},
{
"docstring": "Handle a GET request from the client and sends response back.",
"name": "do_GET",
"signature": "def do_GET(self)"
... | 4 | stack_v2_sparse_classes_30k_train_016881 | Implement the Python class `StubYouTubeHandler` described below.
Class description:
A handler for Youtube GET requests.
Method signatures and docstrings:
- def do_DELETE(self): Allow callers to delete all the server configurations using the /del_config URL.
- def do_GET(self): Handle a GET request from the client and... | Implement the Python class `StubYouTubeHandler` described below.
Class description:
A handler for Youtube GET requests.
Method signatures and docstrings:
- def do_DELETE(self): Allow callers to delete all the server configurations using the /del_config URL.
- def do_GET(self): Handle a GET request from the client and... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class StubYouTubeHandler:
"""A handler for Youtube GET requests."""
def do_DELETE(self):
"""Allow callers to delete all the server configurations using the /del_config URL."""
<|body_0|>
def do_GET(self):
"""Handle a GET request from the client and sends response back.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StubYouTubeHandler:
"""A handler for Youtube GET requests."""
def do_DELETE(self):
"""Allow callers to delete all the server configurations using the /del_config URL."""
if self.path == '/del_config' or self.path == '/del_config/':
self.server.config = dict()
self.... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/djangoapps/terrain/stubs/youtube.py | luque/better-ways-of-thinking-about-software | train | 3 |
781d002e5ce2177595aeae5056758074f2b49f07 | [
"self.quota_policy = quota_policy\nself.sid = sid\nself.unix_uid = unix_uid",
"if dictionary is None:\n return None\nquota_policy = cohesity_management_sdk.models.quota_policy.QuotaPolicy.from_dictionary(dictionary.get('quotaPolicy')) if dictionary.get('quotaPolicy') else None\nsid = dictionary.get('sid')\nuni... | <|body_start_0|>
self.quota_policy = quota_policy
self.sid = sid
self.unix_uid = unix_uid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
quota_policy = cohesity_management_sdk.models.quota_policy.QuotaPolicy.from_dictionary(dictionary.get('quotaPo... | Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are available (i.e., when mixed mode is ... | UserQuota | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserQuota:
"""Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are... | stack_v2_sparse_classes_36k_train_012839 | 2,632 | permissive | [
{
"docstring": "Constructor for the UserQuota class",
"name": "__init__",
"signature": "def __init__(self, quota_policy=None, sid=None, unix_uid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object ... | 2 | null | Implement the Python class `UserQuota` described below.
Class description:
Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise,... | Implement the Python class `UserQuota` described below.
Class description:
Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise,... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UserQuota:
"""Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserQuota:
"""Implementation of the 'UserQuota' model. Specifies the quota policy applied to a user. Attributes: quota_policy (QuotaPolicy): User quota policy applied to this user. sid (string): If interested in a user via smb_client, include SID. Otherwise, If a valid unix-id to SID mappings are available (i... | the_stack_v2_python_sparse | cohesity_management_sdk/models/user_quota.py | cohesity/management-sdk-python | train | 24 |
cdda8a14090380a17b41430e97cd910c05171aed | [
"self.kv = {keys[i]: values[i] for i in range(len(keys))}\nself.vk = defaultdict(list)\nfor i in range(len(keys)):\n vk[values[i]].append(keys[i])\nself.d = Trie()\nfor word in dictionary:\n self.d.insert(word)",
"res = []\nfor ch in word1:\n res.append(self.kv[ch])\nreturn ''.join(res)",
"res = []\nfo... | <|body_start_0|>
self.kv = {keys[i]: values[i] for i in range(len(keys))}
self.vk = defaultdict(list)
for i in range(len(keys)):
vk[values[i]].append(keys[i])
self.d = Trie()
for word in dictionary:
self.d.insert(word)
<|end_body_0|>
<|body_start_1|>
... | Encrypter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
<|body_0|>
def encrypt(self, word1):
""":type word1: str :rtype: str"""
<|body_1|>
def decrypt(self, word2):
... | stack_v2_sparse_classes_36k_train_012840 | 2,665 | no_license | [
{
"docstring": ":type keys: List[str] :type values: List[str] :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, keys, values, dictionary)"
},
{
"docstring": ":type word1: str :rtype: str",
"name": "encrypt",
"signature": "def encrypt(self, word1)"
},
... | 3 | stack_v2_sparse_classes_30k_train_004450 | Implement the Python class `Encrypter` described below.
Class description:
Implement the Encrypter class.
Method signatures and docstrings:
- def __init__(self, keys, values, dictionary): :type keys: List[str] :type values: List[str] :type dictionary: List[str]
- def encrypt(self, word1): :type word1: str :rtype: str... | Implement the Python class `Encrypter` described below.
Class description:
Implement the Encrypter class.
Method signatures and docstrings:
- def __init__(self, keys, values, dictionary): :type keys: List[str] :type values: List[str] :type dictionary: List[str]
- def encrypt(self, word1): :type word1: str :rtype: str... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
<|body_0|>
def encrypt(self, word1):
""":type word1: str :rtype: str"""
<|body_1|>
def decrypt(self, word2):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encrypter:
def __init__(self, keys, values, dictionary):
""":type keys: List[str] :type values: List[str] :type dictionary: List[str]"""
self.kv = {keys[i]: values[i] for i in range(len(keys))}
self.vk = defaultdict(list)
for i in range(len(keys)):
vk[values[i]].app... | the_stack_v2_python_sparse | _CodeTopics/LeetCode_contest/weekly/weekly2022/287/unfinished--287_4.py | BIAOXYZ/variousCodes | train | 0 | |
89797a12399b63f28d171ec3f3da1a651fe01d28 | [
"super().__init__(model_config)\nself.model = model\nself.pipeline_id = pipeline_id\nmodel.eval()",
"if not path_to_checkpoint.is_file():\n logging.warning(f'Could not recover model from checkpoint path {path_to_checkpoint}')\n return None\nif config.compute_mean_teacher_model:\n raise NotImplementedErro... | <|body_start_0|>
super().__init__(model_config)
self.model = model
self.pipeline_id = pipeline_id
model.eval()
<|end_body_0|>
<|body_start_1|>
if not path_to_checkpoint.is_file():
logging.warning(f'Could not recover model from checkpoint path {path_to_checkpoint}')
... | Pipeline for inference from a single model on classification tasks. | ScalarInferencePipeline | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: ScalarLightning, model_config: ScalarModelBase, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :param model_config: Model con... | stack_v2_sparse_classes_36k_train_012841 | 9,301 | permissive | [
{
"docstring": ":param model: Model recovered from the checkpoint. :param model_config: Model configuration information. :param pipeline_id: ID for this pipeline (useful for ensembles). :return:",
"name": "__init__",
"signature": "def __init__(self, model: ScalarLightning, model_config: ScalarModelBase,... | 3 | null | Implement the Python class `ScalarInferencePipeline` described below.
Class description:
Pipeline for inference from a single model on classification tasks.
Method signatures and docstrings:
- def __init__(self, model: ScalarLightning, model_config: ScalarModelBase, pipeline_id: int) -> None: :param model: Model reco... | Implement the Python class `ScalarInferencePipeline` described below.
Class description:
Pipeline for inference from a single model on classification tasks.
Method signatures and docstrings:
- def __init__(self, model: ScalarLightning, model_config: ScalarModelBase, pipeline_id: int) -> None: :param model: Model reco... | 2877002d50d3a34d80f647c18cb561025d9066cc | <|skeleton|>
class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: ScalarLightning, model_config: ScalarModelBase, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :param model_config: Model con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalarInferencePipeline:
"""Pipeline for inference from a single model on classification tasks."""
def __init__(self, model: ScalarLightning, model_config: ScalarModelBase, pipeline_id: int) -> None:
""":param model: Model recovered from the checkpoint. :param model_config: Model configuration in... | the_stack_v2_python_sparse | InnerEye/ML/pipelines/scalar_inference.py | microsoft/InnerEye-DeepLearning | train | 511 |
bb3bc703cc345d0bb209484d039ea6468f5e953c | [
"stack = [root]\nwhile stack and root:\n cur = stack.pop()\n if cur.right:\n stack.append(cur.right)\n if cur.left:\n stack.append(cur.left)\n if cur != root:\n root.left, root.right = (None, TreeNode(cur.val))\n root = root.right",
"stack = [root]\nres = []\nwhile stack an... | <|body_start_0|>
stack = [root]
while stack and root:
cur = stack.pop()
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
if cur != root:
root.left, root.right = (None, TreeNode(cur.va... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
<|body_0|>
def flatten2(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sta... | stack_v2_sparse_classes_36k_train_012842 | 1,465 | no_license | [
{
"docstring": "前序遍历 :param root: :return:",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten2",
"signature": "def flatten2(self, root: TreeNode) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_005405 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 前序遍历 :param root: :return:
- def flatten2(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 前序遍历 :param root: :return:
- def flatten2(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
<|skele... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
<|body_0|>
def flatten2(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
stack = [root]
while stack and root:
cur = stack.pop()
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
... | the_stack_v2_python_sparse | 114_二叉树展开为链表.py | lovehhf/LeetCode | train | 0 | |
4ca7dfeecbccba396ec5f4b0f1c33381f0ec868f | [
"self._turn_on_light()\nself._turn_on_dimmer(**kwargs)\nif self.assumed_state:\n self.async_write_ha_state()",
"super()._async_update()\nself._async_update_light()\nself._async_update_dimmer()"
] | <|body_start_0|>
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
if self.assumed_state:
self.async_write_ha_state()
<|end_body_0|>
<|body_start_1|>
super()._async_update()
self._async_update_light()
self._async_update_dimmer()
<|end_body_1|>
| Dimmer child class to MySensorsLight. | MySensorsLightDimmer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_0|>
def _async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
... | stack_v2_sparse_classes_36k_train_012843 | 8,168 | permissive | [
{
"docstring": "Turn the device on.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs: Any) -> None"
},
{
"docstring": "Update the controller with the latest value from a sensor.",
"name": "_async_update",
"signature": "def _async_update(self) -> None"
}
] | 2 | null | Implement the Python class `MySensorsLightDimmer` described below.
Class description:
Dimmer child class to MySensorsLight.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def _async_update(self) -> None: Update the controller with the latest value from ... | Implement the Python class `MySensorsLightDimmer` described below.
Class description:
Dimmer child class to MySensorsLight.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def _async_update(self) -> None: Update the controller with the latest value from ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_0|>
def _async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
if self.assumed_state:
self.async_write_ha_state()
def _a... | the_stack_v2_python_sparse | homeassistant/components/mysensors/light.py | home-assistant/core | train | 35,501 |
13f14e8c54f9f61c501ff49c39b3f9465e05f791 | [
"x1 = x[0]\nx2 = x[1]\nx3 = x[2]\nx4 = x[3]\nreturn sum((100 * (x1 ** 2 - x2) ** 2, (x1 - 1) ** 2, (x3 - 1) ** 2, 90 * (x3 ** 2 - x4) ** 2, 10.1 * ((x2 - 1) ** 2 + (x4 - 1) ** 2), 19.8 * (x2 - 1) * (x4 - 1)))",
"x1 = x[0]\nx2 = x[1]\nx3 = x[2]\nx4 = x[3]\nreturn np.array([400 * x1 * (x1 ** 2 - x2) + 2 * (x1 - 1),... | <|body_start_0|>
x1 = x[0]
x2 = x[1]
x3 = x[2]
x4 = x[3]
return sum((100 * (x1 ** 2 - x2) ** 2, (x1 - 1) ** 2, (x3 - 1) ** 2, 90 * (x3 ** 2 - x4) ** 2, 10.1 * ((x2 - 1) ** 2 + (x4 - 1) ** 2), 19.8 * (x2 - 1) * (x4 - 1)))
<|end_body_0|>
<|body_start_1|>
x1 = x[0]
... | Class for evaluating a function including the gradient and hessian matrix at a given point x | Wood | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wood:
"""Class for evaluating a function including the gradient and hessian matrix at a given point x"""
def eval(self, x):
"""Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going to be evaluated"""
<|body_0|>
def gradient(... | stack_v2_sparse_classes_36k_train_012844 | 1,888 | no_license | [
{
"docstring": "Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going to be evaluated",
"name": "eval",
"signature": "def eval(self, x)"
},
{
"docstring": "Evaluates gradient of function at point x Parameters ---------- x : numpy.array Point at whic... | 3 | stack_v2_sparse_classes_30k_train_011030 | Implement the Python class `Wood` described below.
Class description:
Class for evaluating a function including the gradient and hessian matrix at a given point x
Method signatures and docstrings:
- def eval(self, x): Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going... | Implement the Python class `Wood` described below.
Class description:
Class for evaluating a function including the gradient and hessian matrix at a given point x
Method signatures and docstrings:
- def eval(self, x): Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going... | cbdfe22f367dbebcfdb03dee84a2c820e3718ffd | <|skeleton|>
class Wood:
"""Class for evaluating a function including the gradient and hessian matrix at a given point x"""
def eval(self, x):
"""Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going to be evaluated"""
<|body_0|>
def gradient(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wood:
"""Class for evaluating a function including the gradient and hessian matrix at a given point x"""
def eval(self, x):
"""Evaluates function at point x Parameters ---------- x : numpy.array Point at which function is going to be evaluated"""
x1 = x[0]
x2 = x[1]
x3 = x... | the_stack_v2_python_sparse | tarea7/Wood.py | IsaacRodgz/Optimizacion | train | 0 |
5995b5541e001406ad93a004e7cc3fab5dfd7f1b | [
"actions.mode.disable('command')\nactions.mode.enable('dictation')\nactions.mode.enable('user.german')\ngui_german_mode_active.show()",
"actions.mode.disable('user.german')\nactions.mode.disable('dictation')\nactions.mode.enable('command')\ngui_german_mode_active.hide()"
] | <|body_start_0|>
actions.mode.disable('command')
actions.mode.enable('dictation')
actions.mode.enable('user.german')
gui_german_mode_active.show()
<|end_body_0|>
<|body_start_1|>
actions.mode.disable('user.german')
actions.mode.disable('dictation')
actions.mode.e... | Actions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actions:
def german_mode_activate():
"""Activates german mode, to allow dictation in german language"""
<|body_0|>
def german_mode_deactivate():
"""Deactivates german mode and goes back to command mode in english"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_012845 | 794 | no_license | [
{
"docstring": "Activates german mode, to allow dictation in german language",
"name": "german_mode_activate",
"signature": "def german_mode_activate()"
},
{
"docstring": "Deactivates german mode and goes back to command mode in english",
"name": "german_mode_deactivate",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_014603 | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def german_mode_activate(): Activates german mode, to allow dictation in german language
- def german_mode_deactivate(): Deactivates german mode and goes back to command mode in en... | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def german_mode_activate(): Activates german mode, to allow dictation in german language
- def german_mode_deactivate(): Deactivates german mode and goes back to command mode in en... | e3221b708edea126e7a25ce3aa99567ba62b2e7d | <|skeleton|>
class Actions:
def german_mode_activate():
"""Activates german mode, to allow dictation in german language"""
<|body_0|>
def german_mode_deactivate():
"""Deactivates german mode and goes back to command mode in english"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actions:
def german_mode_activate():
"""Activates german mode, to allow dictation in german language"""
actions.mode.disable('command')
actions.mode.enable('dictation')
actions.mode.enable('user.german')
gui_german_mode_active.show()
def german_mode_deactivate():
... | the_stack_v2_python_sparse | dotfiles/talon/user/mystuff/languages/language_mode_actions.py | sbungartz/dotfiles | train | 1 | |
5ad624c97a74c6cd5eccb595c116d43290f02135 | [
"results = {}\nroom = gdata.rooms()[roomid]\nroom_conf = room.roomDefine.configure\nftlog.debug('room_conf =', room_conf, caller=cls)\nif not room_conf.get(MFTDefine.IS_CREATE, 0):\n return results\nfrom majiang2.servers.table.rpc import table_rpc\ntable = table_rpc.getTableByRoomId(roomid)\nreturn table",
"fo... | <|body_start_0|>
results = {}
room = gdata.rooms()[roomid]
room_conf = room.roomDefine.configure
ftlog.debug('room_conf =', room_conf, caller=cls)
if not room_conf.get(MFTDefine.IS_CREATE, 0):
return results
from majiang2.servers.table.rpc import table_rpc
... | 自建桌 | CreateTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateTable:
"""自建桌"""
def get_create_table_by_roomid(cls, roomid):
"""table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程"""
<|body_0|>
def get_create_table_from_table_list(cls, table_list):
"""根据room得到合适的table返回"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_012846 | 1,483 | no_license | [
{
"docstring": "table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程",
"name": "get_create_table_by_roomid",
"signature": "def get_create_table_by_roomid(cls, roomid)"
},
{
"docstring": "根据room得到合适的table返回",
"name": "get_create_table_from_table_list",
"signature": "def get_create_table_from_table... | 2 | null | Implement the Python class `CreateTable` described below.
Class description:
自建桌
Method signatures and docstrings:
- def get_create_table_by_roomid(cls, roomid): table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程
- def get_create_table_from_table_list(cls, table_list): 根据room得到合适的table返回 | Implement the Python class `CreateTable` described below.
Class description:
自建桌
Method signatures and docstrings:
- def get_create_table_by_roomid(cls, roomid): table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程
- def get_create_table_from_table_list(cls, table_list): 根据room得到合适的table返回
<|skeleton|>
class CreateTable:
... | b5b08a85d49c3bed460255a62dc5201b998d88d4 | <|skeleton|>
class CreateTable:
"""自建桌"""
def get_create_table_by_roomid(cls, roomid):
"""table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程"""
<|body_0|>
def get_create_table_from_table_list(cls, table_list):
"""根据room得到合适的table返回"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateTable:
"""自建桌"""
def get_create_table_by_roomid(cls, roomid):
"""table的RPC方法调用,UT进程请求执行,获取此房间符合条件的桌子并返回给UT进程"""
results = {}
room = gdata.rooms()[roomid]
room_conf = room.roomDefine.configure
ftlog.debug('room_conf =', room_conf, caller=cls)
if not ro... | the_stack_v2_python_sparse | majiang2/src/majiang2/entity/create_table_list.py | cnbcloud/mjserver | train | 1 |
fd4bafce42215876a71cdb4e88ea676cb2b7455d | [
"super().__init__()\nself.t_0 = t_0\nself.amp = amplitude",
"def wrap(time: Union[float, np.ndarray]) -> Union[float, np.ndarray]:\n return np.heaviside(time - self.t_0, 1)\nreturn wrap"
] | <|body_start_0|>
super().__init__()
self.t_0 = t_0
self.amp = amplitude
<|end_body_0|>
<|body_start_1|>
def wrap(time: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
return np.heaviside(time - self.t_0, 1)
return wrap
<|end_body_1|>
| Represent a sine waveform to be attached to a source. | StepWaveform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepWaveform:
"""Represent a sine waveform to be attached to a source."""
def __init__(self, t_0: float, amplitude: float=1):
"""Represent a A*sin(2*pi*f*t+offset)function."""
<|body_0|>
def func(self):
"""Return a gaussian waveform function."""
<|body_1|... | stack_v2_sparse_classes_36k_train_012847 | 2,517 | permissive | [
{
"docstring": "Represent a A*sin(2*pi*f*t+offset)function.",
"name": "__init__",
"signature": "def __init__(self, t_0: float, amplitude: float=1)"
},
{
"docstring": "Return a gaussian waveform function.",
"name": "func",
"signature": "def func(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001269 | Implement the Python class `StepWaveform` described below.
Class description:
Represent a sine waveform to be attached to a source.
Method signatures and docstrings:
- def __init__(self, t_0: float, amplitude: float=1): Represent a A*sin(2*pi*f*t+offset)function.
- def func(self): Return a gaussian waveform function. | Implement the Python class `StepWaveform` described below.
Class description:
Represent a sine waveform to be attached to a source.
Method signatures and docstrings:
- def __init__(self, t_0: float, amplitude: float=1): Represent a A*sin(2*pi*f*t+offset)function.
- def func(self): Return a gaussian waveform function.... | f2134cb3e36eabca1639b8ff4e428d3a268953bd | <|skeleton|>
class StepWaveform:
"""Represent a sine waveform to be attached to a source."""
def __init__(self, t_0: float, amplitude: float=1):
"""Represent a A*sin(2*pi*f*t+offset)function."""
<|body_0|>
def func(self):
"""Return a gaussian waveform function."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StepWaveform:
"""Represent a sine waveform to be attached to a source."""
def __init__(self, t_0: float, amplitude: float=1):
"""Represent a A*sin(2*pi*f*t+offset)function."""
super().__init__()
self.t_0 = t_0
self.amp = amplitude
def func(self):
"""Return a g... | the_stack_v2_python_sparse | fdtd/waveforms.py | tiagovla/fdtd.py | train | 4 |
74979e1e8793f43899afbb5ae6a5d64aeed8dd09 | [
"url = 'os-services'\nif params:\n url += '?%s' % urllib.urlencode(params)\nresp, body = self.get(url)\nbody = json.loads(body)\nschema = self.get_schema(self.schema_versions_info)\nself.validate_response(schema.list_services, resp, body)\nreturn rest_client.ResponseBody(resp, body)",
"put_body = json.dumps(kw... | <|body_start_0|>
url = 'os-services'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
schema = self.get_schema(self.schema_versions_info)
self.validate_response(schema.list_services, resp, body)
retu... | Client class to send CRUD Volume Services API requests | ServicesClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesClient:
"""Client class to send CRUD Volume Services API requests"""
def list_services(self, **params):
"""List all Cinder services. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#list-... | stack_v2_sparse_classes_36k_train_012848 | 4,477 | permissive | [
{
"docstring": "List all Cinder services. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#list-all-cinder-services",
"name": "list_services",
"signature": "def list_services(self, **params)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_train_013929 | Implement the Python class `ServicesClient` described below.
Class description:
Client class to send CRUD Volume Services API requests
Method signatures and docstrings:
- def list_services(self, **params): List all Cinder services. For a full list of available parameters, please refer to the official API reference: h... | Implement the Python class `ServicesClient` described below.
Class description:
Client class to send CRUD Volume Services API requests
Method signatures and docstrings:
- def list_services(self, **params): List all Cinder services. For a full list of available parameters, please refer to the official API reference: h... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class ServicesClient:
"""Client class to send CRUD Volume Services API requests"""
def list_services(self, **params):
"""List all Cinder services. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#list-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServicesClient:
"""Client class to send CRUD Volume Services API requests"""
def list_services(self, **params):
"""List all Cinder services. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/block-storage/v3/#list-all-cinder-se... | the_stack_v2_python_sparse | tempest/lib/services/volume/v3/services_client.py | openstack/tempest | train | 270 |
3883f3cc197a9d057f224cfd7c288049048629d8 | [
"if model._meta.app_label == 'auditoria':\n return 'logs'\nreturn None",
"if model._meta.app_label == 'auditoria':\n return 'logs'\nreturn None",
"if obj1._meta.app_label == 'auditoria' or obj2._meta.app_label == 'auditoria':\n return True\nreturn None",
"if app_label == 'auditoria':\n return db =... | <|body_start_0|>
if model._meta.app_label == 'auditoria':
return 'logs'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'auditoria':
return 'logs'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label == 'auditoria' ... | A router to control all database operations on models in the auditoria application. | LogRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogRouter:
"""A router to control all database operations on models in the auditoria application."""
def db_for_read(self, model, **hints):
"""Attempts to read AuditoriaLog models go to logs."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to wr... | stack_v2_sparse_classes_36k_train_012849 | 1,118 | no_license | [
{
"docstring": "Attempts to read AuditoriaLog models go to logs.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write AuditoriaLog models go to logs.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hint... | 4 | stack_v2_sparse_classes_30k_train_004385 | Implement the Python class `LogRouter` described below.
Class description:
A router to control all database operations on models in the auditoria application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read AuditoriaLog models go to logs.
- def db_for_write(self, model, **h... | Implement the Python class `LogRouter` described below.
Class description:
A router to control all database operations on models in the auditoria application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read AuditoriaLog models go to logs.
- def db_for_write(self, model, **h... | 16b04f9c3e520f7ca54a1cc28ede3e1e533a33a5 | <|skeleton|>
class LogRouter:
"""A router to control all database operations on models in the auditoria application."""
def db_for_read(self, model, **hints):
"""Attempts to read AuditoriaLog models go to logs."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to wr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogRouter:
"""A router to control all database operations on models in the auditoria application."""
def db_for_read(self, model, **hints):
"""Attempts to read AuditoriaLog models go to logs."""
if model._meta.app_label == 'auditoria':
return 'logs'
return None
de... | the_stack_v2_python_sparse | huellas/auditoria/dbrouters.py | MarioPayan/asdasdwqe | train | 0 |
79cfcb47cb5967c39a581c2bd465d37009afe7d7 | [
"query = {}\nif len(args) > 0:\n query.update(args[0])\nquery.update(kwargs)\nquery.update({'role': ROLES.ISSUE})\nissues = content_objects.filter(type=Container, **query).mapOnExecute(Issue)\nreturn issues",
"query = {}\nif len(args) > 0:\n query.update(args[0])\nquery.update(kwargs)\nquery.update({'role':... | <|body_start_0|>
query = {}
if len(args) > 0:
query.update(args[0])
query.update(kwargs)
query.update({'role': ROLES.ISSUE})
issues = content_objects.filter(type=Container, **query).mapOnExecute(Issue)
return issues
<|end_body_0|>
<|body_start_1|>
que... | Public: A model that corresponds to a Container with `role='publication'`. | Publication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Publication:
"""Public: A model that corresponds to a Container with `role='publication'`."""
def issues(self, *args, **kwargs):
"""Public: load the Issues that belong to the Publication instance from the API, filtered by the specified arguments. args - (optional) A single dict to us... | stack_v2_sparse_classes_36k_train_012850 | 7,379 | no_license | [
{
"docstring": "Public: load the Issues that belong to the Publication instance from the API, filtered by the specified arguments. args - (optional) A single dict to use for the query, allowing for query keys that cannot be used as keywoard arguments. kwargs - (optional) Keyword arguments that are added to the ... | 2 | stack_v2_sparse_classes_30k_train_015459 | Implement the Python class `Publication` described below.
Class description:
Public: A model that corresponds to a Container with `role='publication'`.
Method signatures and docstrings:
- def issues(self, *args, **kwargs): Public: load the Issues that belong to the Publication instance from the API, filtered by the s... | Implement the Python class `Publication` described below.
Class description:
Public: A model that corresponds to a Container with `role='publication'`.
Method signatures and docstrings:
- def issues(self, *args, **kwargs): Public: load the Issues that belong to the Publication instance from the API, filtered by the s... | 69f003813cc1750379127948afbfd1db00e8ef0d | <|skeleton|>
class Publication:
"""Public: A model that corresponds to a Container with `role='publication'`."""
def issues(self, *args, **kwargs):
"""Public: load the Issues that belong to the Publication instance from the API, filtered by the specified arguments. args - (optional) A single dict to us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Publication:
"""Public: A model that corresponds to a Container with `role='publication'`."""
def issues(self, *args, **kwargs):
"""Public: load the Issues that belong to the Publication instance from the API, filtered by the specified arguments. args - (optional) A single dict to use for the que... | the_stack_v2_python_sparse | app/models.py | marquee/runtime | train | 0 |
a1a9bbed552af6dd4277c1ff5cc041f4dcb5f25f | [
"self.entity_description = description\nself.data = data\nself._camera = data.cameras[camera]\nself._attr_unique_id = f'{self._camera.serial}-{description.key}'\nself._sensor_key = 'temperature_calibrated' if description.key == 'temperature' else description.key\nself._attr_device_info = DeviceInfo(identifiers={(DO... | <|body_start_0|>
self.entity_description = description
self.data = data
self._camera = data.cameras[camera]
self._attr_unique_id = f'{self._camera.serial}-{description.key}'
self._sensor_key = 'temperature_calibrated' if description.key == 'temperature' else description.key
... | A Blink camera sensor. | BlinkSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlinkSensor:
"""A Blink camera sensor."""
def __init__(self, data, camera, description: SensorEntityDescription) -> None:
"""Initialize sensors from Blink camera."""
<|body_0|>
def update(self) -> None:
"""Retrieve sensor data from the camera."""
<|body_1... | stack_v2_sparse_classes_36k_train_012851 | 3,039 | permissive | [
{
"docstring": "Initialize sensors from Blink camera.",
"name": "__init__",
"signature": "def __init__(self, data, camera, description: SensorEntityDescription) -> None"
},
{
"docstring": "Retrieve sensor data from the camera.",
"name": "update",
"signature": "def update(self) -> None"
... | 2 | null | Implement the Python class `BlinkSensor` described below.
Class description:
A Blink camera sensor.
Method signatures and docstrings:
- def __init__(self, data, camera, description: SensorEntityDescription) -> None: Initialize sensors from Blink camera.
- def update(self) -> None: Retrieve sensor data from the camera... | Implement the Python class `BlinkSensor` described below.
Class description:
A Blink camera sensor.
Method signatures and docstrings:
- def __init__(self, data, camera, description: SensorEntityDescription) -> None: Initialize sensors from Blink camera.
- def update(self) -> None: Retrieve sensor data from the camera... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BlinkSensor:
"""A Blink camera sensor."""
def __init__(self, data, camera, description: SensorEntityDescription) -> None:
"""Initialize sensors from Blink camera."""
<|body_0|>
def update(self) -> None:
"""Retrieve sensor data from the camera."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlinkSensor:
"""A Blink camera sensor."""
def __init__(self, data, camera, description: SensorEntityDescription) -> None:
"""Initialize sensors from Blink camera."""
self.entity_description = description
self.data = data
self._camera = data.cameras[camera]
self._at... | the_stack_v2_python_sparse | homeassistant/components/blink/sensor.py | home-assistant/core | train | 35,501 |
92a26ea192637dcdf422b462a446a22806887140 | [
"super().__init__()\nself.image_conv = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.kspace_conv = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.forward_operator = forward_operator\nself.backward_operator = backward_operator... | <|body_start_0|>
super().__init__()
self.image_conv = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.kspace_conv = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.forward_operator = forward_operator
... | MultiDomainConvTranspose2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiDomainConvTranspose2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConvTranspose2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Call... | stack_v2_sparse_classes_36k_train_012852 | 11,794 | permissive | [
{
"docstring": "Inits :class:`MultiDomainConvTranspose2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_channels: int Number of input channels. out_channels: int Number of output channels.",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_001416 | Implement the Python class `MultiDomainConvTranspose2d` described below.
Class description:
Implement the MultiDomainConvTranspose2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`Mult... | Implement the Python class `MultiDomainConvTranspose2d` described below.
Class description:
Implement the MultiDomainConvTranspose2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`Mult... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class MultiDomainConvTranspose2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConvTranspose2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiDomainConvTranspose2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConvTranspose2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward ... | the_stack_v2_python_sparse | direct/nn/multidomainnet/multidomain.py | NKI-AI/direct | train | 151 | |
93fcea611e99e3137b1b6047c362ac72cb988275 | [
"args = self.get_args.parse_args()\nnum_rows = args.get('rows') or 100\nquery = g.db.query(Machine)\nif args.get('realm', None) not in ('aws', 'local'):\n abort(http_client.BAD_REQUEST, description=\"realm must be 'aws' or 'local'\")\nif args['realm'] == 'local':\n query = query.filter(Machine.realm == 'local... | <|body_start_0|>
args = self.get_args.parse_args()
num_rows = args.get('rows') or 100
query = g.db.query(Machine)
if args.get('realm', None) not in ('aws', 'local'):
abort(http_client.BAD_REQUEST, description="realm must be 'aws' or 'local'")
if args['realm'] == 'loca... | The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new publicIP address for example, it will ge... | MachinesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachinesAPI:
"""The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new p... | stack_v2_sparse_classes_36k_train_012853 | 8,672 | permissive | [
{
"docstring": "Get a list of machines",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Register a machine",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006034 | Implement the Python class `MachinesAPI` described below.
Class description:
The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post ... | Implement the Python class `MachinesAPI` described below.
Class description:
The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post ... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class MachinesAPI:
"""The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MachinesAPI:
"""The interface to battleserver machines. Each physical machine (for example ec2 instance) has a machine resource here. Each machine resource has zero or more battleserver resources. A machine is defined as a set of the parameters for the post call below. If an instance gets a new publicIP addre... | the_stack_v2_python_sparse | driftbase/api/machines.py | dgnorth/drift-base | train | 1 |
f1bc5d26f3ffecb5a68d1b8af313a27eb5cb1798 | [
"self.date1 = datetime.date(2011, 1, 1)\nself.date2 = datetime.date(2011, 1, 2)\nself.date3 = datetime.date(2011, 1, 3)\nself.test_user = create_test_user()\nself.boiler_obj = create_test_boiler(self.test_user)\nself.fuel_info1 = FuelInfo.objects.create(boiler=self.boiler_obj, creator=self.test_user, type='Coal')\n... | <|body_start_0|>
self.date1 = datetime.date(2011, 1, 1)
self.date2 = datetime.date(2011, 1, 2)
self.date3 = datetime.date(2011, 1, 3)
self.test_user = create_test_user()
self.boiler_obj = create_test_boiler(self.test_user)
self.fuel_info1 = FuelInfo.objects.create(boiler=... | FuelRemainsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
<|body_0|>
def tearDown(self):
"""Post-execution"""
<|body_1|>
def test_creation(self):
"""1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.5) 2. Созд... | stack_v2_sparse_classes_36k_train_012854 | 14,802 | no_license | [
{
"docstring": "Pre-execution",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Post-execution",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.... | 4 | stack_v2_sparse_classes_30k_train_014860 | Implement the Python class `FuelRemainsTest` described below.
Class description:
Implement the FuelRemainsTest class.
Method signatures and docstrings:
- def setUp(self): Pre-execution
- def tearDown(self): Post-execution
- def test_creation(self): 1. Создаем объект остатоков на первый день месяца (остатки топлива на... | Implement the Python class `FuelRemainsTest` described below.
Class description:
Implement the FuelRemainsTest class.
Method signatures and docstrings:
- def setUp(self): Pre-execution
- def tearDown(self): Post-execution
- def test_creation(self): 1. Создаем объект остатоков на первый день месяца (остатки топлива на... | 016c3e5ad4099d6e1dbff42fd414f5fedd4d8530 | <|skeleton|>
class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
<|body_0|>
def tearDown(self):
"""Post-execution"""
<|body_1|>
def test_creation(self):
"""1. Создаем объект остатоков на первый день месяца (остатки топлива на 1е число месяца = 10.5) 2. Созд... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FuelRemainsTest:
def setUp(self):
"""Pre-execution"""
self.date1 = datetime.date(2011, 1, 1)
self.date2 = datetime.date(2011, 1, 2)
self.date3 = datetime.date(2011, 1, 3)
self.test_user = create_test_user()
self.boiler_obj = create_test_boiler(self.test_user)
... | the_stack_v2_python_sparse | src/dailyreport/fuel/tests.py | johnsky/dailyreport-server | train | 0 | |
6479c06810459e14a4eccaebfa64d5cafab14b76 | [
"prev_min = prev_max = global_max = nums[0]\nfor num in nums[1:]:\n minn, maxx = (min(num, prev_max * num, prev_min * num), max(num, prev_max * num, prev_min * num))\n prev_min, prev_max, global_max = (minn, maxx, max(global_max, maxx))\nreturn global_max",
"front_max = front_min = global_max = nums[0]\nfor... | <|body_start_0|>
prev_min = prev_max = global_max = nums[0]
for num in nums[1:]:
minn, maxx = (min(num, prev_max * num, prev_min * num), max(num, prev_max * num, prev_min * num))
prev_min, prev_max, global_max = (minn, maxx, max(global_max, maxx))
return global_max
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxProduct_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxProduct_2(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_012855 | 3,237 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxProduct_1",
"signature": "def maxProduct_1(self, nums)"
},
{
"docstring": ":type nums: List[int] ... | 4 | stack_v2_sparse_classes_30k_train_010808 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): :type nums: List[int] :rtype: int
- def maxProduct_1(self, nums): :type nums: List[int] :rtype: int
- def maxProduct_2(self, nums): :type nums: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): :type nums: List[int] :rtype: int
- def maxProduct_1(self, nums): :type nums: List[int] :rtype: int
- def maxProduct_2(self, nums): :type nums: List[i... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxProduct_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def maxProduct_2(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, nums):
""":type nums: List[int] :rtype: int"""
prev_min = prev_max = global_max = nums[0]
for num in nums[1:]:
minn, maxx = (min(num, prev_max * num, prev_min * num), max(num, prev_max * num, prev_min * num))
prev_min, prev_max, gl... | the_stack_v2_python_sparse | Solutions/0152_maxProduct.py | YoupengLi/leetcode-sorting | train | 3 | |
ca74ca63928e7b210aeba68e237112bbc2cdda20 | [
"self.n = n\nself.colors = colors\nself.alpha = 0.4\ntheta = np.linspace(0, 2 * np.pi, n, endpoint=False) + vertex_0_theta\nself.vertex = np.stack([np.cos(theta), np.sin(theta)])",
"if not cliques:\n return\nfor s in cliques:\n v = radius * self.vertex[:, list(s)] + np.array([center]).T\n plt.fill(v[0, :... | <|body_start_0|>
self.n = n
self.colors = colors
self.alpha = 0.4
theta = np.linspace(0, 2 * np.pi, n, endpoint=False) + vertex_0_theta
self.vertex = np.stack([np.cos(theta), np.sin(theta)])
<|end_body_0|>
<|body_start_1|>
if not cliques:
return
for s... | Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot. | CliqueFigure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set ... | stack_v2_sparse_classes_36k_train_012856 | 7,114 | permissive | [
{
"docstring": "n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set vertex_0_theta: angle at which to place vertex 0 FIXME - include radius here? - add method to show which edge was zeroed out?",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_val_001122 | Implement the Python class `CliqueFigure` described below.
Class description:
Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot.
Method signatures and docstrings:
- def __init__(self, n, colors, vertex_0_theta): n: number of vertices in each graph colors: hash from sets (de... | Implement the Python class `CliqueFigure` described below.
Class description:
Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot.
Method signatures and docstrings:
- def __init__(self, n, colors, vertex_0_theta): n: number of vertices in each graph colors: hash from sets (de... | ae7b736d5199085e6b4d0aadd7c05467920cc20e | <|skeleton|>
class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set vertex_0_thet... | the_stack_v2_python_sparse | countingBound/py/figure/zeroing.py | joshtburdick/misc | train | 0 |
7ba7334325f03fc5074fd3b9b1bd73721d7968db | [
"low, high = (1, len(nums) - 1)\nwhile low <= high:\n mid = low + high >> 1\n cnt = sum((x <= mid for x in nums))\n if cnt > mid:\n high = mid - 1\n else:\n low = mid + 1\nreturn low",
"slow, fast = (nums[0], nums[0])\nwhile True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n ... | <|body_start_0|>
low, high = (1, len(nums) - 1)
while low <= high:
mid = low + high >> 1
cnt = sum((x <= mid for x in nums))
if cnt > mid:
high = mid - 1
else:
low = mid + 1
return low
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate_v3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findDuplicate_v1(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k_train_012857 | 15,812 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate_v3",
"signature": "def findDuplicate_v3(self, nums)"
},
{
"docstring": ":type nu... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate_v3(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate_v1(self, nums): :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate_v3(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate_v1(self, nums): :type n... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate_v3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findDuplicate_v1(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
low, high = (1, len(nums) - 1)
while low <= high:
mid = low + high >> 1
cnt = sum((x <= mid for x in nums))
if cnt > mid:
high = mid - 1
else... | the_stack_v2_python_sparse | python/287_Find_the_Duplicate_Number.py | Moby5/myleetcode | train | 2 | |
07565e7a7081f8856862b6478fe0dec958f4aed8 | [
"if isinstance(config, dict):\n config = LambdaConfig.parse_obj(config)\nconfig = cast(LambdaConfig, config)\nsuper().__init__(config)\nself.blocking_features = config.blocking_features\nself.mylambda = config.Lambda\nself.bf_len = config.bloom_filter_length\nself.num_hash_function = config.number_of_hash_functi... | <|body_start_0|>
if isinstance(config, dict):
config = LambdaConfig.parse_obj(config)
config = cast(LambdaConfig, config)
super().__init__(config)
self.blocking_features = config.blocking_features
self.mylambda = config.Lambda
self.bf_len = config.bloom_filter... | Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking method. | PPRLIndexLambdaFold | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PPRLIndexLambdaFold:
"""Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking method."""
def __init__(self, config:... | stack_v2_sparse_classes_36k_train_012858 | 3,639 | permissive | [
{
"docstring": "Initialize the class and set the required parameters. :param config: Configuration for P-Sig reverted index.",
"name": "__init__",
"signature": "def __init__(self, config: Union[LambdaConfig, Dict])"
},
{
"docstring": "Convert a record to list of bigrams and then map to a bloom f... | 3 | stack_v2_sparse_classes_30k_train_001191 | Implement the Python class `PPRLIndexLambdaFold` described below.
Class description:
Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking met... | Implement the Python class `PPRLIndexLambdaFold` described below.
Class description:
Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking met... | edfd26fbef398b48f464f68453b815ea442a5cdd | <|skeleton|>
class PPRLIndexLambdaFold:
"""Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking method."""
def __init__(self, config:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PPRLIndexLambdaFold:
"""Class that implements the PPRL indexing technique: An LSH-Based Blocking Approach with a Homomorphic Matching Technique for Privacy-Preserving Record Linkage. This class includes an implementation of Lambda-fold redundant blocking method."""
def __init__(self, config: Union[Lambda... | the_stack_v2_python_sparse | blocklib/pprllambdafold.py | data61/blocklib | train | 21 |
5c89dd72f82519ccefbcd48bf30935519ead0ae3 | [
"SlipTimeFn.__init__(self, name)\nModuleBruneSlipFn.__init__(self)\nself._loggingPrefix = 'BrSF '\nreturn",
"SlipTimeFn._configure(self)\nModuleBruneSlipFn.dbFinalSlip(self, self.inventory.dbSlip)\nModuleBruneSlipFn.dbSlipTime(self, self.inventory.dbSlipTime)\nModuleBruneSlipFn.dbRiseTime(self, self.inventory.dbR... | <|body_start_0|>
SlipTimeFn.__init__(self, name)
ModuleBruneSlipFn.__init__(self)
self._loggingPrefix = 'BrSF '
return
<|end_body_0|>
<|body_start_1|>
SlipTimeFn._configure(self)
ModuleBruneSlipFn.dbFinalSlip(self, self.inventory.dbSlip)
ModuleBruneSlipFn.dbSlipT... | Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial database of rise time Factory: slip_time_fn | BruneSlipFn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial databas... | stack_v2_sparse_classes_36k_train_012859 | 2,807 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, name='bruneslipfn')"
},
{
"docstring": "Setup members using inventory.",
"name": "_configure",
"signature": "def _configure(self)"
}
] | 2 | null | Implement the Python class `BruneSlipFn` described below.
Class description:
Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiati... | Implement the Python class `BruneSlipFn` described below.
Class description:
Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiati... | 67bfe2e75e0a20bb55c93eb98bef7a9b3694523a | <|skeleton|>
class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial databas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial database of rise tim... | the_stack_v2_python_sparse | pylith/faults/obsolete/BruneSlipFn.py | fjiaqi/pylith | train | 0 |
08c10a8467f8798cf6787a78f50a1f608a55969c | [
"if segment_ids.size == 0:\n return []\nK = max(segment_ids) + 1\noutputs = [np.zeros((np.count_nonzero(segment_ids == seg_id),) + data.shape[1:], dtype=data.dtype) for seg_id in range(0, K)]\ncounts = np.zeros(K, dtype=int)\nfor i, seg_id in enumerate(segment_ids):\n data_idx = i if indices is None else indi... | <|body_start_0|>
if segment_ids.size == 0:
return []
K = max(segment_ids) + 1
outputs = [np.zeros((np.count_nonzero(segment_ids == seg_id),) + data.shape[1:], dtype=data.dtype) for seg_id in range(0, K)]
counts = np.zeros(K, dtype=int)
for i, seg_id in enumerate(segme... | SegmentsTester | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentsTester:
def split(self, data, segment_ids, indices=None):
"""Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indic... | stack_v2_sparse_classes_36k_train_012860 | 23,854 | permissive | [
{
"docstring": "Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indices, returns K outputs, each one containing data entries corresponding to one ... | 2 | null | Implement the Python class `SegmentsTester` described below.
Class description:
Implement the SegmentsTester class.
Method signatures and docstrings:
- def split(self, data, segment_ids, indices=None): Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 ... | Implement the Python class `SegmentsTester` described below.
Class description:
Implement the SegmentsTester class.
Method signatures and docstrings:
- def split(self, data, segment_ids, indices=None): Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 ... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class SegmentsTester:
def split(self, data, segment_ids, indices=None):
"""Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentsTester:
def split(self, data, segment_ids, indices=None):
"""Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indices, returns K ... | the_stack_v2_python_sparse | pytorch/source/caffe2/python/operator_test/segment_ops_test.py | ryfeus/lambda-packs | train | 1,283 | |
f3ba4cc5e165c68972ebb18c7012d65001af3e4b | [
"if not prices:\n return 0\nn = len(prices)\ndp0 = 0\ndp1 = -prices[0]\nfor i in range(1, n):\n dp0 = max(dp0, dp1 + prices[i])\n dp1 = max(dp1, dp0 - prices[i])\nreturn dp0",
"if not prices:\n return 0\nn = len(prices)\nif k > n / 2:\n return self.maxProfit_inf(prices)\ndp = [[[0 for _ in range(2)... | <|body_start_0|>
if not prices:
return 0
n = len(prices)
dp0 = 0
dp1 = -prices[0]
for i in range(1, n):
dp0 = max(dp0, dp1 + prices[i])
dp1 = max(dp1, dp0 - prices[i])
return dp0
<|end_body_0|>
<|body_start_1|>
if not prices:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit_inf(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not prices:
... | stack_v2_sparse_classes_36k_train_012861 | 1,101 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_inf",
"signature": "def maxProfit_inf(self, prices)"
},
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, k, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_inf(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_inf(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int
<|skeleton|>
class Soluti... | 013f6f222c6c2a617787b258f8a37003a9f51526 | <|skeleton|>
class Solution:
def maxProfit_inf(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit_inf(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
n = len(prices)
dp0 = 0
dp1 = -prices[0]
for i in range(1, n):
dp0 = max(dp0, dp1 + prices[i])
dp1 = max(dp1, dp0 - p... | the_stack_v2_python_sparse | dp/stock4.py | terrifyzhao/leetcode | train | 0 | |
7403a6745d4f0b45769925d214ac0e15b43587d4 | [
"params = kwarg['params']\ncmd = 'dnsmasq {} '.format(command)\nreturn cmd",
"params = kwarg['params']\ncmd = 'dnsmasq {} '.format(command)\nreturn cmd"
] | <|body_start_0|>
params = kwarg['params']
cmd = 'dnsmasq {} '.format(command)
return cmd
<|end_body_0|>
<|body_start_1|>
params = kwarg['params']
cmd = 'dnsmasq {} '.format(command)
return cmd
<|end_body_1|>
| dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]... | LinuxDnsmasqImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinuxDnsmasqImpl:
"""dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]..."""
def format_test(self, command, *argv, **kwarg):
"""--test - Read and syntax check configuration ... | stack_v2_sparse_classes_36k_train_012862 | 1,083 | permissive | [
{
"docstring": "--test - Read and syntax check configuration file(s). Exit with code 0 if all is OK, or a non-zero code otherwise. Do not start up dnsmasq.",
"name": "format_test",
"signature": "def format_test(self, command, *argv, **kwarg)"
},
{
"docstring": "--test - Read and syntax check con... | 2 | null | Implement the Python class `LinuxDnsmasqImpl` described below.
Class description:
dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]...
Method signatures and docstrings:
- def format_test(self, command, *argv... | Implement the Python class `LinuxDnsmasqImpl` described below.
Class description:
dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]...
Method signatures and docstrings:
- def format_test(self, command, *argv... | e4c8221e18cd94e7424c30e12eb0fb82f7767267 | <|skeleton|>
class LinuxDnsmasqImpl:
"""dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]..."""
def format_test(self, command, *argv, **kwarg):
"""--test - Read and syntax check configuration ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinuxDnsmasqImpl:
"""dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN. dnsmasq [OPTION]..."""
def format_test(self, command, *argv, **kwarg):
"""--test - Read and syntax check configuration file(s). Exit... | the_stack_v2_python_sparse | Amazon_Framework/DentOsTestbedLib/src/dent_os_testbed/lib/dnsmasq/linux/linux_dnsmasq_impl.py | tld3daniel/testing | train | 0 |
5762f256dc366fd4f990c4aab5d2940aa6ff5eb2 | [
"super(MeasureBeforeSuccessScenario, self).__init__(egp=egp, request_cycle=request_cycle, request_prob=request_prob, min_pairs=min_pairs, max_pairs=max_pairs, min_fidelity=min_fidelity, tmax_pair=tmax_pair, num_requests=num_requests, purpose_id=purpose_id, priority=priority, store=store, atomic=atomic, measure_dire... | <|body_start_0|>
super(MeasureBeforeSuccessScenario, self).__init__(egp=egp, request_cycle=request_cycle, request_prob=request_prob, min_pairs=min_pairs, max_pairs=max_pairs, min_fidelity=min_fidelity, tmax_pair=tmax_pair, num_requests=num_requests, purpose_id=purpose_id, priority=priority, store=store, atomic=... | MeasureBeforeSuccessScenario | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasureBeforeSuccessScenario:
def __init__(self, egp, request_cycle, request_prob=1, min_pairs=1, max_pairs=1, min_fidelity=0.2, tmax_pair=0, num_requests=0, purpose_id=1, priority=10, store=False, atomic=False, t0=0):
"""Scenario for when spin is measured directly after photon is emitte... | stack_v2_sparse_classes_36k_train_012863 | 23,433 | permissive | [
{
"docstring": "Scenario for when spin is measured directly after photon is emitted, i.e. before messages is returned from midpoint. The classical information from the choice of measurement basis and measurement outcome can be used to compute QubErr and/or produce key. i EGP simulation scenario that schedules c... | 3 | stack_v2_sparse_classes_30k_train_017313 | Implement the Python class `MeasureBeforeSuccessScenario` described below.
Class description:
Implement the MeasureBeforeSuccessScenario class.
Method signatures and docstrings:
- def __init__(self, egp, request_cycle, request_prob=1, min_pairs=1, max_pairs=1, min_fidelity=0.2, tmax_pair=0, num_requests=0, purpose_id... | Implement the Python class `MeasureBeforeSuccessScenario` described below.
Class description:
Implement the MeasureBeforeSuccessScenario class.
Method signatures and docstrings:
- def __init__(self, egp, request_cycle, request_prob=1, min_pairs=1, max_pairs=1, min_fidelity=0.2, tmax_pair=0, num_requests=0, purpose_id... | 552f4b59d4deb5e838b21d569b5c4fd835fa1494 | <|skeleton|>
class MeasureBeforeSuccessScenario:
def __init__(self, egp, request_cycle, request_prob=1, min_pairs=1, max_pairs=1, min_fidelity=0.2, tmax_pair=0, num_requests=0, purpose_id=1, priority=10, store=False, atomic=False, t0=0):
"""Scenario for when spin is measured directly after photon is emitte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasureBeforeSuccessScenario:
def __init__(self, egp, request_cycle, request_prob=1, min_pairs=1, max_pairs=1, min_fidelity=0.2, tmax_pair=0, num_requests=0, purpose_id=1, priority=10, store=False, atomic=False, t0=0):
"""Scenario for when spin is measured directly after photon is emitted, i.e. before... | the_stack_v2_python_sparse | qlinklayer/scenario.py | SoftwareQuTech/QLinkLayerSimulations | train | 9 | |
c309be587f0d851a2ce651bdb52055279a6cfdc1 | [
"super().__init__()\nif cost_objective is None:\n if cost_model.num_outputs == 1:\n cost_objective = IdentityMCObjective()\n else:\n cost_objective = GenericMCObjective(lambda Y, X: Y.sum(dim=-1))\nself.cost_model = cost_model\nself.cost_objective = cost_objective\nself._use_mean = use_mean\nsel... | <|body_start_0|>
super().__init__()
if cost_objective is None:
if cost_model.num_outputs == 1:
cost_objective = IdentityMCObjective()
else:
cost_objective = GenericMCObjective(lambda Y, X: Y.sum(dim=-1))
self.cost_model = cost_model
... | A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean `mean_cost` of the cost model, i.e. `weighted utility = mean(U) / mean_cost`. If `use_mean=F... | InverseCostWeightedUtility | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InverseCostWeightedUtility:
"""A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean `mean_cost` of the cost model, i.e. `w... | stack_v2_sparse_classes_36k_train_012864 | 8,906 | permissive | [
{
"docstring": "Cost-aware utility that weights increase in utiltiy by inverse cost. Args: cost_model: A model of the cost of evaluating a candidate set `X`, where `X` are the same features as in the model for the acquisition function this is to be used with. If no cost_objective is specified, the outputs are r... | 2 | null | Implement the Python class `InverseCostWeightedUtility` described below.
Class description:
A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean... | Implement the Python class `InverseCostWeightedUtility` described below.
Class description:
A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class InverseCostWeightedUtility:
"""A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean `mean_cost` of the cost model, i.e. `w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InverseCostWeightedUtility:
"""A cost-aware utility using inverse cost weighting based on a model. Computes the cost-aware utility by inverse-weighting samples `U = (u_1, ..., u_N)` of the increase in utility. If `use_mean=True`, this uses the posterior mean `mean_cost` of the cost model, i.e. `weighted utili... | the_stack_v2_python_sparse | botorch/acquisition/cost_aware.py | pytorch/botorch | train | 2,891 |
f25920ceeaff98fe2013ffa342aa2c3d49d346f6 | [
"super(FilteredLineDataProvider, self).__init__(source, **kwargs)\nself.strip_lines = strip_lines\nself.strip_newlines = strip_newlines\nself.provide_blank = provide_blank\nself.comment_char = comment_char",
"if line is not None:\n if self.strip_lines:\n line = line.strip()\n elif self.strip_newlines... | <|body_start_0|>
super(FilteredLineDataProvider, self).__init__(source, **kwargs)
self.strip_lines = strip_lines
self.strip_newlines = strip_newlines
self.provide_blank = provide_blank
self.comment_char = comment_char
<|end_body_0|>
<|body_start_1|>
if line is not None:
... | Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return. | FilteredLineDataProvider | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteredLineDataProvider:
"""Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return."""
def __init__(self, source, strip_lines=True, strip_newlines=False, provide_blank=False, comment_char=DEFAULT_COMMENT_CHA... | stack_v2_sparse_classes_36k_train_012865 | 9,672 | permissive | [
{
"docstring": ":param strip_lines: remove whitespace from the beginning an ending of each line (or not). Optional: defaults to True :type strip_lines: bool :param strip_newlines: remove newlines only (only functions when ``strip_lines`` is false) Optional: defaults to False :type strip_lines: bool :param provi... | 2 | null | Implement the Python class `FilteredLineDataProvider` described below.
Class description:
Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return.
Method signatures and docstrings:
- def __init__(self, source, strip_lines=True, strip_n... | Implement the Python class `FilteredLineDataProvider` described below.
Class description:
Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return.
Method signatures and docstrings:
- def __init__(self, source, strip_lines=True, strip_n... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class FilteredLineDataProvider:
"""Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return."""
def __init__(self, source, strip_lines=True, strip_newlines=False, provide_blank=False, comment_char=DEFAULT_COMMENT_CHA... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilteredLineDataProvider:
"""Data provider that yields lines of data from its source allowing optional control over which line to start on and how many lines to return."""
def __init__(self, source, strip_lines=True, strip_newlines=False, provide_blank=False, comment_char=DEFAULT_COMMENT_CHAR, **kwargs):... | the_stack_v2_python_sparse | lib/galaxy/datatypes/dataproviders/line.py | bwlang/galaxy | train | 0 |
34d35f0c80c9909be9550bcd9aebd32189f9a9ba | [
"def serializeHelper(node):\n if not node:\n vals.append('#')\n else:\n vals.append(str(node.val))\n serializeHelper(node.left)\n serializeHelper(node.right)\nvals = []\nserializeHelper(root)\nreturn ' '.join(vals)",
"def deserializeHelper():\n val = next(vals)\n if val == ... | <|body_start_0|>
def serializeHelper(node):
if not node:
vals.append('#')
else:
vals.append(str(node.val))
serializeHelper(node.left)
serializeHelper(node.right)
vals = []
serializeHelper(root)
return... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_012866 | 9,842 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def serializeHelper(node):
if not node:
vals.append('#')
else:
vals.append(str(node.val))
serializeHelper(node.lef... | the_stack_v2_python_sparse | cs15211/SerializeandDeserializeBinaryTree.py | JulyKikuAkita/PythonPrac | train | 1 | |
ea4e446001cbff70b872e5742f86aad87d67f76e | [
"self.class_name = class_name.lower()\ntry:\n if _req.json is not None:\n self.parse.json = _req.json\n if bool(_req.form):\n self.parse.form = _req.form.to_dict(flat=False)\n if bool(_req.files):\n self.parse.file = _req.files.to_dict(flat=False)\n if bool(_req.args):\n ... | <|body_start_0|>
self.class_name = class_name.lower()
try:
if _req.json is not None:
self.parse.json = _req.json
if bool(_req.form):
self.parse.form = _req.form.to_dict(flat=False)
if bool(_req.files):
self.parse... | Requests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requests:
def __init__(self, class_name):
"""## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and validation for incoming requests."""
<|body_0|>
def validation(self, csrf_enable=True, **k... | stack_v2_sparse_classes_36k_train_012867 | 4,554 | permissive | [
{
"docstring": "## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and validation for incoming requests.",
"name": "__init__",
"signature": "def __init__(self, class_name)"
},
{
"docstring": "## validation :para... | 2 | stack_v2_sparse_classes_30k_train_005141 | Implement the Python class `Requests` described below.
Class description:
Implement the Requests class.
Method signatures and docstrings:
- def __init__(self, class_name): ## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and valida... | Implement the Python class `Requests` described below.
Class description:
Implement the Requests class.
Method signatures and docstrings:
- def __init__(self, class_name): ## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and valida... | a9a9ddc284a12618a93febe238f12a71f95dd9f1 | <|skeleton|>
class Requests:
def __init__(self, class_name):
"""## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and validation for incoming requests."""
<|body_0|>
def validation(self, csrf_enable=True, **k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Requests:
def __init__(self, class_name):
"""## Requests [ID] Class ini berguna untuk melakukan parsing dan validasi terhadap requests yang masuk. [EN] This class is used to parsed and validation for incoming requests."""
self.class_name = class_name.lower()
try:
if _req.js... | the_stack_v2_python_sparse | metric/app/resource.py | metric-python/metric | train | 1 | |
fa8c85e32cb877e06d1df3183a229012768b1197 | [
"self.CsvLocations = []\nself.ApiLocations = []\nself.columns = ['Address', 'Key', 'URL', 'Location']\nself.ApiURL = 'https://www.vaccinespotter.org/api/v0/stores/WA/pharmaca.json'\nself.csvFile = 'PharmacaLoc.csv'\nself.headers = {'if-modified-since': '<DATE_STRING>'}\nself.ReadLocations()",
"now = datetime.utcn... | <|body_start_0|>
self.CsvLocations = []
self.ApiLocations = []
self.columns = ['Address', 'Key', 'URL', 'Location']
self.ApiURL = 'https://www.vaccinespotter.org/api/v0/stores/WA/pharmaca.json'
self.csvFile = 'PharmacaLoc.csv'
self.headers = {'if-modified-since': '<DATE_S... | wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location | PharmacaWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PharmacaWrapper:
"""wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location"""
def __init__(self):
"""initialize the Pharmaca class and call a method to load the csv with different location data"""
<|body_0|>
def ReadLoca... | stack_v2_sparse_classes_36k_train_012868 | 3,430 | permissive | [
{
"docstring": "initialize the Pharmaca class and call a method to load the csv with different location data",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "open the csv storing location data and read into self.CsvLocations. Also call the API to read availability infor... | 3 | null | Implement the Python class `PharmacaWrapper` described below.
Class description:
wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location
Method signatures and docstrings:
- def __init__(self): initialize the Pharmaca class and call a method to load the csv with differ... | Implement the Python class `PharmacaWrapper` described below.
Class description:
wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location
Method signatures and docstrings:
- def __init__(self): initialize the Pharmaca class and call a method to load the csv with differ... | 28248155c136f9b267f0ada7749d30848de0981f | <|skeleton|>
class PharmacaWrapper:
"""wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location"""
def __init__(self):
"""initialize the Pharmaca class and call a method to load the csv with different location data"""
<|body_0|>
def ReadLoca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PharmacaWrapper:
"""wrapper function for Pharmaca locations. Instantiates an instance of the Pharmaca class for each location"""
def __init__(self):
"""initialize the Pharmaca class and call a method to load the csv with different location data"""
self.CsvLocations = []
self.ApiLo... | the_stack_v2_python_sparse | python/PharmacaWrapper.py | CovidWA/scrapers-oss | train | 0 |
0dc1be6032f6f025fb77db479f374b769baff274 | [
"if not string:\n ' Empty String '\n return False\nvalue_dict = {}\nfor ltr in string:\n try:\n value_dict[ltr]\n ' String has a recurring value '\n return False\n except KeyError as err:\n value_dict[ltr] = True\n' String is completely Unique '\nreturn True",
"if not strin... | <|body_start_0|>
if not string:
' Empty String '
return False
value_dict = {}
for ltr in string:
try:
value_dict[ltr]
' String has a recurring value '
return False
except KeyError as err:
... | Check for Unique Characters in a string | UniqueCharacters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniqueCharacters:
"""Check for Unique Characters in a string"""
def initial_attempt(cls, string):
"""Initial Attempt"""
<|body_0|>
def without_the_try_catch(cls, string):
"""Attempting the same method as above without the try/catch"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_012869 | 5,023 | no_license | [
{
"docstring": "Initial Attempt",
"name": "initial_attempt",
"signature": "def initial_attempt(cls, string)"
},
{
"docstring": "Attempting the same method as above without the try/catch",
"name": "without_the_try_catch",
"signature": "def without_the_try_catch(cls, string)"
},
{
... | 4 | stack_v2_sparse_classes_30k_test_001182 | Implement the Python class `UniqueCharacters` described below.
Class description:
Check for Unique Characters in a string
Method signatures and docstrings:
- def initial_attempt(cls, string): Initial Attempt
- def without_the_try_catch(cls, string): Attempting the same method as above without the try/catch
- def with... | Implement the Python class `UniqueCharacters` described below.
Class description:
Check for Unique Characters in a string
Method signatures and docstrings:
- def initial_attempt(cls, string): Initial Attempt
- def without_the_try_catch(cls, string): Attempting the same method as above without the try/catch
- def with... | 94a35dc3e25ee55530920fd57d7484d24d4abbfb | <|skeleton|>
class UniqueCharacters:
"""Check for Unique Characters in a string"""
def initial_attempt(cls, string):
"""Initial Attempt"""
<|body_0|>
def without_the_try_catch(cls, string):
"""Attempting the same method as above without the try/catch"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UniqueCharacters:
"""Check for Unique Characters in a string"""
def initial_attempt(cls, string):
"""Initial Attempt"""
if not string:
' Empty String '
return False
value_dict = {}
for ltr in string:
try:
value_dict[ltr]
... | the_stack_v2_python_sparse | src/strings/unique_string_characters.py | DanielHabib/practice_makes_perfect | train | 4 |
a8f17df991e3d505b087ac230624a80f759fcb5c | [
"category_data = {'priority': int(priority), 'name': category_name}\nself.output('Uploading category..')\nobject_type = 'category'\nif obj_id:\n url = '{}/{}/{}'.format(jamf_url, self.api_endpoints(object_type), obj_id)\nelse:\n url = '{}/{}'.format(jamf_url, self.api_endpoints(object_type))\ncount = 0\ncateg... | <|body_start_0|>
category_data = {'priority': int(priority), 'name': category_name}
self.output('Uploading category..')
object_type = 'category'
if obj_id:
url = '{}/{}/{}'.format(jamf_url, self.api_endpoints(object_type), obj_id)
else:
url = '{}/{}'.forma... | JamfCategoryUploader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JamfCategoryUploader:
def upload_category(self, jamf_url, category_name, priority, token, obj_id=0):
"""Update category metadata."""
<|body_0|>
def main(self):
"""Do the main thing here"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
category_data =... | stack_v2_sparse_classes_36k_train_012870 | 6,448 | permissive | [
{
"docstring": "Update category metadata.",
"name": "upload_category",
"signature": "def upload_category(self, jamf_url, category_name, priority, token, obj_id=0)"
},
{
"docstring": "Do the main thing here",
"name": "main",
"signature": "def main(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021225 | Implement the Python class `JamfCategoryUploader` described below.
Class description:
Implement the JamfCategoryUploader class.
Method signatures and docstrings:
- def upload_category(self, jamf_url, category_name, priority, token, obj_id=0): Update category metadata.
- def main(self): Do the main thing here | Implement the Python class `JamfCategoryUploader` described below.
Class description:
Implement the JamfCategoryUploader class.
Method signatures and docstrings:
- def upload_category(self, jamf_url, category_name, priority, token, obj_id=0): Update category metadata.
- def main(self): Do the main thing here
<|skele... | 7c0a2eaf223822480ccd80a7ea3d163cc9b5b507 | <|skeleton|>
class JamfCategoryUploader:
def upload_category(self, jamf_url, category_name, priority, token, obj_id=0):
"""Update category metadata."""
<|body_0|>
def main(self):
"""Do the main thing here"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JamfCategoryUploader:
def upload_category(self, jamf_url, category_name, priority, token, obj_id=0):
"""Update category metadata."""
category_data = {'priority': int(priority), 'name': category_name}
self.output('Uploading category..')
object_type = 'category'
if obj_id... | the_stack_v2_python_sparse | JamfUploaderProcessors/JamfCategoryUploader.py | autopkg/grahampugh-recipes | train | 66 | |
76ddce80d9f095483937f336969804c4889395c3 | [
"super().__init__()\nself.window_length = window_length\nself.ser = socket",
"self.count += 1\noutput = self.ser.readline().decode('utf-8').rstrip()\nif output == '':\n return [0]\nelse:\n return [output]"
] | <|body_start_0|>
super().__init__()
self.window_length = window_length
self.ser = socket
<|end_body_0|>
<|body_start_1|>
self.count += 1
output = self.ser.readline().decode('utf-8').rstrip()
if output == '':
return [0]
else:
return [output... | Get pulse amplitude from socket. | Arduino | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arduino:
"""Get pulse amplitude from socket."""
def __init__(self, socket, window_length=10):
"""Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The default socket for the project is serial.Serial('COM3', 1152... | stack_v2_sparse_classes_36k_train_012871 | 1,132 | no_license | [
{
"docstring": "Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The default socket for the project is serial.Serial('COM3', 115200) :param window_length: The windows size which refers to the time duration",
"name": "__init__",
"s... | 2 | stack_v2_sparse_classes_30k_train_010761 | Implement the Python class `Arduino` described below.
Class description:
Get pulse amplitude from socket.
Method signatures and docstrings:
- def __init__(self, socket, window_length=10): Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The def... | Implement the Python class `Arduino` described below.
Class description:
Get pulse amplitude from socket.
Method signatures and docstrings:
- def __init__(self, socket, window_length=10): Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The def... | 5c299b675774ec16a59e26f6ef6bd727ad9a7308 | <|skeleton|>
class Arduino:
"""Get pulse amplitude from socket."""
def __init__(self, socket, window_length=10):
"""Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The default socket for the project is serial.Serial('COM3', 1152... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Arduino:
"""Get pulse amplitude from socket."""
def __init__(self, socket, window_length=10):
"""Passing a socket for the initialization :param socket: A socket object specified with the port number and the buffer size. The default socket for the project is serial.Serial('COM3', 115200) :param wi... | the_stack_v2_python_sparse | src/signal_source/arduino_signals.py | qiwliu/heart_rate_analyzer | train | 0 |
2e2a39e57328e7bbd27dc82db884f30bda115f47 | [
"LoginPreconditions.make_already_in_message_page(reset)\nmess = MessagePage()\nmess.open_workbench_page()\nworkbench = WorkbenchPage()\nif workbench.is_on_welcome_page():\n workbench.click_now_create_team()\nelse:\n workbench.wait_for_page_load()\n workbench.click_create_team()\nteam = CreateTeamPage()\nte... | <|body_start_0|>
LoginPreconditions.make_already_in_message_page(reset)
mess = MessagePage()
mess.open_workbench_page()
workbench = WorkbenchPage()
if workbench.is_on_welcome_page():
workbench.click_now_create_team()
else:
workbench.wait_for_page_l... | 工作台前置条件 | WorkbenchPreconditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbenchPreconditions:
"""工作台前置条件"""
def enter_create_team_page(reset=False):
"""从消息进入创建团队页面"""
<|body_0|>
def get_team_name():
"""获取团队"""
<|body_1|>
def create_team(team_name=None, user_name='admin'):
"""创建团队"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k_train_012872 | 5,912 | no_license | [
{
"docstring": "从消息进入创建团队页面",
"name": "enter_create_team_page",
"signature": "def enter_create_team_page(reset=False)"
},
{
"docstring": "获取团队",
"name": "get_team_name",
"signature": "def get_team_name()"
},
{
"docstring": "创建团队",
"name": "create_team",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_007758 | Implement the Python class `WorkbenchPreconditions` described below.
Class description:
工作台前置条件
Method signatures and docstrings:
- def enter_create_team_page(reset=False): 从消息进入创建团队页面
- def get_team_name(): 获取团队
- def create_team(team_name=None, user_name='admin'): 创建团队 | Implement the Python class `WorkbenchPreconditions` described below.
Class description:
工作台前置条件
Method signatures and docstrings:
- def enter_create_team_page(reset=False): 从消息进入创建团队页面
- def get_team_name(): 获取团队
- def create_team(team_name=None, user_name='admin'): 创建团队
<|skeleton|>
class WorkbenchPreconditions:
... | 543d8e81b086376944bd64ccad7a7b7da48e794d | <|skeleton|>
class WorkbenchPreconditions:
"""工作台前置条件"""
def enter_create_team_page(reset=False):
"""从消息进入创建团队页面"""
<|body_0|>
def get_team_name():
"""获取团队"""
<|body_1|>
def create_team(team_name=None, user_name='admin'):
"""创建团队"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkbenchPreconditions:
"""工作台前置条件"""
def enter_create_team_page(reset=False):
"""从消息进入创建团队页面"""
LoginPreconditions.make_already_in_message_page(reset)
mess = MessagePage()
mess.open_workbench_page()
workbench = WorkbenchPage()
if workbench.is_on_welcome_pa... | the_stack_v2_python_sparse | preconditions/BasePreconditions.py | TypeLife/appium-unittest | train | 9 |
b4fd9bffee583db8cc45237db4c0604fa3a2c574 | [
"super(ChangeNoiseParameters, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._new_steer_noise = new_steer_noise\nself._new_throttle_noise = new_throttle_noise\nself._noise_mean = noise_mean\nself._noise_std = noise_std\nself._dynamic_mean_for_steer = dynamic_mean_for_steer\... | <|body_start_0|>
super(ChangeNoiseParameters, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._new_steer_noise = new_steer_noise
self._new_throttle_noise = new_throttle_noise
self._noise_mean = noise_mean
self._noise_std = noise_std
... | This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration | ChangeNoiseParameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeNoiseParameters:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration"""
def __init__(self, new_steer_noise, new_throttle... | stack_v2_sparse_classes_36k_train_012873 | 39,839 | permissive | [
{
"docstring": "Setup actor , maximum steer value and throttle value",
"name": "__init__",
"signature": "def __init__(self, new_steer_noise, new_throttle_noise, noise_mean, noise_std, dynamic_mean_for_steer, dynamic_mean_for_throttle, name='ChangeJittering')"
},
{
"docstring": "Change the noise ... | 2 | null | Implement the Python class `ChangeNoiseParameters` described below.
Class description:
This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration
Method signature... | Implement the Python class `ChangeNoiseParameters` described below.
Class description:
This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration
Method signature... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class ChangeNoiseParameters:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration"""
def __init__(self, new_steer_noise, new_throttle... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChangeNoiseParameters:
"""This class contains an atomic jitter behavior. To add noise to steer as well as throttle of the vehicle. This behavior should be used in conjuction with AddNoiseToVehicle The behavior terminates after one iteration"""
def __init__(self, new_steer_noise, new_throttle_noise, noise... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_behaviors.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
62da91a16ff40032e992fece978fb0533fee0e2b | [
"trie = lambda: defaultdict(trie)\n\ndef trie():\n return defaultdict(trie)\nself.trie = trie()",
"child = self.trie\nfor c in word:\n child = child[c]\nchild['is_word'] = True",
"child = self.trie\nfor c in word:\n if c in child:\n child = child[c]\n else:\n return False\nreturn child... | <|body_start_0|>
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
<|end_body_0|>
<|body_start_1|>
child = self.trie
for c in word:
child = child[c]
child['is_word'] = True
<|end_body_1|>
<|body_start_2|>
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_36k_train_012874 | 3,882 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_018152 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 5d29bcf7ea1a9e489a92bc36d2158456de25829e | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
child = self.... | the_stack_v2_python_sparse | 208.实现-trie-前缀树.py | oceanbei333/leetcode | train | 0 | |
90e4a0dd5dea16b232c74615e64fc385259a0482 | [
"super(SVGD_SGHMC_hybrid, self).__init__(x_dim, y_dim, num_networks, network_structure, ll_sigma, p_sigma, rbf_sigma, svgd_step_size, hmc_step_size, hmc_n_leapfrog_steps)\nself.momentum = momentum\nself.prior_factor = 1",
"def calc_likelihood(bnn, X, y):\n yhat = bnn.forward(X)\n ll = -0.5 * torch.sum((torc... | <|body_start_0|>
super(SVGD_SGHMC_hybrid, self).__init__(x_dim, y_dim, num_networks, network_structure, ll_sigma, p_sigma, rbf_sigma, svgd_step_size, hmc_step_size, hmc_n_leapfrog_steps)
self.momentum = momentum
self.prior_factor = 1
<|end_body_0|>
<|body_start_1|>
def calc_likelihood(b... | SVGD_SGHMC_hybrid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVGD_SGHMC_hybrid:
def __init__(self, x_dim, y_dim, num_networks=16, network_structure=[32], ll_sigma=1, p_sigma=1, rbf_sigma=1, svgd_step_size=0.01, hmc_step_size=0.01, hmc_n_leapfrog_steps=10, momentum=0.999):
""":param x_dim: :param y_dim: :param num_networks: :param network_structure... | stack_v2_sparse_classes_36k_train_012875 | 9,910 | no_license | [
{
"docstring": ":param x_dim: :param y_dim: :param num_networks: :param network_structure: :param ll_sigma: :param p_sigma: :param rbf_sigma: :param svgd_step_size: :param hmc_step_size: :param hmc_n_leapfrog_steps: :param momentum:",
"name": "__init__",
"signature": "def __init__(self, x_dim, y_dim, nu... | 2 | stack_v2_sparse_classes_30k_train_015914 | Implement the Python class `SVGD_SGHMC_hybrid` described below.
Class description:
Implement the SVGD_SGHMC_hybrid class.
Method signatures and docstrings:
- def __init__(self, x_dim, y_dim, num_networks=16, network_structure=[32], ll_sigma=1, p_sigma=1, rbf_sigma=1, svgd_step_size=0.01, hmc_step_size=0.01, hmc_n_lea... | Implement the Python class `SVGD_SGHMC_hybrid` described below.
Class description:
Implement the SVGD_SGHMC_hybrid class.
Method signatures and docstrings:
- def __init__(self, x_dim, y_dim, num_networks=16, network_structure=[32], ll_sigma=1, p_sigma=1, rbf_sigma=1, svgd_step_size=0.01, hmc_step_size=0.01, hmc_n_lea... | 1e8cdfb1eeedff7a67131f7d9229ec0f3b1e0e18 | <|skeleton|>
class SVGD_SGHMC_hybrid:
def __init__(self, x_dim, y_dim, num_networks=16, network_structure=[32], ll_sigma=1, p_sigma=1, rbf_sigma=1, svgd_step_size=0.01, hmc_step_size=0.01, hmc_n_leapfrog_steps=10, momentum=0.999):
""":param x_dim: :param y_dim: :param num_networks: :param network_structure... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVGD_SGHMC_hybrid:
def __init__(self, x_dim, y_dim, num_networks=16, network_structure=[32], ll_sigma=1, p_sigma=1, rbf_sigma=1, svgd_step_size=0.01, hmc_step_size=0.01, hmc_n_leapfrog_steps=10, momentum=0.999):
""":param x_dim: :param y_dim: :param num_networks: :param network_structure: :param ll_si... | the_stack_v2_python_sparse | BNN_SVGD/SVGD_HMC_hybrid.py | dnguyen1196/BNN_SVGD | train | 4 | |
07a02f8fc8a72acdc9378ee9e07d393823442960 | [
"self._lock = allocate_lock()\nself._loaded = {}\nPictureManager.MANAGER = self",
"resource_wrapper = ResourceWrapper(name=name)\nstart_new_thread(self.load_picture_asynchronously, (resource_wrapper,))\nreturn resource_wrapper",
"try:\n logging.debug('Begin loading picture ' + resource_wrapper.name)\n sel... | <|body_start_0|>
self._lock = allocate_lock()
self._loaded = {}
PictureManager.MANAGER = self
<|end_body_0|>
<|body_start_1|>
resource_wrapper = ResourceWrapper(name=name)
start_new_thread(self.load_picture_asynchronously, (resource_wrapper,))
return resource_wrapper
<|e... | The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture. | PictureManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_012876 | 2,624 | no_license | [
{
"docstring": "Generates a new instance of this class. Generates a new instance of this class and sets the field information.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Loads the picture. This method loads the picture with the given name. Calling this method star... | 4 | stack_v2_sparse_classes_30k_test_000347 | Implement the Python class `PictureManager` described below.
Class description:
The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded pic... | Implement the Python class `PictureManager` described below.
Class description:
The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded pic... | 0308785a51bf61d9a4fec2d8370540df502b8178 | <|skeleton|>
class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
"""Generat... | the_stack_v2_python_sparse | resources/pictures/picture_manager.py | donhilion/JumpAndRun | train | 0 |
9b96c01af9f24356dd8f6cbce62e2846f9d52429 | [
"m = len(A)\nn = len(B)\ndp = [[0] * (n + 1) for _ in range(2)]\nfor i in range(1, m + 1):\n idx = i % 2\n for j in range(1, n + 1):\n if A[i - 1] == B[j - 1]:\n dp[idx][j] = dp[idx ^ 1][j - 1] + 1\n else:\n dp[idx][j] = max(dp[idx ^ 1][j], dp[idx][j - 1])\nreturn dp[idx][n... | <|body_start_0|>
m = len(A)
n = len(B)
dp = [[0] * (n + 1) for _ in range(2)]
for i in range(1, m + 1):
idx = i % 2
for j in range(1, n + 1):
if A[i - 1] == B[j - 1]:
dp[idx][j] = dp[idx ^ 1][j - 1] + 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
"""Space optimized DP"""
<|body_0|>
def maxUncrossedLines_2(self, A: List[int], B: List[int]) -> int:
"""Longest common subsequence"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_012877 | 1,028 | no_license | [
{
"docstring": "Space optimized DP",
"name": "maxUncrossedLines",
"signature": "def maxUncrossedLines(self, A: List[int], B: List[int]) -> int"
},
{
"docstring": "Longest common subsequence",
"name": "maxUncrossedLines_2",
"signature": "def maxUncrossedLines_2(self, A: List[int], B: List... | 2 | stack_v2_sparse_classes_30k_train_014165 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: Space optimized DP
- def maxUncrossedLines_2(self, A: List[int], B: List[int]) -> int: Longest common subsequence | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: Space optimized DP
- def maxUncrossedLines_2(self, A: List[int], B: List[int]) -> int: Longest common subsequence
... | 20a48021be5e5348d681e910c843e734df98b596 | <|skeleton|>
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
"""Space optimized DP"""
<|body_0|>
def maxUncrossedLines_2(self, A: List[int], B: List[int]) -> int:
"""Longest common subsequence"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
"""Space optimized DP"""
m = len(A)
n = len(B)
dp = [[0] * (n + 1) for _ in range(2)]
for i in range(1, m + 1):
idx = i % 2
for j in range(1, n + 1):
if A[i... | the_stack_v2_python_sparse | uncrossed_lines/uncrossed_lines.py | narnat/leetcode | train | 0 | |
2238757765430213ab6e26b875d4e1ef3d185747 | [
"if data is empty:\n return True\nreturn not any(json.loads(data).values())",
"if self.is_empty_i18n_data(data) and self.required:\n self.fail('required')\nreturn super().validate_empty_values(data)"
] | <|body_start_0|>
if data is empty:
return True
return not any(json.loads(data).values())
<|end_body_0|>
<|body_start_1|>
if self.is_empty_i18n_data(data) and self.required:
self.fail('required')
return super().validate_empty_values(data)
<|end_body_1|>
| I18nCharField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I18nCharField:
def is_empty_i18n_data(data):
"""check for values in each language empty value example: {"en":""}"""
<|body_0|>
def validate_empty_values(self, data):
"""Empty i18n fields have the following format: {"en":""}, we have to decode json and check empty str... | stack_v2_sparse_classes_36k_train_012878 | 759 | no_license | [
{
"docstring": "check for values in each language empty value example: {\"en\":\"\"}",
"name": "is_empty_i18n_data",
"signature": "def is_empty_i18n_data(data)"
},
{
"docstring": "Empty i18n fields have the following format: {\"en\":\"\"}, we have to decode json and check empty strings for langu... | 2 | stack_v2_sparse_classes_30k_train_004699 | Implement the Python class `I18nCharField` described below.
Class description:
Implement the I18nCharField class.
Method signatures and docstrings:
- def is_empty_i18n_data(data): check for values in each language empty value example: {"en":""}
- def validate_empty_values(self, data): Empty i18n fields have the follo... | Implement the Python class `I18nCharField` described below.
Class description:
Implement the I18nCharField class.
Method signatures and docstrings:
- def is_empty_i18n_data(data): check for values in each language empty value example: {"en":""}
- def validate_empty_values(self, data): Empty i18n fields have the follo... | 338fd6396dbdce971bc542718fbb9608bdcfc2a7 | <|skeleton|>
class I18nCharField:
def is_empty_i18n_data(data):
"""check for values in each language empty value example: {"en":""}"""
<|body_0|>
def validate_empty_values(self, data):
"""Empty i18n fields have the following format: {"en":""}, we have to decode json and check empty str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class I18nCharField:
def is_empty_i18n_data(data):
"""check for values in each language empty value example: {"en":""}"""
if data is empty:
return True
return not any(json.loads(data).values())
def validate_empty_values(self, data):
"""Empty i18n fields have the foll... | the_stack_v2_python_sparse | api/custom_fields.py | sai9912/mypyton | train | 0 | |
02be51da6ff605ab0bb1b0c5ffa25b17512a59dd | [
"super(HodgkinHuxleyStats, self).__init__(seed=seed)\nself.t_on = t_on\nself.t_off = t_off\nself.n_mom = n_mom\nself.n_summary = np.minimum(n_summary, n_mom + 3)",
"stats = []\nfor r in range(repetition_list[0]['data'].shape[0]):\n x = repetition_list[0]\n data = x['data'][r, :]\n t = x['time']\n dt =... | <|body_start_0|>
super(HodgkinHuxleyStats, self).__init__(seed=seed)
self.t_on = t_on
self.t_off = t_off
self.n_mom = n_mom
self.n_summary = np.minimum(n_summary, n_mom + 3)
<|end_body_0|>
<|body_start_1|>
stats = []
for r in range(repetition_list[0]['data'].shap... | Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics | HodgkinHuxleyStats | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HodgkinHuxleyStats:
"""Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics"""
def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None):
"""See SummaryStats.py for docstring"""
<|body_0|>
def calc(self, repetition_list):
... | stack_v2_sparse_classes_36k_train_012879 | 10,875 | permissive | [
{
"docstring": "See SummaryStats.py for docstring",
"name": "__init__",
"signature": "def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None)"
},
{
"docstring": "Calculate summary statistics Parameters ---------- repetition_list : list of dictionaries, one per repetition data list, retu... | 2 | stack_v2_sparse_classes_30k_train_012853 | Implement the Python class `HodgkinHuxleyStats` described below.
Class description:
Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics
Method signatures and docstrings:
- def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None): See SummaryStats.py for docstring
- def c... | Implement the Python class `HodgkinHuxleyStats` described below.
Class description:
Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics
Method signatures and docstrings:
- def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None): See SummaryStats.py for docstring
- def c... | d06b9f2e6ce6235c4b318b9807a75263beb3e518 | <|skeleton|>
class HodgkinHuxleyStats:
"""Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics"""
def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None):
"""See SummaryStats.py for docstring"""
<|body_0|>
def calc(self, repetition_list):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HodgkinHuxleyStats:
"""Moment based SummaryStats class for the Hodgkin-Huxley model Calculates summary statistics"""
def __init__(self, t_on, t_off, n_mom=4, n_summary=7, seed=None):
"""See SummaryStats.py for docstring"""
super(HodgkinHuxleyStats, self).__init__(seed=seed)
self.t... | the_stack_v2_python_sparse | model/HH/HH_model.py | holmosaint/delfi | train | 0 |
6b6d5315c9c4293f5a6fc7d97f800add67d6b095 | [
"if not username:\n raise ValueError('users must have an username')\nuser = self.model(username=username, is_customer=is_customer, is_merchant=is_merchant, is_subadmin=is_subadmin)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, password=passwo... | <|body_start_0|>
if not username:
raise ValueError('users must have an username')
user = self.model(username=username, is_customer=is_customer, is_merchant=is_merchant, is_subadmin=is_subadmin)
user.set_password(password)
user.save(using=self._db)
return user
<|end_bo... | MyuserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyuserManager:
def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False):
"""Creates and saves a User with the given email, date of birtb and password."""
<|body_0|>
def create_superuser(self, username, password, is_customer=True,... | stack_v2_sparse_classes_36k_train_012880 | 5,730 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birtb and password.",
"name": "create_user",
"signature": "def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False)"
},
{
"docstring": "creates and save a superuser with the given... | 2 | stack_v2_sparse_classes_30k_train_008334 | Implement the Python class `MyuserManager` described below.
Class description:
Implement the MyuserManager class.
Method signatures and docstrings:
- def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False): Creates and saves a User with the given email, date of birtb and... | Implement the Python class `MyuserManager` described below.
Class description:
Implement the MyuserManager class.
Method signatures and docstrings:
- def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False): Creates and saves a User with the given email, date of birtb and... | 88e4e994a029527d9e6b9431155a81cd5774b63c | <|skeleton|>
class MyuserManager:
def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False):
"""Creates and saves a User with the given email, date of birtb and password."""
<|body_0|>
def create_superuser(self, username, password, is_customer=True,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyuserManager:
def create_user(self, username, password=None, is_customer=True, is_merchant=False, is_subadmin=False):
"""Creates and saves a User with the given email, date of birtb and password."""
if not username:
raise ValueError('users must have an username')
user = se... | the_stack_v2_python_sparse | myuser/models.py | anku580/Upfront---Backend | train | 0 | |
5819fc5031474b321b0c610d1e562b85a6ced586 | [
"if not root:\n return 0\n\ndef visit(prefixes, node: TreeNode) -> int:\n new_prefixes = {key + node.val: count for key, count in prefixes.items()}\n new_prefixes[node.val] = new_prefixes.get(node.val, 0) + 1\n count = new_prefixes.get(target, 0)\n if node.left:\n count += visit(new_prefixes, ... | <|body_start_0|>
if not root:
return 0
def visit(prefixes, node: TreeNode) -> int:
new_prefixes = {key + node.val: count for key, count in prefixes.items()}
new_prefixes[node.val] = new_prefixes.get(node.val, 0) + 1
count = new_prefixes.get(target, 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
<|body_0|>
def pathSum(self,... | stack_v2_sparse_classes_36k_train_012881 | 2,344 | no_license | [
{
"docstring": "Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths.",
"name": "pathSum",
"signature": "def pathSum(self, root: TreeNode, target: int) -> int"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_000939 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root: TreeNode, target: int) -> int: Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for mult... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root: TreeNode, target: int) -> int: Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for mult... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
<|body_0|>
def pathSum(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
if not root:
return 0
def ... | the_stack_v2_python_sparse | binary_tree/PathSum3.py | QuentinDuval/PythonExperiments | train | 3 | |
9abbb516d5fa52ead1845cfc888b466131d9d205 | [
"super(LinearND, self).__init__()\nself.fc = nn.Linear(*size, bias=bias)\nself.dropout = nn.Dropout(p=dropout)",
"size = list(xs.size())\nxs = xs.contiguous().view((int(np.prod(size[:-1])), int(size[-1])))\nxs = self.fc(xs)\nxs = self.dropout(xs)\nsize[-1] = xs.size()[-1]\nreturn xs.view(size)"
] | <|body_start_0|>
super(LinearND, self).__init__()
self.fc = nn.Linear(*size, bias=bias)
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
size = list(xs.size())
xs = xs.contiguous().view((int(np.prod(size[:-1])), int(size[-1])))
xs = self.fc(xs)
... | LinearND | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearND:
def __init__(self, *size, bias=True, dropout=0):
"""A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension. Args: size (): bias (bool, optional): if False, remove a bias term dropout (float, optional):""... | stack_v2_sparse_classes_36k_train_012882 | 4,283 | no_license | [
{
"docstring": "A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension. Args: size (): bias (bool, optional): if False, remove a bias term dropout (float, optional):",
"name": "__init__",
"signature": "def __init__(self, *size, b... | 2 | stack_v2_sparse_classes_30k_train_010831 | Implement the Python class `LinearND` described below.
Class description:
Implement the LinearND class.
Method signatures and docstrings:
- def __init__(self, *size, bias=True, dropout=0): A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension... | Implement the Python class `LinearND` described below.
Class description:
Implement the LinearND class.
Method signatures and docstrings:
- def __init__(self, *size, bias=True, dropout=0): A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension... | b6b60a338d65bb369d0034f423feb09db10db8b7 | <|skeleton|>
class LinearND:
def __init__(self, *size, bias=True, dropout=0):
"""A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension. Args: size (): bias (bool, optional): if False, remove a bias term dropout (float, optional):""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearND:
def __init__(self, *size, bias=True, dropout=0):
"""A torch.nn.Linear layer modified to accept ND arrays. The function treats the last dimension of the input as the hidden dimension. Args: size (): bias (bool, optional): if False, remove a bias term dropout (float, optional):"""
supe... | the_stack_v2_python_sparse | models/pytorch/linear.py | carolinebear/pytorch_end2end_speech_recognition | train | 0 | |
61443dd3bc358e1d185a3ae3a4c54c3dcf928571 | [
"dev = self.selectedDevice(c)\nif f is not None:\n yield dev.setFrequency(f)\nreturnValue(float(dev.frequency) * Hz)",
"dev = self.selectedDevice(c)\nif a is not None:\n yield dev.setAmplitude(a)\nreturnValue(float(dev.amplitude) * dBm)",
"dev = self.selectedDevice(c)\nif os is not None:\n yield dev.se... | <|body_start_0|>
dev = self.selectedDevice(c)
if f is not None:
yield dev.setFrequency(f)
returnValue(float(dev.frequency) * Hz)
<|end_body_0|>
<|body_start_1|>
dev = self.selectedDevice(c)
if a is not None:
yield dev.setAmplitude(a)
returnValue(f... | ADD DOCUMENT STRING | HittiteServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HittiteServer:
"""ADD DOCUMENT STRING"""
def frequency(self, c, f=None):
"""Get or set the CW frequency."""
<|body_0|>
def amplitude(self, c, a=None):
"""Get or set the CW amplitude."""
<|body_1|>
def output_state(self, c, os=None):
"""Get or... | stack_v2_sparse_classes_36k_train_012883 | 3,982 | no_license | [
{
"docstring": "Get or set the CW frequency.",
"name": "frequency",
"signature": "def frequency(self, c, f=None)"
},
{
"docstring": "Get or set the CW amplitude.",
"name": "amplitude",
"signature": "def amplitude(self, c, a=None)"
},
{
"docstring": "Get or set the output status."... | 4 | stack_v2_sparse_classes_30k_train_019965 | Implement the Python class `HittiteServer` described below.
Class description:
ADD DOCUMENT STRING
Method signatures and docstrings:
- def frequency(self, c, f=None): Get or set the CW frequency.
- def amplitude(self, c, a=None): Get or set the CW amplitude.
- def output_state(self, c, os=None): Get or set the output... | Implement the Python class `HittiteServer` described below.
Class description:
ADD DOCUMENT STRING
Method signatures and docstrings:
- def frequency(self, c, f=None): Get or set the CW frequency.
- def amplitude(self, c, a=None): Get or set the CW amplitude.
- def output_state(self, c, os=None): Get or set the output... | 94c7aa8db708badf0be53b582dc2ba80262834a0 | <|skeleton|>
class HittiteServer:
"""ADD DOCUMENT STRING"""
def frequency(self, c, f=None):
"""Get or set the CW frequency."""
<|body_0|>
def amplitude(self, c, a=None):
"""Get or set the CW amplitude."""
<|body_1|>
def output_state(self, c, os=None):
"""Get or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HittiteServer:
"""ADD DOCUMENT STRING"""
def frequency(self, c, f=None):
"""Get or set the CW frequency."""
dev = self.selectedDevice(c)
if f is not None:
yield dev.setFrequency(f)
returnValue(float(dev.frequency) * Hz)
def amplitude(self, c, a=None):
... | the_stack_v2_python_sparse | HittiteT2100/hittite_T2100.py | yutaka-tabuchi/servers | train | 0 |
70876f5d65de9f40a5c5b1e4c0e1f410fe5211ca | [
"with patch('builtins.input', return_value='1'):\n assert input() == '1'\nwith patch('builtins.input', return_value='2'):\n assert input() == '2'\nwith patch('builtins.input', return_value='3'):\n assert input() == '3'",
"test_gp = mm.getprice('test1')\ninput_gp = mm.getprice('test2')\nself.assertEqual(t... | <|body_start_0|>
with patch('builtins.input', return_value='1'):
assert input() == '1'
with patch('builtins.input', return_value='2'):
assert input() == '2'
with patch('builtins.input', return_value='3'):
assert input() == '3'
<|end_body_0|>
<|body_start_1|>
... | class docstring | MainmenuTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainmenuTest:
"""class docstring"""
def test_mainmenu(self):
"""method doc string"""
<|body_0|>
def test_getprice(self):
"""method doc string"""
<|body_1|>
def test_iteminfo(self):
"""method doc string"""
<|body_2|>
def test_exit... | stack_v2_sparse_classes_36k_train_012884 | 3,874 | no_license | [
{
"docstring": "method doc string",
"name": "test_mainmenu",
"signature": "def test_mainmenu(self)"
},
{
"docstring": "method doc string",
"name": "test_getprice",
"signature": "def test_getprice(self)"
},
{
"docstring": "method doc string",
"name": "test_iteminfo",
"sign... | 4 | null | Implement the Python class `MainmenuTest` described below.
Class description:
class docstring
Method signatures and docstrings:
- def test_mainmenu(self): method doc string
- def test_getprice(self): method doc string
- def test_iteminfo(self): method doc string
- def test_exit(self): method docstring | Implement the Python class `MainmenuTest` described below.
Class description:
class docstring
Method signatures and docstrings:
- def test_mainmenu(self): method doc string
- def test_getprice(self): method doc string
- def test_iteminfo(self): method doc string
- def test_exit(self): method docstring
<|skeleton|>
c... | ac12beeae8aa57135bbcd03ac7a4f977fa3bdb56 | <|skeleton|>
class MainmenuTest:
"""class docstring"""
def test_mainmenu(self):
"""method doc string"""
<|body_0|>
def test_getprice(self):
"""method doc string"""
<|body_1|>
def test_iteminfo(self):
"""method doc string"""
<|body_2|>
def test_exit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainmenuTest:
"""class docstring"""
def test_mainmenu(self):
"""method doc string"""
with patch('builtins.input', return_value='1'):
assert input() == '1'
with patch('builtins.input', return_value='2'):
assert input() == '2'
with patch('builtins.inp... | the_stack_v2_python_sparse | students/Daniel_Carrasco/lesson01/assignment/test_unit.py | UWPCE-PythonCert-ClassRepos/py220-online-201904-V2 | train | 1 |
0b269bd5c040070aad8ebd6d043dbe18500338a0 | [
"Questionnaire.__init__(self, df)\nself.names = ['PRFQ_PM', 'PRFQ_CM', 'PRFQ_IC']\nself.labels = ['PRFQ Pre-Mentalizing Modes', 'PRFQ Certainty about Mental States', 'PRFQ Interest and Curiosity in Mental States']\nself.values = {'PRFQ_PM': {}, 'PRFQ_CM': {}, 'PRFQ_IC': {}}\nself.new_df = pd.DataFrame(0, index=self... | <|body_start_0|>
Questionnaire.__init__(self, df)
self.names = ['PRFQ_PM', 'PRFQ_CM', 'PRFQ_IC']
self.labels = ['PRFQ Pre-Mentalizing Modes', 'PRFQ Certainty about Mental States', 'PRFQ Interest and Curiosity in Mental States']
self.values = {'PRFQ_PM': {}, 'PRFQ_CM': {}, 'PRFQ_IC': {}}
... | A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the questionnaire recode(col) recode each number in a column to the opposite number | PRFC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PRFC:
"""A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the questionnaire recode(col) recode each number in... | stack_v2_sparse_classes_36k_train_012885 | 2,593 | no_license | [
{
"docstring": "Init the following arguments: names = the new columns' names (after grading) labels = labels for each column to be written in the SPSS output file values = explanation for the values in each SPSS column - empty for this questionaire new_df = new DataFrame with the graded values Parameters ------... | 3 | stack_v2_sparse_classes_30k_train_013420 | Implement the Python class `PRFC` described below.
Class description:
A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the question... | Implement the Python class `PRFC` described below.
Class description:
A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the question... | 26b8a2847d7202b61e67e2cd0074278a46a9f8f3 | <|skeleton|>
class PRFC:
"""A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the questionnaire recode(col) recode each number in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PRFC:
"""A class used to represent an the The Parental Reflective Functioning Questionnaire Attributes ---------- df : DataFrame a Pandas data frame with the specific columns for the questionnaire Methods ------- grade() calculate the grading of the questionnaire recode(col) recode each number in a column to ... | the_stack_v2_python_sparse | Questionnaires/PRFC.py | TechnionENIC/ENIC_scoring_program | train | 0 |
c33da48d04c3066abe2a34f9221bfe650f78f30b | [
"if not heights:\n return 0\nleft_max = right_max = 0\nleft, right = (0, len(heights) - 1)\nwater_area = 0\nwhile left < right:\n if heights[left] < heights[right]:\n left_max = max(left_max, heights[left])\n water_area += left_max - heights[left]\n left += 1\n else:\n right_max... | <|body_start_0|>
if not heights:
return 0
left_max = right_max = 0
left, right = (0, len(heights) - 1)
water_area = 0
while left < right:
if heights[left] < heights[right]:
left_max = max(left_max, heights[left])
water_area ... | RainWater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def total_area_trapped_(self, heights: List[int]) -> int:
"""Approach: Two Poin... | stack_v2_sparse_classes_36k_train_012886 | 1,847 | no_license | [
{
"docstring": "Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:",
"name": "total_area_trapped",
"signature": "def total_area_trapped(self, heights: List[int]) -> int"
},
{
"docstring": "Approach: Two Pointers Time Complexity: O(N) Space Comp... | 2 | stack_v2_sparse_classes_30k_train_012693 | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def total_area_trapped(self, heights: List[int]) -> int: Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def total_area... | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def total_area_trapped(self, heights: List[int]) -> int: Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def total_area... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def total_area_trapped_(self, heights: List[int]) -> int:
"""Approach: Two Poin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RainWater:
def total_area_trapped(self, heights: List[int]) -> int:
"""Approach: Two Pointers Optimized Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
if not heights:
return 0
left_max = right_max = 0
left, right = (0, len(heights) - 1)
... | the_stack_v2_python_sparse | expedia/trapping_rain_water.py | Shiv2157k/leet_code | train | 1 | |
85e805c14e8b7a3c966c67e06320c6e74c26b8cd | [
"self.dist = dist\nself.accel = accel\nself.decel = decel\nd0 = dist * decel / (accel + decel)\nd1 = 0\nt0 = sqrt(2 * d0 / accel)\nt1 = 0\nt2 = accel / decel * t0\nvc = accel * t0\nif vc > max_speed:\n t0 = max_speed / accel\n t2 = max_speed / decel\n d0 = max_speed * t0 / 2\n d1 = dist - 0.5 * (accel *... | <|body_start_0|>
self.dist = dist
self.accel = accel
self.decel = decel
d0 = dist * decel / (accel + decel)
d1 = 0
t0 = sqrt(2 * d0 / accel)
t1 = 0
t2 = accel / decel * t0
vc = accel * t0
if vc > max_speed:
t0 = max_speed / acce... | The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant. | AToBConstAccel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AToBConstAccel:
"""The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant."""
def __init__(self, dist, accel, decel, max_speed=inf):
"""dist: The distance between A to B; accel: The rate of acceleration; decel: The ... | stack_v2_sparse_classes_36k_train_012887 | 1,724 | no_license | [
{
"docstring": "dist: The distance between A to B; accel: The rate of acceleration; decel: The rate of deceleration; max_speed: Optional. The max speed of movement.",
"name": "__init__",
"signature": "def __init__(self, dist, accel, decel, max_speed=inf)"
},
{
"docstring": "Calculating the curre... | 2 | stack_v2_sparse_classes_30k_test_000243 | Implement the Python class `AToBConstAccel` described below.
Class description:
The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant.
Method signatures and docstrings:
- def __init__(self, dist, accel, decel, max_speed=inf): dist: The distance bet... | Implement the Python class `AToBConstAccel` described below.
Class description:
The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant.
Method signatures and docstrings:
- def __init__(self, dist, accel, decel, max_speed=inf): dist: The distance bet... | 3945ef235ac8e7a7a66fec018597aa9b34b0a4e6 | <|skeleton|>
class AToBConstAccel:
"""The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant."""
def __init__(self, dist, accel, decel, max_speed=inf):
"""dist: The distance between A to B; accel: The rate of acceleration; decel: The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AToBConstAccel:
"""The model of movement from A to B. The speed at point A and B is 0. The rates of acceleration and deceleration are constant."""
def __init__(self, dist, accel, decel, max_speed=inf):
"""dist: The distance between A to B; accel: The rate of acceleration; decel: The rate of decel... | the_stack_v2_python_sparse | wavesynlib/formulae/motion.py | xialulee/WaveSyn | train | 9 |
4ef6c029b7a43f677807f1edc95957af404b77b0 | [
"self.NATS_DIR = str(Path(__file__).parent.parent.parent) + '/NATS'\nself.module = params[0]\nself.params = params[1:]",
"os.system('cd ' + self.NATS_DIR)\nopen_file, file_name, description = imp.find_module(self.module, [self.NATS_DIR + '/scriptsSwRI/'])\nmodule = imp.load_module(self.module + '.py', open_file, ... | <|body_start_0|>
self.NATS_DIR = str(Path(__file__).parent.parent.parent) + '/NATS'
self.module = params[0]
self.params = params[1:]
<|end_body_0|>
<|body_start_1|>
os.system('cd ' + self.NATS_DIR)
open_file, file_name, description = imp.find_module(self.module, [self.NATS_DIR +... | Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command). | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command)."""
def __init__(self, params):
"""params (list): list of str where element 0 is the NATS module name and all other elements are ar... | stack_v2_sparse_classes_36k_train_012888 | 1,398 | no_license | [
{
"docstring": "params (list): list of str where element 0 is the NATS module name and all other elements are arguments to pass",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "run the NATS script",
"name": "executeCommand",
"signature": "def executeComm... | 2 | stack_v2_sparse_classes_30k_test_000113 | Implement the Python class `Command` described below.
Class description:
Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command).
Method signatures and docstrings:
- def __init__(self, params): params (list): list of str where elemen... | Implement the Python class `Command` described below.
Class description:
Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command).
Method signatures and docstrings:
- def __init__(self, params): params (list): list of str where elemen... | 7bf11b0dc3b6633aa5702c1b37d5842ef4a6878e | <|skeleton|>
class Command:
"""Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command)."""
def __init__(self, params):
"""params (list): list of str where element 0 is the NATS module name and all other elements are ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Class Command wraps the command methods and functions to be executed. For user-defined commands, this name should be kept the same (Command)."""
def __init__(self, params):
"""params (list): list of str where element 0 is the NATS module name and all other elements are arguments to pa... | the_stack_v2_python_sparse | paraatm/deprecated/Commands/runNATS.py | ymlasu/para-atm | train | 11 |
5612a990a3f1f5c0c6165b6ee40034a8480865c9 | [
"try:\n img = Image.open(blob)\n LOGGER.debug('Removing stale EXIF keys')\n for key in list(blob.attributes.keys()):\n if key.startswith('blob.p2.io/exif/'):\n del blob.attributes[key]\n if hasattr(img, '_getexif'):\n LOGGER.debug('Adding exif from file')\n exif_data = im... | <|body_start_0|>
try:
img = Image.open(blob)
LOGGER.debug('Removing stale EXIF keys')
for key in list(blob.attributes.keys()):
if key.startswith('blob.p2.io/exif/'):
del blob.attributes[key]
if hasattr(img, '_getexif'):
... | add image attributes from exif data | ImageController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageController:
"""add image attributes from exif data"""
def handle(self, blob):
"""extract EXIF data from image and save as attributes"""
<|body_0|>
def get_attributes(self, raw_exif):
"""Convert raw exif data into usable tags"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_012889 | 2,180 | permissive | [
{
"docstring": "extract EXIF data from image and save as attributes",
"name": "handle",
"signature": "def handle(self, blob)"
},
{
"docstring": "Convert raw exif data into usable tags",
"name": "get_attributes",
"signature": "def get_attributes(self, raw_exif)"
}
] | 2 | null | Implement the Python class `ImageController` described below.
Class description:
add image attributes from exif data
Method signatures and docstrings:
- def handle(self, blob): extract EXIF data from image and save as attributes
- def get_attributes(self, raw_exif): Convert raw exif data into usable tags | Implement the Python class `ImageController` described below.
Class description:
add image attributes from exif data
Method signatures and docstrings:
- def handle(self, blob): extract EXIF data from image and save as attributes
- def get_attributes(self, raw_exif): Convert raw exif data into usable tags
<|skeleton|... | 80b5c6a821f90cef73d6e8cd3c6cdb05ffa86b27 | <|skeleton|>
class ImageController:
"""add image attributes from exif data"""
def handle(self, blob):
"""extract EXIF data from image and save as attributes"""
<|body_0|>
def get_attributes(self, raw_exif):
"""Convert raw exif data into usable tags"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageController:
"""add image attributes from exif data"""
def handle(self, blob):
"""extract EXIF data from image and save as attributes"""
try:
img = Image.open(blob)
LOGGER.debug('Removing stale EXIF keys')
for key in list(blob.attributes.keys()):
... | the_stack_v2_python_sparse | p2/components/image/controller.py | BeryJu/p2 | train | 1 |
a9a306ac1eab65fed662856b0c415d742b392296 | [
"current = root\nstack = []\nwhile True:\n stack.append(current)\n if node.val == current.val:\n return stack\n elif node.val < current.val:\n current = current.left\n else:\n current = current.right",
"stackp = self.find_ancestors(root, p)\nstackq = self.find_ancestors(root, q)\n... | <|body_start_0|>
current = root
stack = []
while True:
stack.append(current)
if node.val == current.val:
return stack
elif node.val < current.val:
current = current.left
else:
current = current.right
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_ancestors(self, root, node):
""":type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|bod... | stack_v2_sparse_classes_36k_train_012890 | 1,754 | no_license | [
{
"docstring": ":type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)",
"name": "find_ancestors",
"signature": "def find_ancestors(self, root, node)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_ancestors(self, root, node): :type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_ancestors(self, root, node): :type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p:... | 1bba7aadabd5d234a9482a661da84a6829adfb77 | <|skeleton|>
class Solution:
def find_ancestors(self, root, node):
""":type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_ancestors(self, root, node):
""":type root: TreeNode :type node: TreeNode :rtype: List(TreeNode)"""
current = root
stack = []
while True:
stack.append(current)
if node.val == current.val:
return stack
elif n... | the_stack_v2_python_sparse | 235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.py | nickciaravella/leetcode | train | 0 | |
5d42fd1cfed98b18a841906e10e6f6243e229888 | [
"super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get(FunctionComponent.INTEGRATION_NAME, {})\nself.url = self.options.get('url')\nself.submit_url = self.options.get('submit_url')\nself.api_key = self.options.get('submit_api_key')",
"self.opts = opts\nself.options = opts.get(Fu... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionComponent.INTEGRATION_NAME, {})
self.url = self.options.get('url')
self.submit_url = self.options.get('submit_url')
self.api_key = self.options.get('submit_api_... | Component that implements Resilient function 'URLHaus lookup | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'URLHaus lookup"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save n... | stack_v2_sparse_classes_36k_train_012891 | 5,060 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Configuration options have changed, save new values",
"name": "_reload",
"signature": "def _reload(self, event, opts)"
},
{
"d... | 5 | null | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'URLHaus lookup
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'URLHaus lookup
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options... | 2e3c4b6102555517bad22bf87fa4a06341714166 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'URLHaus lookup"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionComponent:
"""Component that implements Resilient function 'URLHaus lookup"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionCom... | the_stack_v2_python_sparse | fn_urlhaus/fn_urlhaus/components/func_urlhaus.py | jjfallete/resilient-community-apps | train | 1 |
4200782a5602e4020adeebc16dd8d375a5a5bc57 | [
"res = []\nwhile head:\n res.append(head.val)\n head = head.next\nreturn int(''.join((str(e) for e in res)), base=2)",
"num = head.val\nwhile head.next:\n num = num * 2 + head.next.val\n head = head.next\nreturn num",
"num = head.val\nwhile head.next:\n num = num << 1 | head.next.val\n head = ... | <|body_start_0|>
res = []
while head:
res.append(head.val)
head = head.next
return int(''.join((str(e) for e in res)), base=2)
<|end_body_0|>
<|body_start_1|>
num = head.val
while head.next:
num = num * 2 + head.next.val
head = hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def getDecimalValue1(self, head):
"""Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int"""
<|body_1|>
def getDecimalValue2(self, head):
... | stack_v2_sparse_classes_36k_train_012892 | 1,080 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "getDecimalValue",
"signature": "def getDecimalValue(self, head)"
},
{
"docstring": "Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int",
"name": "getDecimalValue1",
"signature": "def getDecimalValue1(sel... | 3 | stack_v2_sparse_classes_30k_train_013148 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getDecimalValue(self, head): :type head: ListNode :rtype: int
- def getDecimalValue1(self, head): Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getDecimalValue(self, head): :type head: ListNode :rtype: int
- def getDecimalValue1(self, head): Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int
... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def getDecimalValue1(self, head):
"""Binary Representation time O(n) space O(1) :type head: ListNode :rtype: int"""
<|body_1|>
def getDecimalValue2(self, head):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getDecimalValue(self, head):
""":type head: ListNode :rtype: int"""
res = []
while head:
res.append(head.val)
head = head.next
return int(''.join((str(e) for e in res)), base=2)
def getDecimalValue1(self, head):
"""Binary Repre... | the_stack_v2_python_sparse | LeetCode/LinkedList/1290_convert_binary_number_in_a_linked_list_to_integer.py | XyK0907/for_work | train | 0 | |
9106775c35ea030ce6287facdd3a416f412dc686 | [
"super(PositionalEncoding, self).__init__(**kwargs)\nself._initializer = initializer\nself._cache_encoding = cache_encoding\nself._pos_encoding = None\nself._rezero = Scale(initializer=initializer, name='rezero')",
"config = {'initializer': self._initializer, 'cache_encoding': self._cache_encoding}\nbase_config =... | <|body_start_0|>
super(PositionalEncoding, self).__init__(**kwargs)
self._initializer = initializer
self._cache_encoding = cache_encoding
self._pos_encoding = None
self._rezero = Scale(initializer=initializer, name='rezero')
<|end_body_0|>
<|body_start_1|>
config = {'ini... | Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it. This implements: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion ... | PositionalEncoding | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it. This implements: Ashish Vaswani, Noam... | stack_v2_sparse_classes_36k_train_012893 | 33,772 | permissive | [
{
"docstring": "Initializes positional encoding. Args: initializer: A `str` of initializer for weighting the positional encoding. cache_encoding: A `bool`. If True, cache the positional encoding tensor after calling build. Otherwise, rebuild the tensor for every call. Setting this to False can be useful when we... | 6 | null | Implement the Python class `PositionalEncoding` described below.
Class description:
Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it... | Implement the Python class `PositionalEncoding` described below.
Class description:
Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it... | 192ae544169c1230c21141c033800aa1bd94e9b6 | <|skeleton|>
class PositionalEncoding:
"""Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it. This implements: Ashish Vaswani, Noam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Creates a network layer that adds a sinusoidal positional encoding. Positional encoding is incremented across frames, and is added to the input. The positional encoding is first weighted at 0 so that the network can choose to ignore it. This implements: Ashish Vaswani, Noam Shazeer, Nik... | the_stack_v2_python_sparse | official/vision/beta/modeling/layers/nn_layers.py | DemonDamon/mask-detection-based-on-tf2odapi | train | 2 |
62a06265a899f1d422031d38480e05ed3b650020 | [
"query = Query(SkillCategory.collection, service_id=self._client.service_id)\nquery.add_term(field=self.id_field, value=self.id)\nquery.limit(100)\nreturn SequenceProxy(SkillCategory, query, client=self._client)",
"item_id = self.data.required_item_id or -1\nquery = Query(Item.collection, service_id=self._client.... | <|body_start_0|>
query = Query(SkillCategory.collection, service_id=self._client.service_id)
query.add_term(field=self.id_field, value=self.id)
query.limit(100)
return SequenceProxy(SkillCategory, query, client=self._client)
<|end_body_0|>
<|body_start_1|>
item_id = self.data.re... | A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Additionally, skill sets are used for unlocking vehicle weapons. .. attribute:: id ... | SkillSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkillSet:
"""A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Additionally, skill sets are used for unlocking... | stack_v2_sparse_classes_36k_train_012894 | 11,338 | permissive | [
{
"docstring": "Return the skill categories in this skill set. This returns a :class:`auraxium.SequenceProxy`.",
"name": "categories",
"signature": "def categories(self) -> SequenceProxy['SkillCategory']"
},
{
"docstring": "Return the item required for access to this skill set. This returns an :... | 2 | null | Implement the Python class `SkillSet` described below.
Class description:
A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Addition... | Implement the Python class `SkillSet` described below.
Class description:
A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Addition... | 23dcf927a199c8d7c917d89fe96b470a34cf4bba | <|skeleton|>
class SkillSet:
"""A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Additionally, skill sets are used for unlocking... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkillSet:
"""A skill set for a particular vehicle or class. In the old certifications menu, skill sets were used for all certifications associated with a given item or vehicle. Since its removal, they are mostly for internal grouping of skill lines. Additionally, skill sets are used for unlocking vehicle weap... | the_stack_v2_python_sparse | auraxium/ps2/_skill.py | leonhard-s/auraxium | train | 29 |
37232588ba499e8749b56dfc512b2254fddab075 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.is_active = True\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = Tru... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_s... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_012895 | 17,164 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_001999 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 4a72aed204d978dbc756d9982ba17b5736f6e172 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | mycrm/crm/models.py | soin3/mycrm | train | 0 | |
5a1f2ddf2ff08aa8f31c4e323d3816c6994e03e1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Ad service. Service to manage ads. | AdServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdServiceServicer:
"""Proto file describing the Ad service. Service to manage ads."""
def GetAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAds(self, request, context):
"""Updates ads. Operation statuses are return... | stack_v2_sparse_classes_36k_train_012896 | 3,033 | permissive | [
{
"docstring": "Returns the requested ad in full detail.",
"name": "GetAd",
"signature": "def GetAd(self, request, context)"
},
{
"docstring": "Updates ads. Operation statuses are returned. Updating ads is not supported for TextAd, ExpandedDynamicSearchAd, GmailAd and ImageAd.",
"name": "Mut... | 2 | null | Implement the Python class `AdServiceServicer` described below.
Class description:
Proto file describing the Ad service. Service to manage ads.
Method signatures and docstrings:
- def GetAd(self, request, context): Returns the requested ad in full detail.
- def MutateAds(self, request, context): Updates ads. Operatio... | Implement the Python class `AdServiceServicer` described below.
Class description:
Proto file describing the Ad service. Service to manage ads.
Method signatures and docstrings:
- def GetAd(self, request, context): Returns the requested ad in full detail.
- def MutateAds(self, request, context): Updates ads. Operatio... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class AdServiceServicer:
"""Proto file describing the Ad service. Service to manage ads."""
def GetAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAds(self, request, context):
"""Updates ads. Operation statuses are return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdServiceServicer:
"""Proto file describing the Ad service. Service to manage ads."""
def GetAd(self, request, context):
"""Returns the requested ad in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotI... | the_stack_v2_python_sparse | google/ads/google_ads/v4/proto/services/ad_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
843dfce0a9e3c8260f3a5129a7ac7e749e6c5543 | [
"letter = 'abcdefghijklmnopqrstuvwxyz'\ns = list(S)\ni, j = (0, len(s) - 1)\nwhile i < j:\n if s[i].lower() not in letter:\n i = i + 1\n elif s[j].lower() not in letter:\n j = j - 1\n else:\n s[i], s[j] = (s[j], s[i])\n i = i + 1\n j = j - 1\nreturn ''.join(s)",
"def ge... | <|body_start_0|>
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list(S)
i, j = (0, len(s) - 1)
while i < j:
if s[i].lower() not in letter:
i = i + 1
elif s[j].lower() not in letter:
j = j - 1
else:
s[i], s[j] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
<|body_0|>
def reverseOnlyLetters2(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list... | stack_v2_sparse_classes_36k_train_012897 | 1,112 | no_license | [
{
"docstring": ":type S: str :rtype: str",
"name": "reverseOnlyLetters",
"signature": "def reverseOnlyLetters(self, S)"
},
{
"docstring": ":type S: str :rtype: str",
"name": "reverseOnlyLetters2",
"signature": "def reverseOnlyLetters2(self, S)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004995 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseOnlyLetters(self, S): :type S: str :rtype: str
- def reverseOnlyLetters2(self, S): :type S: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseOnlyLetters(self, S): :type S: str :rtype: str
- def reverseOnlyLetters2(self, S): :type S: str :rtype: str
<|skeleton|>
class Solution:
def reverseOnlyLetters(s... | b149d1e8a83b0dfc724bd9dc129a1cad407dd91f | <|skeleton|>
class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
<|body_0|>
def reverseOnlyLetters2(self, S):
""":type S: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseOnlyLetters(self, S):
""":type S: str :rtype: str"""
letter = 'abcdefghijklmnopqrstuvwxyz'
s = list(S)
i, j = (0, len(s) - 1)
while i < j:
if s[i].lower() not in letter:
i = i + 1
elif s[j].lower() not in lett... | the_stack_v2_python_sparse | string/0917_reverse_only_letters/0917_reverse_only_letters.py | zdyxry/LeetCode | train | 6 | |
ad85057e489e7d3eb3d82fc7e4fb9bf6a23922c0 | [
"record = model.get_email_authorized_for_repo(namespace, repository, email)\nif not record:\n abort(404)\nresponse = record.to_dict()\ndel response['code']\nreturn response",
"with tf(db):\n record = model.get_email_authorized_for_repo(namespace, repository, email)\n if record and record.confirmed:\n ... | <|body_start_0|>
record = model.get_email_authorized_for_repo(namespace, repository, email)
if not record:
abort(404)
response = record.to_dict()
del response['code']
return response
<|end_body_0|>
<|body_start_1|>
with tf(db):
record = model.get_... | Resource for checking and authorizing e-mail addresses to receive repo notifications. | RepositoryAuthorizedEmail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_36k_train_012898 | 2,290 | permissive | [
{
"docstring": "Checks to see if the given e-mail address is authorized on this repository.",
"name": "get",
"signature": "def get(self, namespace, repository, email)"
},
{
"docstring": "Starts the authorization process for an e-mail address on a repository.",
"name": "post",
"signature"... | 2 | null | Implement the Python class `RepositoryAuthorizedEmail` described below.
Class description:
Resource for checking and authorizing e-mail addresses to receive repo notifications.
Method signatures and docstrings:
- def get(self, namespace, repository, email): Checks to see if the given e-mail address is authorized on t... | Implement the Python class `RepositoryAuthorizedEmail` described below.
Class description:
Resource for checking and authorizing e-mail addresses to receive repo notifications.
Method signatures and docstrings:
- def get(self, namespace, repository, email): Checks to see if the given e-mail address is authorized on t... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepositoryAuthorizedEmail:
"""Resource for checking and authorizing e-mail addresses to receive repo notifications."""
def get(self, namespace, repository, email):
"""Checks to see if the given e-mail address is authorized on this repository."""
record = model.get_email_authorized_for_rep... | the_stack_v2_python_sparse | endpoints/api/repoemail.py | quay/quay | train | 2,363 |
f2313a5e2139f55fdfd67a66f6eb53b0e706db5d | [
"parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('The usernames of users whose tokens will be invalidated.'))\nparser.add_argument('-r', '--reason', default='', help=_('A message indicating why the tokens are no longer valid.'))\nparser.add_argument('-a', '--all', action='store_true', default... | <|body_start_0|>
parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('The usernames of users whose tokens will be invalidated.'))
parser.add_argument('-r', '--reason', default='', help=_('A message indicating why the tokens are no longer valid.'))
parser.add_argument('-a', '--... | Management command to invalidate API tokens. Version Added: 5.0 | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Management command to invalidate API tokens. Version Added: 5.0"""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
<|body_0|>
def handle(self, *args, **options):... | stack_v2_sparse_classes_36k_train_012899 | 3,834 | permissive | [
{
"docstring": "Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Handle the command. Args: *args (tuple, unused): Arguments parsed on the command... | 2 | stack_v2_sparse_classes_30k_train_003753 | Implement the Python class `Command` described below.
Class description:
Management command to invalidate API tokens. Version Added: 5.0
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.
- def... | Implement the Python class `Command` described below.
Class description:
Management command to invalidate API tokens. Version Added: 5.0
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.
- def... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class Command:
"""Management command to invalidate API tokens. Version Added: 5.0"""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
<|body_0|>
def handle(self, *args, **options):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Management command to invalidate API tokens. Version Added: 5.0"""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
parser.add_argument('usernames', metavar='USERNAME', nargs='*', ... | the_stack_v2_python_sparse | reviewboard/webapi/management/commands/invalidate-api-tokens.py | reviewboard/reviewboard | train | 1,141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.