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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b70bf32f0bd39773c1acafbd78de998ece30f31f | [
"self.config = config\nprint(config)\nself.model = SASRec(config['model'])\nself.num_batch = config['model']['n_users'] // config['model']['batch_size']\nself.bce_criterion = torch.nn.BCEWithLogitsLoss()\nsuper(SASRecEngine, self).__init__(config)",
"assert hasattr(self, 'model'), 'Please specify the exact model ... | <|body_start_0|>
self.config = config
print(config)
self.model = SASRec(config['model'])
self.num_batch = config['model']['n_users'] // config['model']['batch_size']
self.bce_criterion = torch.nn.BCEWithLogitsLoss()
super(SASRecEngine, self).__init__(config)
<|end_body_0|... | Engine for training Triple model. | SASRecEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SASRecEngine:
"""Engine for training Triple model."""
def __init__(self, config):
"""Initialize Triple2vecEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|>
def trai... | stack_v2_sparse_classes_36k_train_009700 | 9,120 | permissive | [
{
"docstring": "Initialize Triple2vecEngine Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train the model in a single batch.",
"name": "train_single_batch",
"signature": "def train_single_batch(self, batch_data, ratings=None)"
},
{
"doc... | 3 | null | Implement the Python class `SASRecEngine` described below.
Class description:
Engine for training Triple model.
Method signatures and docstrings:
- def __init__(self, config): Initialize Triple2vecEngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.
- def train_an... | Implement the Python class `SASRecEngine` described below.
Class description:
Engine for training Triple model.
Method signatures and docstrings:
- def __init__(self, config): Initialize Triple2vecEngine Class.
- def train_single_batch(self, batch_data, ratings=None): Train the model in a single batch.
- def train_an... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class SASRecEngine:
"""Engine for training Triple model."""
def __init__(self, config):
"""Initialize Triple2vecEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data, ratings=None):
"""Train the model in a single batch."""
<|body_1|>
def trai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SASRecEngine:
"""Engine for training Triple model."""
def __init__(self, config):
"""Initialize Triple2vecEngine Class."""
self.config = config
print(config)
self.model = SASRec(config['model'])
self.num_batch = config['model']['n_users'] // config['model']['batch_... | the_stack_v2_python_sparse | beta_rec/models/sasrec.py | beta-team/beta-recsys | train | 156 |
f17bc693587f8cf15c9c808117c8599155ca5f19 | [
"self.size = size\nself.scale = scale\nself.min_pool_binary = min_pool_binary\nself.binary_keys = list(binary_keys)\nself.flow_keys = list(flow_keys)",
"h, w = inputs[list(inputs.keys())[0]].shape[2:4]\nif self.size is None or self.size[0] < 1 or self.size[1] < 1:\n self.size = (int(self.scale * h), int(self.s... | <|body_start_0|>
self.size = size
self.scale = scale
self.min_pool_binary = min_pool_binary
self.binary_keys = list(binary_keys)
self.flow_keys = list(flow_keys)
<|end_body_0|>
<|body_start_1|>
h, w = inputs[list(inputs.keys())[0]].shape[2:4]
if self.size is None... | Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used. | Resize | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resize:
"""Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used."""
def __init__(self, size: Tuple[int, int]=(0, 0), scale: float=1.0, min_pool_binary: bool=True, binary_keys: Union[KeysView, Sequence[str]]=('mbs', 'occs', 'valids... | stack_v2_sparse_classes_36k_train_009701 | 42,078 | permissive | [
{
"docstring": "Initialize Resize. Parameters ---------- size : Tuple[int, int], default (0, 0) The target size to resize the inputs. If it is zeros, then the scale will be used instead. scale : float, default 1.0 The scale factor to resize the images. Only used if size is zeros. min_pool_binary : bool, default... | 2 | stack_v2_sparse_classes_30k_train_009465 | Implement the Python class `Resize` described below.
Class description:
Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used.
Method signatures and docstrings:
- def __init__(self, size: Tuple[int, int]=(0, 0), scale: float=1.0, min_pool_binary: bool=True,... | Implement the Python class `Resize` described below.
Class description:
Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used.
Method signatures and docstrings:
- def __init__(self, size: Tuple[int, int]=(0, 0), scale: float=1.0, min_pool_binary: bool=True,... | d6582a0fd386517fdefbe2c347cef53150b5b1da | <|skeleton|>
class Resize:
"""Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used."""
def __init__(self, size: Tuple[int, int]=(0, 0), scale: float=1.0, min_pool_binary: bool=True, binary_keys: Union[KeysView, Sequence[str]]=('mbs', 'occs', 'valids... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resize:
"""Resize the image to a given size or scale. Size is checked first, if any of its values is zero, then scale is used."""
def __init__(self, size: Tuple[int, int]=(0, 0), scale: float=1.0, min_pool_binary: bool=True, binary_keys: Union[KeysView, Sequence[str]]=('mbs', 'occs', 'valids', 'mbs_b', '... | the_stack_v2_python_sparse | ptlflow/data/flow_transforms.py | hmorimitsu/ptlflow | train | 140 |
3e6195f6ded96af2de131c7c2d42e612630f1842 | [
"domain = []\nif self.location:\n domain.append(('location', '=', self.location.id))\nelse:\n domain.append(('location', 'in', []))\nreturn {'domain': {'rail': domain}}",
"active_id = self.env.context.get('active_id')\nmodel = self.env['metro_park_dispatch.cur_train_manage']\nrecord = model.browse(active_id... | <|body_start_0|>
domain = []
if self.location:
domain.append(('location', '=', self.location.id))
else:
domain.append(('location', 'in', []))
return {'domain': {'rail': domain}}
<|end_body_0|>
<|body_start_1|>
active_id = self.env.context.get('active_id')... | 设置车辆当前位置 | SetCurLocationWizard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetCurLocationWizard:
"""设置车辆当前位置"""
def on_change_location(self):
"""当位置发生改变的时候, 只能选择location下面的rail :return:"""
<|body_0|>
def on_ok(self):
"""确定 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
domain = []
if self.location:
... | stack_v2_sparse_classes_36k_train_009702 | 1,629 | no_license | [
{
"docstring": "当位置发生改变的时候, 只能选择location下面的rail :return:",
"name": "on_change_location",
"signature": "def on_change_location(self)"
},
{
"docstring": "确定 :return:",
"name": "on_ok",
"signature": "def on_ok(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000474 | Implement the Python class `SetCurLocationWizard` described below.
Class description:
设置车辆当前位置
Method signatures and docstrings:
- def on_change_location(self): 当位置发生改变的时候, 只能选择location下面的rail :return:
- def on_ok(self): 确定 :return: | Implement the Python class `SetCurLocationWizard` described below.
Class description:
设置车辆当前位置
Method signatures and docstrings:
- def on_change_location(self): 当位置发生改变的时候, 只能选择location下面的rail :return:
- def on_ok(self): 确定 :return:
<|skeleton|>
class SetCurLocationWizard:
"""设置车辆当前位置"""
def on_change_locat... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class SetCurLocationWizard:
"""设置车辆当前位置"""
def on_change_location(self):
"""当位置发生改变的时候, 只能选择location下面的rail :return:"""
<|body_0|>
def on_ok(self):
"""确定 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetCurLocationWizard:
"""设置车辆当前位置"""
def on_change_location(self):
"""当位置发生改变的时候, 只能选择location下面的rail :return:"""
domain = []
if self.location:
domain.append(('location', '=', self.location.id))
else:
domain.append(('location', 'in', []))
re... | the_stack_v2_python_sparse | mdias_addons/metro_park_dispatch/models/set_cur_location_wizard.py | rezaghanimi/main_mdias | train | 0 |
5719de02c8b56e9c1a4c5b8efa338146b0461852 | [
"super(Upsample, self).__init__()\nself.apply_dropout = apply_dropout\ninitializer = tf.random_normal_initializer(0, 0.02)\nself.conv1 = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer, use_bias=False)\nself.batch_normal = tf.... | <|body_start_0|>
super(Upsample, self).__init__()
self.apply_dropout = apply_dropout
initializer = tf.random_normal_initializer(0, 0.02)
self.conv1 = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer,... | Use convolution layer to upsample. | Upsample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_009703 | 20,044 | no_license | [
{
"docstring": "The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:",
"name": "__init__",
"signature": "def __init__(self, filters, size, apply_dropout=True)"
},
{
"docstring": "Calls the model on n... | 2 | stack_v2_sparse_classes_30k_train_007770 | Implement the Python class `Upsample` described below.
Class description:
Use convolution layer to upsample.
Method signatures and docstrings:
- def __init__(self, filters, size, apply_dropout=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchn... | Implement the Python class `Upsample` described below.
Class description:
Use convolution layer to upsample.
Method signatures and docstrings:
- def __init__(self, filters, size, apply_dropout=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchn... | d1b70b2a954f4665b628ba252b03c1a74b95559f | <|skeleton|>
class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Upsample:
"""Use convolution layer to upsample."""
def __init__(self, filters, size, apply_dropout=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
super(Upsample, self).__ini... | the_stack_v2_python_sparse | NeuralNetworks-tensorflow/generation_network_model/GAN/pix2pix.py | zhaocc1106/machine_learn | train | 15 |
50bbbbbf55a022a1067e1c001515c6cbbffcf71e | [
"self.cert_file_name = cert_file_name\nself.hosts_info_list = hosts_info_list\nself.mtype = mtype\nself.valid_days = valid_days",
"if dictionary is None:\n return None\ncert_file_name = dictionary.get('certFileName')\nhosts_info_list = None\nif dictionary.get('hostsInfoList') != None:\n hosts_info_list = li... | <|body_start_0|>
self.cert_file_name = cert_file_name
self.hosts_info_list = hosts_info_list
self.mtype = mtype
self.valid_days = valid_days
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
cert_file_name = dictionary.get('certFileName')
... | Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo): Specifies the list of all hosts on which the certificate is to be deployed. mtype (T... | DeployCertParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployCertParameters:
"""Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo): Specifies the list of all hosts on w... | stack_v2_sparse_classes_36k_train_009704 | 2,976 | permissive | [
{
"docstring": "Constructor for the DeployCertParameters class",
"name": "__init__",
"signature": "def __init__(self, cert_file_name=None, hosts_info_list=None, mtype=None, valid_days=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A d... | 2 | null | Implement the Python class `DeployCertParameters` described below.
Class description:
Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo... | Implement the Python class `DeployCertParameters` described below.
Class description:
Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DeployCertParameters:
"""Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo): Specifies the list of all hosts on w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeployCertParameters:
"""Implementation of the 'DeployCertParameters' model. Specifies the parameters used to generate and deploy a certificate. Attributes: cert_file_name (string): Specifies the filename of the certificate. hosts_info_list (list of HostInfo): Specifies the list of all hosts on which the cert... | the_stack_v2_python_sparse | cohesity_management_sdk/models/deploy_cert_parameters.py | cohesity/management-sdk-python | train | 24 |
df0435da5a001a50958fcb7ef22e23988c7a91db | [
"field_name = self.name\nfor record in records:\n context = record.env.context\n binary_value = record[field_name]\n field_object = record._fields[field_name]\n parent_field = field_object._attrs.get('resize_based_on')\n if parent_field and (not record.env.context.get('refresh_image_cache')):\n ... | <|body_start_0|>
field_name = self.name
for record in records:
context = record.env.context
binary_value = record[field_name]
field_object = record._fields[field_name]
parent_field = field_object._attrs.get('resize_based_on')
if parent_field an... | Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized | ImageField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageField:
"""Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized"""
def _comput... | stack_v2_sparse_classes_36k_train_009705 | 13,811 | no_license | [
{
"docstring": "Control how a value of ImageField should be updated, when an ImageField field is updated should consider the case: - current field is parent field or child field: the parent field should be always update first, then update related child fields. :param {openerp.models.BaseModel} records: current ... | 3 | null | Implement the Python class `ImageField` described below.
Class description:
Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height o... | Implement the Python class `ImageField` described below.
Class description:
Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height o... | 673dd0f2a7c0b69a984342b20f55164a97a00529 | <|skeleton|>
class ImageField:
"""Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized"""
def _comput... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageField:
"""Class for all ImageField type The __init__ should take optional parameters as bellow :param {string} resize_based_on: name of the field that should be resized :param {integer} width: width of the image resized :param {integer} height: height of the image resized"""
def _compute_write(self,... | the_stack_v2_python_sparse | addons/trobz-extra/binary_field/fields.py | TinPlusIT05/tms | train | 0 |
6e3ff59d92de4fa810222be82c191aa56336529d | [
"charList = [chr(x) for x in xrange(97, 123)]\nvisited = set()\nvisited.add(beginWord)\nwordSet = set(wordList)\nq = Queue()\nq.put(beginWord)\nres = 1\nwhile not q.empty():\n for _ in xrange(q.qsize()):\n curr = q.get()\n if curr == endWord:\n return res\n for i in xrange(len(cur... | <|body_start_0|>
charList = [chr(x) for x in xrange(97, 123)]
visited = set()
visited.add(beginWord)
wordSet = set(wordList)
q = Queue()
q.put(beginWord)
res = 1
while not q.empty():
for _ in xrange(q.qsize()):
curr = q.get()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
<|body_0|>
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordL... | stack_v2_sparse_classes_36k_train_009706 | 2,961 | no_license | [
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int",
"name": "ladderLength",
"signature": "def ladderLength(self, beginWord, endWord, wordList)"
},
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int",
"name... | 2 | stack_v2_sparse_classes_30k_train_000416 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
- def ladderLength(self, beginWord, endWord, w... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
- def ladderLength(self, beginWord, endWord, w... | 14febbb5d8504438ef143678dedc89d4b61b07c9 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
<|body_0|>
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordL... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
charList = [chr(x) for x in xrange(97, 123)]
visited = set()
visited.add(beginWord)
wordSet = set(wordList)
q = Qu... | the_stack_v2_python_sparse | BFS/127. Word Ladder.py | roy355068/Algo | train | 0 | |
23055efcdb54fb0f2f0afa82f3e22eafbeda0a78 | [
"set1 = set()\nset2 = set()\nfor ele in nums:\n if ele not in set1:\n set1.add(ele)\n else:\n set2.add(ele)\nres = set1 - set2\nreturn res.pop()",
"hash_table = {}\nfor i in nums:\n try:\n hash_table.pop(i)\n except:\n hash_table[i] = 1\nreturn hash_table.popitem()[0]"
] | <|body_start_0|>
set1 = set()
set2 = set()
for ele in nums:
if ele not in set1:
set1.add(ele)
else:
set2.add(ele)
res = set1 - set2
return res.pop()
<|end_body_0|>
<|body_start_1|>
hash_table = {}
for i in n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
set1 = set()
set2 = set()
... | stack_v2_sparse_classes_36k_train_009707 | 1,246 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(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 singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def singleNu... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(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 singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
set1 = set()
set2 = set()
for ele in nums:
if ele not in set1:
set1.add(ele)
else:
set2.add(ele)
res = set1 - set2
return res.... | the_stack_v2_python_sparse | 2.SET/single_number/solution.py | kimmyoo/python_leetcode | train | 1 | |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(KeepVelocity, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._control = carla.VehicleControl()\nself._actor = actor\nself._target_velocity = target_velocity\nself._control.steering = 0",
"new_status = py_trees.common.Status.RUNNING\nif CarlaDataProvider.get_velocit... | <|body_start_0|>
super(KeepVelocity, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._control = carla.VehicleControl()
self._actor = actor
self._target_velocity = target_velocity
self._control.steering = 0
<|end_body_0|>
<|body_star... | This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is active. Note: In parallel to this behavior a termination behavior has to be used... | KeepVelocity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeepVelocity:
"""This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is active. Note: In parallel to this behavi... | stack_v2_sparse_classes_36k_train_009708 | 25,380 | permissive | [
{
"docstring": "Setup parameters including acceleration value (via throttle_value) and target velocity",
"name": "__init__",
"signature": "def __init__(self, actor, target_velocity, name='KeepVelocity')"
},
{
"docstring": "Set throttle to throttle_value, as long as velocity is < target_velocity"... | 3 | stack_v2_sparse_classes_30k_train_000098 | Implement the Python class `KeepVelocity` described below.
Class description:
This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is a... | Implement the Python class `KeepVelocity` described below.
Class description:
This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is a... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class KeepVelocity:
"""This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is active. Note: In parallel to this behavi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeepVelocity:
"""This class contains an atomic behavior to keep the provided velocity. The controlled traffic participant will accelerate as fast as possible until reaching a given _target_velocity_, which is then maintained for as long as this behavior is active. Note: In parallel to this behavior a terminat... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
5a14ea8a60638680f440c7251be330c65f5a09d9 | [
"workoutset = WorkoutSet.objects.select_related('workout_fk', 'exercise_fk').get(pk=pk)\nself._check_workoutset_permissions(workout_fk, workoutset)\nserializer = WorkoutSetGetSerializer(workoutset)\nreturn Response(serializer.data)",
"workoutset = WorkoutSet.objects.select_related('workout_fk').get(pk=pk)\nself._... | <|body_start_0|>
workoutset = WorkoutSet.objects.select_related('workout_fk', 'exercise_fk').get(pk=pk)
self._check_workoutset_permissions(workout_fk, workoutset)
serializer = WorkoutSetGetSerializer(workoutset)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
wo... | GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py | WorkoutSetDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkoutSetDetail:
"""GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py"""
def get(self, request, workout_fk, pk, format=None):
"""Retrieve a single workoutset."""
<|body_0|>
def put(self, request, w... | stack_v2_sparse_classes_36k_train_009709 | 4,956 | no_license | [
{
"docstring": "Retrieve a single workoutset.",
"name": "get",
"signature": "def get(self, request, workout_fk, pk, format=None)"
},
{
"docstring": "Update a single workoutset.",
"name": "put",
"signature": "def put(self, request, workout_fk, pk, format=None)"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_train_016599 | Implement the Python class `WorkoutSetDetail` described below.
Class description:
GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py
Method signatures and docstrings:
- def get(self, request, workout_fk, pk, format=None): Retrieve a single workou... | Implement the Python class `WorkoutSetDetail` described below.
Class description:
GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py
Method signatures and docstrings:
- def get(self, request, workout_fk, pk, format=None): Retrieve a single workou... | 829e1a721e2382489f2cf0f730b2c462ecc54722 | <|skeleton|>
class WorkoutSetDetail:
"""GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py"""
def get(self, request, workout_fk, pk, format=None):
"""Retrieve a single workoutset."""
<|body_0|>
def put(self, request, w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkoutSetDetail:
"""GET, PUT, DELETE using a WorkoutSet id. See notes on WorkoutSetBaseSerializer vs WorkoutSetGetSerializer in serializers.py"""
def get(self, request, workout_fk, pk, format=None):
"""Retrieve a single workoutset."""
workoutset = WorkoutSet.objects.select_related('worko... | the_stack_v2_python_sparse | bigfitnessgains/apps/mainapp/rest_api/workoutset.py | AnthonyHonstain/bigfitnessgains | train | 0 |
3f013217c9391083b2b1c329110f696d01d5311d | [
"if t is None:\n return True\nelif s is None:\n return False\nelse:\n return self.__compare(s, t) or (s.left is not None and self.isSubtree(s.left, t)) or (s.right is not None and self.isSubtree(s.right, t))",
"if node1 is None and node2 is None:\n return True\nelif node1 is not None and node2 is not ... | <|body_start_0|>
if t is None:
return True
elif s is None:
return False
else:
return self.__compare(s, t) or (s.left is not None and self.isSubtree(s.left, t)) or (s.right is not None and self.isSubtree(s.right, t))
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_0|>
def __compare(self, node1, node2):
""":type node1: TreeNode :type node2: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_009710 | 2,193 | permissive | [
{
"docstring": ":type s: TreeNode :type t: TreeNode :rtype: bool",
"name": "isSubtree",
"signature": "def isSubtree(self, s, t)"
},
{
"docstring": ":type node1: TreeNode :type node2: TreeNode :rtype: bool",
"name": "__compare",
"signature": "def __compare(self, node1, node2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
- def __compare(self, node1, node2): :type node1: TreeNode :type node2: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
- def __compare(self, node1, node2): :type node1: TreeNode :type node2: TreeNode :rtype: bool
<|skele... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_0|>
def __compare(self, node1, node2):
""":type node1: TreeNode :type node2: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
if t is None:
return True
elif s is None:
return False
else:
return self.__compare(s, t) or (s.left is not None and self.isSubtree(s.left, t)) or (s.r... | the_stack_v2_python_sparse | leetcode/easy/tree/test_subtree_of_another_tree.py | yenbohuang/online-contest-python | train | 0 | |
11ce04e718ff2ba330b9b8619159203950d885e4 | [
"super(SharedTextCNN, self).__init__()\nself.nk = len(kernel_sizes)\nself.dim_e = embeddings.shape[1]\nself.dim_sum_filter = sum(channels_outs)\nif activation == 'relu':\n self.activation_function = F.relu\nelif activation == 'elu':\n self.activation_function = F.elu\nelif activation == 'gelu':\n self.acti... | <|body_start_0|>
super(SharedTextCNN, self).__init__()
self.nk = len(kernel_sizes)
self.dim_e = embeddings.shape[1]
self.dim_sum_filter = sum(channels_outs)
if activation == 'relu':
self.activation_function = F.relu
elif activation == 'elu':
self.a... | SharedTextCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedTextCNN:
def __init__(self, embeddings, embeddings_freeze, slen, output_size, dropout_p=0.1, kernel_sizes=(3, 4, 5), channels_outs=(100, 100, 100), activation='relu', alpha_dropout=False):
"""channels_out[s] is the ouput of the convolution which converts channels_in into channels_o... | stack_v2_sparse_classes_36k_train_009711 | 12,941 | permissive | [
{
"docstring": "channels_out[s] is the ouput of the convolution which converts channels_in into channels_out. this is commonly called n_filters or n_feature_maps and \"conceptually corresponds\" to the number of features extracted by a convolution SCNN uses ELUs and AlphaDropout to create a self-normalizing CNN... | 2 | stack_v2_sparse_classes_30k_train_012511 | Implement the Python class `SharedTextCNN` described below.
Class description:
Implement the SharedTextCNN class.
Method signatures and docstrings:
- def __init__(self, embeddings, embeddings_freeze, slen, output_size, dropout_p=0.1, kernel_sizes=(3, 4, 5), channels_outs=(100, 100, 100), activation='relu', alpha_drop... | Implement the Python class `SharedTextCNN` described below.
Class description:
Implement the SharedTextCNN class.
Method signatures and docstrings:
- def __init__(self, embeddings, embeddings_freeze, slen, output_size, dropout_p=0.1, kernel_sizes=(3, 4, 5), channels_outs=(100, 100, 100), activation='relu', alpha_drop... | b99069cf76606da585292fe354fe34e05953925d | <|skeleton|>
class SharedTextCNN:
def __init__(self, embeddings, embeddings_freeze, slen, output_size, dropout_p=0.1, kernel_sizes=(3, 4, 5), channels_outs=(100, 100, 100), activation='relu', alpha_dropout=False):
"""channels_out[s] is the ouput of the convolution which converts channels_in into channels_o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharedTextCNN:
def __init__(self, embeddings, embeddings_freeze, slen, output_size, dropout_p=0.1, kernel_sizes=(3, 4, 5), channels_outs=(100, 100, 100), activation='relu', alpha_dropout=False):
"""channels_out[s] is the ouput of the convolution which converts channels_in into channels_out. this is co... | the_stack_v2_python_sparse | experiments/d33/04_run/mtmodel.py | silknow/text-classification | train | 3 | |
0c20204ba41b6231c5d839f2cbb03f930537c612 | [
"super().__init__(always_apply, p)\nself.s = s\nself.r = r\nself.mask_value_min = mask_value_min\nself.mask_value_max = mask_value_max",
"image_copy = np.copy(image)\nmask_value = np.random.randint(self.mask_value_min, self.mask_value_max + 1)\nh, w, _ = image.shape\nmask_area_pixel = np.random.randint(h * w * se... | <|body_start_0|>
super().__init__(always_apply, p)
self.s = s
self.r = r
self.mask_value_min = mask_value_min
self.mask_value_max = mask_value_max
<|end_body_0|>
<|body_start_1|>
image_copy = np.copy(image)
mask_value = np.random.randint(self.mask_value_min, self... | Class of RandomErase for Albumentations. | RandomErase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomErase:
"""Class of RandomErase for Albumentations."""
def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float=1.0) -> None:
"""Initialize."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_009712 | 1,892 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float=1.0) -> None"
},
{
"docstring": "Apply transform. Note: Input image... | 2 | stack_v2_sparse_classes_30k_test_000776 | Implement the Python class `RandomErase` described below.
Class description:
Class of RandomErase for Albumentations.
Method signatures and docstrings:
- def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float... | Implement the Python class `RandomErase` described below.
Class description:
Class of RandomErase for Albumentations.
Method signatures and docstrings:
- def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float... | b96965761c50ad56c758a63d873fff31ba31d442 | <|skeleton|>
class RandomErase:
"""Class of RandomErase for Albumentations."""
def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float=1.0) -> None:
"""Initialize."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomErase:
"""Class of RandomErase for Albumentations."""
def __init__(self, s: tp.Tuple[float]=(0.02, 0.4), r: tp.Tuple[float]=(0.3, 2.7), mask_value_min: int=0, mask_value_max: int=255, always_apply: bool=False, p: float=1.0) -> None:
"""Initialize."""
super().__init__(always_apply, p... | the_stack_v2_python_sparse | src/base_data/transform.py | tawatawara/atmaCup-11 | train | 11 |
3478c62b4364c4a7c02c552871bf4c443ab21764 | [
"N = len(nums)\nm = defaultdict(list)\nfor i, n in enumerate(nums):\n m[n].append(i)\nvisited = set()\nret = []\nfor i in range(N - 1):\n for j in range(i + 1, N):\n target = -(nums[i] + nums[j])\n key = tuple(sorted([nums[i], nums[j], target]))\n if key in visited:\n continue\... | <|body_start_0|>
N = len(nums)
m = defaultdict(list)
for i, n in enumerate(nums):
m[n].append(i)
visited = set()
ret = []
for i in range(N - 1):
for j in range(i + 1, N):
target = -(nums[i] + nums[j])
key = tuple(sor... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Time complexity: O(n^2) Space complexity: O(n^3)"""
<|body_0|>
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Time complexity: O(n^2) Space complexity: O(1) Exclude return"""
<|b... | stack_v2_sparse_classes_36k_train_009713 | 4,417 | no_license | [
{
"docstring": "Time complexity: O(n^2) Space complexity: O(n^3)",
"name": "threeSum",
"signature": "def threeSum(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Time complexity: O(n^2) Space complexity: O(1) Exclude return",
"name": "threeSum",
"signature": "def threeSum(s... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: Time complexity: O(n^2) Space complexity: O(n^3)
- def threeSum(self, nums: List[int]) -> List[List[int]]: Time complexity... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: Time complexity: O(n^2) Space complexity: O(n^3)
- def threeSum(self, nums: List[int]) -> List[List[int]]: Time complexity... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Time complexity: O(n^2) Space complexity: O(n^3)"""
<|body_0|>
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Time complexity: O(n^2) Space complexity: O(1) Exclude return"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Time complexity: O(n^2) Space complexity: O(n^3)"""
N = len(nums)
m = defaultdict(list)
for i, n in enumerate(nums):
m[n].append(i)
visited = set()
ret = []
for i in range(N... | the_stack_v2_python_sparse | leetcode/solved/15_3Sum/solution.py | sungminoh/algorithms | train | 0 | |
b820497d01965bc02d39058d5d96e4014d4da76e | [
"self = real_self.magic\nrezensent_string = getFormatter(' ')(self.reviewAuthors[0]['firstname'], self.reviewAuthors[0]['lastname'])\nif rezensent_string:\n rezensent_string = '(%s)' % real_self.directTranslate(Message(u'presented_by', 'recensio', mapping={u'review_authors': rezensent_string}))\nfull_citation = ... | <|body_start_0|>
self = real_self.magic
rezensent_string = getFormatter(' ')(self.reviewAuthors[0]['firstname'], self.reviewAuthors[0]['lastname'])
if rezensent_string:
rezensent_string = '(%s)' % real_self.directTranslate(Message(u'presented_by', 'recensio', mapping={u'review_author... | PresentationOnlineResourceNoMagic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresentationOnlineResourceNoMagic:
def getDecoratedTitle(real_self):
"""#commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() # >>> at_mock.customCitation = '' # >>> at_mock.title = 'Homepage of SYSLAB.COM GmbH' # >>> presentation = PresentationOnl... | stack_v2_sparse_classes_36k_train_009714 | 16,109 | no_license | [
{
"docstring": "#commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() # >>> at_mock.customCitation = '' # >>> at_mock.title = 'Homepage of SYSLAB.COM GmbH' # >>> presentation = PresentationOnlineResourceNoMagic(at_mock) # >>> presentation.getDecoratedTitle() # u'Homepage ... | 2 | null | Implement the Python class `PresentationOnlineResourceNoMagic` described below.
Class description:
Implement the PresentationOnlineResourceNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self): #commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() ... | Implement the Python class `PresentationOnlineResourceNoMagic` described below.
Class description:
Implement the PresentationOnlineResourceNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self): #commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() ... | acf6ca3c962bfcf50600739087973de3ba7ad124 | <|skeleton|>
class PresentationOnlineResourceNoMagic:
def getDecoratedTitle(real_self):
"""#commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() # >>> at_mock.customCitation = '' # >>> at_mock.title = 'Homepage of SYSLAB.COM GmbH' # >>> presentation = PresentationOnl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresentationOnlineResourceNoMagic:
def getDecoratedTitle(real_self):
"""#commented out, because it is unmaintained # >>> from mock import Mock # >>> at_mock = Mock() # >>> at_mock.customCitation = '' # >>> at_mock.title = 'Homepage of SYSLAB.COM GmbH' # >>> presentation = PresentationOnlineResourceNoM... | the_stack_v2_python_sparse | recensio/contenttypes/content/presentationonlineresource.py | syslabcom/recensio.contenttypes | train | 0 | |
98a4d75f0b3942efbf913683e97c740e5d3a531b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PrinterCapabilities()",
"from .integer_range import IntegerRange\nfrom .print_color_mode import PrintColorMode\nfrom .print_duplex_mode import PrintDuplexMode\nfrom .printer_feed_orientation import PrinterFeedOrientation\nfrom .print_f... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PrinterCapabilities()
<|end_body_0|>
<|body_start_1|>
from .integer_range import IntegerRange
from .print_color_mode import PrintColorMode
from .print_duplex_mode import PrintDup... | PrinterCapabilities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrinterCapabilities:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterCapabilities:
"""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 ob... | stack_v2_sparse_classes_36k_train_009715 | 11,900 | 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: PrinterCapabilities",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `PrinterCapabilities` described below.
Class description:
Implement the PrinterCapabilities class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterCapabilities: Creates a new instance of the appropriate class based on d... | Implement the Python class `PrinterCapabilities` described below.
Class description:
Implement the PrinterCapabilities class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterCapabilities: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrinterCapabilities:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterCapabilities:
"""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 ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrinterCapabilities:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrinterCapabilities:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/printer_capabilities.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3a5739ae36764f3d0a76f7a2bb50dfa434857cae | [
"self.function_to_call = function_to_call\nself.function_to_call_name = function_to_call_name or function_to_call.__name__\nself.logger = logger",
"fulljson = json.loads(request.body)\nargs = fulljson.get('args')\nkwargs = fulljson.get('kwargs')\nkwargs['request'] = request\ntry:\n r = self.function_to_call(*a... | <|body_start_0|>
self.function_to_call = function_to_call
self.function_to_call_name = function_to_call_name or function_to_call.__name__
self.logger = logger
<|end_body_0|>
<|body_start_1|>
fulljson = json.loads(request.body)
args = fulljson.get('args')
kwargs = fulljso... | wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes. | JsonWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
d... | stack_v2_sparse_classes_36k_train_009716 | 13,571 | permissive | [
{
"docstring": ":param function_to_call_name: this name will be used with any error handling, defaults to function_to_call.__name__ should be used in case of using decorators on base function :type function_to_call_name: str :param function_to_call: callable object which will be wrapped by JsonWrapper :type fun... | 2 | null | Implement the Python class `JsonWrapper` described below.
Class description:
wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into ap... | Implement the Python class `JsonWrapper` described below.
Class description:
wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into ap... | 8113673fa13b6fe195cea99dedab9616aeca3ae8 | <|skeleton|>
class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonWrapper:
"""wrapper object for callable object which provides abstraction layer for packing and unpacking json (to function arguments) as well as wrapping function return object into http request, as well as encoding exceptions raised by function into approperiate http status_codes."""
def __init__(s... | the_stack_v2_python_sparse | src/common/restlib.py | jochym/cc1 | train | 0 |
362457624f21d88bf1359329702ae935af5e933b | [
"self.created_time_msecs = created_time_msecs\nself.description = description\nself.domain = domain\nself.last_updated_time_msecs = last_updated_time_msecs\nself.name = name\nself.restricted = restricted\nself.roles = roles\nself.sid = sid\nself.smb_principals = smb_principals\nself.tenant_ids = tenant_ids\nself.us... | <|body_start_0|>
self.created_time_msecs = created_time_msecs
self.description = description
self.domain = domain
self.last_updated_time_msecs = last_updated_time_msecs
self.name = name
self.restricted = restricted
self.roles = roles
self.sid = sid
... | Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group. domain (string): Specifies the domain of the group. last_updated_time_... | Group | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
"""Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group. domain (string): Specifies the domain... | stack_v2_sparse_classes_36k_train_009717 | 5,082 | permissive | [
{
"docstring": "Constructor for the Group class",
"name": "__init__",
"signature": "def __init__(self, created_time_msecs=None, description=None, domain=None, last_updated_time_msecs=None, name=None, restricted=None, roles=None, sid=None, smb_principals=None, tenant_ids=None, usernames=None, users=None)... | 2 | null | Implement the Python class `Group` described below.
Class description:
Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group... | Implement the Python class `Group` described below.
Class description:
Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Group:
"""Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group. domain (string): Specifies the domain... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Group:
"""Implementation of the 'Group' model. Specifies details about the group. Attributes: created_time_msecs (long|int): Specifies the epoch time in milliseconds when the group was created/added. description (string): Specifies a description of the group. domain (string): Specifies the domain of the group... | the_stack_v2_python_sparse | cohesity_management_sdk/models/group.py | cohesity/management-sdk-python | train | 24 |
ef662fc56498e87c3e30d6bb125d87d13aea189f | [
"self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(10, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=11.3)\nself.pump.get_state = MagicMock(return_value='PUMP_IN')\nself.pump.set_state = ... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=11.3)
... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sensor = Senso... | stack_v2_sparse_classes_36k_train_009718 | 3,554 | no_license | [
{
"docstring": "Set up controller for test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test controller tick method",
"name": "test_controller",
"signature": "def test_controller(self)"
}
] | 2 | null | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method
<|skeleton|>
class ControllerTests:
"""Unit tests for the C... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Set up controller for test"""
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.... | the_stack_v2_python_sparse | students/smitco/lesson06/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
386f788ab7515fe91edb6d1d019063b0a083cbe3 | [
"self.found = found\nself.displaying = displaying\nself.more_available = more_available\nself.created_date = created_date\nself.institutions = institutions\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nfound = dictionary.get('found')\ndisplaying = dictionary.get('... | <|body_start_0|>
self.found = found
self.displaying = displaying
self.more_available = more_available
self.created_date = created_date
self.institutions = institutions
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionar... | Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are more institutions to display that match t... | GetInstitutionsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetInstitutionsResponse:
"""Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if ... | stack_v2_sparse_classes_36k_train_009719 | 3,101 | permissive | [
{
"docstring": "Constructor for the GetInstitutionsResponse class",
"name": "__init__",
"signature": "def __init__(self, found=None, displaying=None, more_available=None, created_date=None, institutions=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a ... | 2 | stack_v2_sparse_classes_30k_train_015279 | Implement the Python class `GetInstitutionsResponse` described below.
Class description:
Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying cou... | Implement the Python class `GetInstitutionsResponse` described below.
Class description:
Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying cou... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class GetInstitutionsResponse:
"""Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetInstitutionsResponse:
"""Implementation of the 'Get Institutions Response' model. A list of Finicity financial institutions from the standard get institutions response Attributes: found (int): Total number of results found displaying (int): Displaying count more_available (bool): Indicates if there are mor... | the_stack_v2_python_sparse | finicityapi/models/get_institutions_response.py | monarchmoney/finicity-python | train | 0 |
001c1e1faf46c4bb9c4469df365cde6786c9526a | [
"try:\n return UsageKey.from_string(usage_id)\nexcept InvalidKeyError:\n error_message = ugettext_noop('Invalid usage_id: {usage_id}.').format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, error_status=status.HTTP_404_NOT_FOUND)",
"usage_key_or_response = se... | <|body_start_0|>
try:
return UsageKey.from_string(usage_id)
except InvalidKeyError:
error_message = ugettext_noop('Invalid usage_id: {usage_id}.').format(usage_id=usage_id)
log.error(error_message)
return self.error_response(error_message, error_status=sta... | **Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for GET** Users can only delete their own bookmarks. If the bookmark_id does not belong t... | BookmarksDetailView | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookmarksDetailView:
"""**Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for GET** Users can only delete their own ... | stack_v2_sparse_classes_36k_train_009720 | 13,218 | permissive | [
{
"docstring": "Create and return usage_key or error Response. Arguments: usage_id (string): The id of required block.",
"name": "get_usage_key_or_error_response",
"signature": "def get_usage_key_or_error_response(self, usage_id)"
},
{
"docstring": "Get a specific bookmark for a user. **Example ... | 3 | null | Implement the Python class `BookmarksDetailView` described below.
Class description:
**Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for... | Implement the Python class `BookmarksDetailView` described below.
Class description:
**Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BookmarksDetailView:
"""**Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for GET** Users can only delete their own ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookmarksDetailView:
"""**Use Cases** Get or delete a specific bookmark for a user. **Example Requests**: GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/ **Response for GET** Users can only delete their own bookmarks. If... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/bookmarks/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
1f5e3faf3330b45c3fec6323424104ff061d18fc | [
"starttime = int(time.time())\ncount = 0\nwhile True:\n elements = self.find_elements(by=by, value=value)\n if not elements:\n time.sleep(0.1)\n nowtime = int(time.time())\n if nowtime - starttime > outtime:\n raise TypeError('此xpath未找到元素:{}'.format(value))\n continue\n ... | <|body_start_0|>
starttime = int(time.time())
count = 0
while True:
elements = self.find_elements(by=by, value=value)
if not elements:
time.sleep(0.1)
nowtime = int(time.time())
if nowtime - starttime > outtime:
... | Driver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
def getelement(self, value=None, by=By.XPATH, outtime=10):
"""返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素"""
... | stack_v2_sparse_classes_36k_train_009721 | 6,948 | no_license | [
{
"docstring": "返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素",
"name": "getelement",
"signature": "def getelement(self, value=None, by=By.XP... | 4 | stack_v2_sparse_classes_30k_train_000494 | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def getelement(self, value=None, by=By.XPATH, outtime=10): 返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的... | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def getelement(self, value=None, by=By.XPATH, outtime=10): 返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的... | 504a454503895371a7c5d679684560d4239b81bf | <|skeleton|>
class Driver:
def getelement(self, value=None, by=By.XPATH, outtime=10):
"""返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
def getelement(self, value=None, by=By.XPATH, outtime=10):
"""返回xpath指向的元素,如果指向多个可见的,只返回第一个,能自动过滤网页中的隐藏元素,并且带超时等待 :param value: xpath,或者是用其他方式查找元素依赖的参数 :param by: 默认用xpath的方法去找,也可以根据自己的需求定义 :param outtime: 一个作用是等待元素出现,第二是配置了超时时间,不能低于2s,有可能会导致元素获取不到 :return: webelemnet元素"""
starttime = ... | the_stack_v2_python_sparse | autotest.py | xiaoshihu/learn | train | 2 | |
94354c5836f45be2f6ad0f751c7a9a35f2cfcdf5 | [
"self.stack = stack\nself.window = window\nbigfont = pygame.font.SysFont('mono', 100)\ntitle = Text('Paused', bigfont, MENU_TEXT_COLOR)\nself.game_objects = []\nself.game_objects.append(ShutterAnimation(title, Container(), TEXT_SPEED, window))",
"if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n s... | <|body_start_0|>
self.stack = stack
self.window = window
bigfont = pygame.font.SysFont('mono', 100)
title = Text('Paused', bigfont, MENU_TEXT_COLOR)
self.game_objects = []
self.game_objects.append(ShutterAnimation(title, Container(), TEXT_SPEED, window))
<|end_body_0|>
<... | PauseState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PauseState:
def __init__(self, stack, window, unused_args):
"""Sets up the pause screen."""
<|body_0|>
def handle_event(self, event):
"""Handles events for the pause screen."""
<|body_1|>
def update(self, dt):
"""Updates the pause screen."""
... | stack_v2_sparse_classes_36k_train_009722 | 1,306 | no_license | [
{
"docstring": "Sets up the pause screen.",
"name": "__init__",
"signature": "def __init__(self, stack, window, unused_args)"
},
{
"docstring": "Handles events for the pause screen.",
"name": "handle_event",
"signature": "def handle_event(self, event)"
},
{
"docstring": "Updates ... | 4 | stack_v2_sparse_classes_30k_train_006659 | Implement the Python class `PauseState` described below.
Class description:
Implement the PauseState class.
Method signatures and docstrings:
- def __init__(self, stack, window, unused_args): Sets up the pause screen.
- def handle_event(self, event): Handles events for the pause screen.
- def update(self, dt): Update... | Implement the Python class `PauseState` described below.
Class description:
Implement the PauseState class.
Method signatures and docstrings:
- def __init__(self, stack, window, unused_args): Sets up the pause screen.
- def handle_event(self, event): Handles events for the pause screen.
- def update(self, dt): Update... | de73b681c7522a38c9bc5837ef8fc12ab015cba0 | <|skeleton|>
class PauseState:
def __init__(self, stack, window, unused_args):
"""Sets up the pause screen."""
<|body_0|>
def handle_event(self, event):
"""Handles events for the pause screen."""
<|body_1|>
def update(self, dt):
"""Updates the pause screen."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PauseState:
def __init__(self, stack, window, unused_args):
"""Sets up the pause screen."""
self.stack = stack
self.window = window
bigfont = pygame.font.SysFont('mono', 100)
title = Text('Paused', bigfont, MENU_TEXT_COLOR)
self.game_objects = []
self.ga... | the_stack_v2_python_sparse | pausestate.py | cadaeibfe/snake | train | 0 | |
d13a366a9ad528c27f99df64163697bbade68bc2 | [
"vnum = len(mat)\nfor x in mat:\n if len(x) != vnum:\n raise ValueError(\"Argument for 'GraphAL'.\")\nself._mat = [Graph._out_edges(mat[i], unconn) for i in range(vnum)]\nself._vnum = vnum\nself._unconn = unconn",
"self._mat.append([])\nself._vnum += 1\nreturn self._vnum - 1",
"if self._vnum == 0:\n ... | <|body_start_0|>
vnum = len(mat)
for x in mat:
if len(x) != vnum:
raise ValueError("Argument for 'GraphAL'.")
self._mat = [Graph._out_edges(mat[i], unconn) for i in range(vnum)]
self._vnum = vnum
self._unconn = unconn
<|end_body_0|>
<|body_start_1|>
... | 图的邻接表的实现 | GraphAL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphAL:
"""图的邻接表的实现"""
def __init__(self, mat=[], unconn=0):
"""支持通过空图构建所需图对象"""
<|body_0|>
def add_vertex(self):
"""增加一个新的顶点到图中"""
<|body_1|>
def add_edge(self, vi, vj, val=1):
"""增加一条新的边 加入的新边按照邻接矩阵的下标顺序排列"""
<|body_2|>
def ge... | stack_v2_sparse_classes_36k_train_009723 | 5,289 | permissive | [
{
"docstring": "支持通过空图构建所需图对象",
"name": "__init__",
"signature": "def __init__(self, mat=[], unconn=0)"
},
{
"docstring": "增加一个新的顶点到图中",
"name": "add_vertex",
"signature": "def add_vertex(self)"
},
{
"docstring": "增加一条新的边 加入的新边按照邻接矩阵的下标顺序排列",
"name": "add_edge",
"signatur... | 5 | null | Implement the Python class `GraphAL` described below.
Class description:
图的邻接表的实现
Method signatures and docstrings:
- def __init__(self, mat=[], unconn=0): 支持通过空图构建所需图对象
- def add_vertex(self): 增加一个新的顶点到图中
- def add_edge(self, vi, vj, val=1): 增加一条新的边 加入的新边按照邻接矩阵的下标顺序排列
- def get_edge(self, vi, vj): 取得两点之间的边
- def out... | Implement the Python class `GraphAL` described below.
Class description:
图的邻接表的实现
Method signatures and docstrings:
- def __init__(self, mat=[], unconn=0): 支持通过空图构建所需图对象
- def add_vertex(self): 增加一个新的顶点到图中
- def add_edge(self, vi, vj, val=1): 增加一条新的边 加入的新边按照邻接矩阵的下标顺序排列
- def get_edge(self, vi, vj): 取得两点之间的边
- def out... | 72eabb5fcc9fafb17172879c1250d3c9553e583d | <|skeleton|>
class GraphAL:
"""图的邻接表的实现"""
def __init__(self, mat=[], unconn=0):
"""支持通过空图构建所需图对象"""
<|body_0|>
def add_vertex(self):
"""增加一个新的顶点到图中"""
<|body_1|>
def add_edge(self, vi, vj, val=1):
"""增加一条新的边 加入的新边按照邻接矩阵的下标顺序排列"""
<|body_2|>
def ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphAL:
"""图的邻接表的实现"""
def __init__(self, mat=[], unconn=0):
"""支持通过空图构建所需图对象"""
vnum = len(mat)
for x in mat:
if len(x) != vnum:
raise ValueError("Argument for 'GraphAL'.")
self._mat = [Graph._out_edges(mat[i], unconn) for i in range(vnum)]
... | the_stack_v2_python_sparse | Chapter7/graph_adt.py | qimanchen/Algorithm_Python | train | 0 |
badd8a46e8573256afda400effd330d022f7db1c | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | BotService exposes operations for interacting with remote bots/workers. | BotServiceServicer | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotServiceServicer:
"""BotService exposes operations for interacting with remote bots/workers."""
def Handshake(self, request, context):
"""Handshake implements the initial handshake from a bot to Swarming."""
<|body_0|>
def BotUpdate(self, request, context):
"""... | stack_v2_sparse_classes_36k_train_009724 | 4,767 | permissive | [
{
"docstring": "Handshake implements the initial handshake from a bot to Swarming.",
"name": "Handshake",
"signature": "def Handshake(self, request, context)"
},
{
"docstring": "BotUpdate requests a version of the bot code.",
"name": "BotUpdate",
"signature": "def BotUpdate(self, request... | 5 | stack_v2_sparse_classes_30k_train_011272 | Implement the Python class `BotServiceServicer` described below.
Class description:
BotService exposes operations for interacting with remote bots/workers.
Method signatures and docstrings:
- def Handshake(self, request, context): Handshake implements the initial handshake from a bot to Swarming.
- def BotUpdate(self... | Implement the Python class `BotServiceServicer` described below.
Class description:
BotService exposes operations for interacting with remote bots/workers.
Method signatures and docstrings:
- def Handshake(self, request, context): Handshake implements the initial handshake from a bot to Swarming.
- def BotUpdate(self... | 3fa4c520dddd82ed190152709e0a54b35faa3bae | <|skeleton|>
class BotServiceServicer:
"""BotService exposes operations for interacting with remote bots/workers."""
def Handshake(self, request, context):
"""Handshake implements the initial handshake from a bot to Swarming."""
<|body_0|>
def BotUpdate(self, request, context):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BotServiceServicer:
"""BotService exposes operations for interacting with remote bots/workers."""
def Handshake(self, request, context):
"""Handshake implements the initial handshake from a bot to Swarming."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Me... | the_stack_v2_python_sparse | appengine/swarming/swarming_bot/proto_bot/swarming_bot_pb2_grpc.py | Slayo2008/New2 | train | 1 |
9ba29e43c79724d3cd2c42e23d9691fdbe618096 | [
"self.performance_pf_dict = {Performance.PERFORMANCE_PF_COL_ITERATION: [], Performance.PERFORMANCE_PF_COL_PATHFINDING_ITERATION: [], Performance.PERFORMANCE_PF_COL_PERSON_ID: [], Performance.PERFORMANCE_PF_COL_PERSON_TRIP_ID: [], Performance.PERFORMANCE_PF_COL_PROCESS_NUM: [], Performance.PERFORMANCE_PF_COL_PATHFIN... | <|body_start_0|>
self.performance_pf_dict = {Performance.PERFORMANCE_PF_COL_ITERATION: [], Performance.PERFORMANCE_PF_COL_PATHFINDING_ITERATION: [], Performance.PERFORMANCE_PF_COL_PERSON_ID: [], Performance.PERFORMANCE_PF_COL_PERSON_TRIP_ID: [], Performance.PERFORMANCE_PF_COL_PROCESS_NUM: [], Performance.PERFOR... | Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops. | Performance | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Performance:
"""Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops."""
def __init__(self):
"""Constructor. Initialize empty dataframe for performance info."""
... | stack_v2_sparse_classes_36k_train_009725 | 11,295 | permissive | [
{
"docstring": "Constructor. Initialize empty dataframe for performance info.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add this row to the performance dict of arrays. Assumes time values are in milliseconds.",
"name": "add_info",
"signature": "def add_in... | 6 | stack_v2_sparse_classes_30k_train_008256 | Implement the Python class `Performance` described below.
Class description:
Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops.
Method signatures and docstrings:
- def __init__(self): Constructor... | Implement the Python class `Performance` described below.
Class description:
Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops.
Method signatures and docstrings:
- def __init__(self): Constructor... | a2549936b2707b00d6c21b4e6ae4be8fefd0aa46 | <|skeleton|>
class Performance:
"""Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops."""
def __init__(self):
"""Constructor. Initialize empty dataframe for performance info."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Performance:
"""Performance class. Keeps track of performance information (time spent, number of labeling iterations, etc) related to pathfinding in Fast-Trips and for the the bigger loops."""
def __init__(self):
"""Constructor. Initialize empty dataframe for performance info."""
self.per... | the_stack_v2_python_sparse | fasttrips/Performance.py | pedrocamargo/fast-trips | train | 3 |
899813d6c430bada0e3e38b84264c07ff6d6cb91 | [
"super(LAMBOptimizer_v2, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nself.include_in_weight_decay = include_in_weight_decay... | <|body_start_0|>
super(LAMBOptimizer_v2, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight... | LAMB (Layer-wise Adaptive Moments optimizer for Batch training). | LAMBOptimizer_v2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LAMBOptimizer_v2:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_fro... | stack_v2_sparse_classes_36k_train_009726 | 25,398 | permissive | [
{
"docstring": "Constructs a LAMBOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=No... | 5 | stack_v2_sparse_classes_30k_train_016058 | Implement the Python class `LAMBOptimizer_v2` described below.
Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, inclu... | Implement the Python class `LAMBOptimizer_v2` described below.
Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, inclu... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class LAMBOptimizer_v2:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LAMBOptimizer_v2:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adapt... | the_stack_v2_python_sparse | t2t_bert/optimizer/optimizer_utils.py | yyht/BERT | train | 37 |
7e3d1048b73e234020ae2b957f547c95734188d7 | [
"self.dimension = dimension\nself.coneSize = maxConeSize\nself.nvertices = numVertices\nself.ncells = numCells\nself.cellType = None\nself.initialize()\nreturn",
"from Mesh import cellTypes\ntry:\n if self.coneSize > 0:\n self.cellType = cellTypes[self.dimension, self.coneSize]\nexcept:\n raise Value... | <|body_start_0|>
self.dimension = dimension
self.coneSize = maxConeSize
self.nvertices = numVertices
self.ncells = numCells
self.cellType = None
self.initialize()
return
<|end_body_0|>
<|body_start_1|>
from Mesh import cellTypes
try:
i... | Fault object for holding mesh memory and performance information. | Fault | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fault:
"""Fault object for holding mesh memory and performance information."""
def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0):
"""Constructor."""
<|body_0|>
def initialize(self):
"""Initialize application."""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_009727 | 1,894 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0)"
},
{
"docstring": "Initialize application.",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "Tabulate memory us... | 3 | stack_v2_sparse_classes_30k_train_012625 | Implement the Python class `Fault` described below.
Class description:
Fault object for holding mesh memory and performance information.
Method signatures and docstrings:
- def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0): Constructor.
- def initialize(self): Initialize application.
- def tab... | Implement the Python class `Fault` described below.
Class description:
Fault object for holding mesh memory and performance information.
Method signatures and docstrings:
- def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0): Constructor.
- def initialize(self): Initialize application.
- def tab... | 8d0170324d3fcdc5e6c4281759c680faa5dd8d38 | <|skeleton|>
class Fault:
"""Fault object for holding mesh memory and performance information."""
def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0):
"""Constructor."""
<|body_0|>
def initialize(self):
"""Initialize application."""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fault:
"""Fault object for holding mesh memory and performance information."""
def __init__(self, dimension=0, maxConeSize=0, numVertices=0, numCells=0):
"""Constructor."""
self.dimension = dimension
self.coneSize = maxConeSize
self.nvertices = numVertices
self.nce... | the_stack_v2_python_sparse | pylith/perf/Fault.py | rwalkerlewis/pylith | train | 0 |
1ee2bd26742610b22d1de9c6d14743acaf3f1a7b | [
"if self.start is None or self.end is None:\n return 0\nlon1, lat1, lon2, lat2 = map(radians, [float(self.start.longitude), float(self.start.latitude), float(self.end.longitude), float(self.end.latitude)])\ndlon = lon2 - lon1\ndlat = lat2 - lat1\na = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** ... | <|body_start_0|>
if self.start is None or self.end is None:
return 0
lon1, lat1, lon2, lat2 = map(radians, [float(self.start.longitude), float(self.start.latitude), float(self.end.longitude), float(self.end.latitude)])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dla... | Trip | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trip:
def price(self):
"""Returns the price of the trip based on the distance of the trip."""
<|body_0|>
def change_status(self, new_status):
"""Change the status based on the status coming in and the previous status."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_009728 | 2,527 | permissive | [
{
"docstring": "Returns the price of the trip based on the distance of the trip.",
"name": "price",
"signature": "def price(self)"
},
{
"docstring": "Change the status based on the status coming in and the previous status.",
"name": "change_status",
"signature": "def change_status(self, ... | 2 | stack_v2_sparse_classes_30k_train_003569 | Implement the Python class `Trip` described below.
Class description:
Implement the Trip class.
Method signatures and docstrings:
- def price(self): Returns the price of the trip based on the distance of the trip.
- def change_status(self, new_status): Change the status based on the status coming in and the previous ... | Implement the Python class `Trip` described below.
Class description:
Implement the Trip class.
Method signatures and docstrings:
- def price(self): Returns the price of the trip based on the distance of the trip.
- def change_status(self, new_status): Change the status based on the status coming in and the previous ... | c93f9afcc3fc435ee4646a294397120ed9a41f15 | <|skeleton|>
class Trip:
def price(self):
"""Returns the price of the trip based on the distance of the trip."""
<|body_0|>
def change_status(self, new_status):
"""Change the status based on the status coming in and the previous status."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trip:
def price(self):
"""Returns the price of the trip based on the distance of the trip."""
if self.start is None or self.end is None:
return 0
lon1, lat1, lon2, lat2 = map(radians, [float(self.start.longitude), float(self.start.latitude), float(self.end.longitude), float... | the_stack_v2_python_sparse | bmw/models/_trip.py | newtonjain/hacktheplanet | train | 5 | |
2134575ba26d013f4f1ba27f201ba899127bdc73 | [
"if os.path.isdir(episode_directory):\n self.episode_directory = episode_directory\n info_path = os.path.join(self.episode_directory, 'info.json')\n with open(info_path, 'r') as json_file:\n info_dict = json.load(json_file)\n self.max_episode_index = info_dict['max_episode_index']\n se... | <|body_start_0|>
if os.path.isdir(episode_directory):
self.episode_directory = episode_directory
info_path = os.path.join(self.episode_directory, 'info.json')
with open(info_path, 'r') as json_file:
info_dict = json.load(json_file)
self.max_epi... | DataLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLoader:
def __init__(self, episode_directory):
"""This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory: (str) directory where it holds all the logged episodes."""
<|body_0|>
def get_episode... | stack_v2_sparse_classes_36k_train_009729 | 2,435 | permissive | [
{
"docstring": "This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory: (str) directory where it holds all the logged episodes.",
"name": "__init__",
"signature": "def __init__(self, episode_directory)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_002054 | Implement the Python class `DataLoader` described below.
Class description:
Implement the DataLoader class.
Method signatures and docstrings:
- def __init__(self, episode_directory): This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory:... | Implement the Python class `DataLoader` described below.
Class description:
Implement the DataLoader class.
Method signatures and docstrings:
- def __init__(self, episode_directory): This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory:... | 548e66c36fba01125cf6290992dfd833ae42709b | <|skeleton|>
class DataLoader:
def __init__(self, episode_directory):
"""This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory: (str) directory where it holds all the logged episodes."""
<|body_0|>
def get_episode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataLoader:
def __init__(self, episode_directory):
"""This initializes a data loader that loads recorded episodes using a causal_world.loggers.DataRecorder object. :param episode_directory: (str) directory where it holds all the logged episodes."""
if os.path.isdir(episode_directory):
... | the_stack_v2_python_sparse | causal_world/loggers/data_loader.py | InspectorDidi/CausalWorld | train | 0 | |
5e876f8aeebddb333e399b42e36009c24e8f7e7f | [
"q = Q(pub_state='public')\nif user and user.is_authenticated():\n if user.is_member:\n q |= Q(pub_state='protected')\nreturn self.filter(q)",
"if user and user.is_staff:\n return self.filter(pub_state='draft')\nreturn self.none()"
] | <|body_start_0|>
q = Q(pub_state='public')
if user and user.is_authenticated():
if user.is_member:
q |= Q(pub_state='protected')
return self.filter(q)
<|end_body_0|>
<|body_start_1|>
if user and user.is_staff:
return self.filter(pub_state='draft')... | AnnouncementManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnouncementManager:
def published(self, user):
"""指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状態が `public` もしくは `protected` のものを、それ以外の場合 は公開状態が `public` になっているものだけを含む。 Args: user (User instance): Djangoの... | stack_v2_sparse_classes_36k_train_009730 | 3,888 | no_license | [
{
"docstring": "指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状態が `public` もしくは `protected` のものを、それ以外の場合 は公開状態が `public` になっているものだけを含む。 Args: user (User instance): DjangoのUserモデル Returns: 指定されたユーザーに対して公開されているAnnouncementインスタンスを 含む... | 2 | null | Implement the Python class `AnnouncementManager` described below.
Class description:
Implement the AnnouncementManager class.
Method signatures and docstrings:
- def published(self, user): 指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状... | Implement the Python class `AnnouncementManager` described below.
Class description:
Implement the AnnouncementManager class.
Method signatures and docstrings:
- def published(self, user): 指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状... | 8f9a850c4df41b0fc1da5b73189772552d5cd531 | <|skeleton|>
class AnnouncementManager:
def published(self, user):
"""指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状態が `public` もしくは `protected` のものを、それ以外の場合 は公開状態が `public` になっているものだけを含む。 Args: user (User instance): Djangoの... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnouncementManager:
def published(self, user):
"""指定されたユーザーに対して公開されているAnnouncementインスタンスを含む クエリを返す。 公開状態は指定されたユーザの所属によって変化する。 ユーザーが認証ユーザかつ[seele, nerv, chidlren]のいずれかに属している 場合は公開状態が `public` もしくは `protected` のものを、それ以外の場合 は公開状態が `public` になっているものだけを含む。 Args: user (User instance): DjangoのUserモデル Return... | the_stack_v2_python_sparse | src/kawaz/apps/announcements/models.py | kawazrepos/Kawaz3rd | train | 7 | |
18e5083aad98f026f91945950a2bc9799bdc7e20 | [
"IS_POPUP_VAR = '_popup'\nTO_FIELD_VAR = '_to_field'\nif IS_POPUP_VAR in request.POST:\n to_field = request.POST.get(TO_FIELD_VAR)\n if to_field:\n attr = str(to_field)\n else:\n attr = obj._meta.pk.attname\n value = obj.serializable_value(attr)\n popup_response_data = json.dumps({'valu... | <|body_start_0|>
IS_POPUP_VAR = '_popup'
TO_FIELD_VAR = '_to_field'
if IS_POPUP_VAR in request.POST:
to_field = request.POST.get(TO_FIELD_VAR)
if to_field:
attr = str(to_field)
else:
attr = obj._meta.pk.attname
value... | LocationAdmin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationAdmin:
def response_add(self, request, obj, post_url_continue=None):
"""This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID."""
<|body_0|>
def response_change(self, r... | stack_v2_sparse_classes_36k_train_009731 | 42,558 | permissive | [
{
"docstring": "This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID.",
"name": "response_add",
"signature": "def response_add(self, request, obj, post_url_continue=None)"
},
{
"docstring": "This ... | 2 | null | Implement the Python class `LocationAdmin` described below.
Class description:
Implement the LocationAdmin class.
Method signatures and docstrings:
- def response_add(self, request, obj, post_url_continue=None): This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added ... | Implement the Python class `LocationAdmin` described below.
Class description:
Implement the LocationAdmin class.
Method signatures and docstrings:
- def response_add(self, request, obj, post_url_continue=None): This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added ... | 19db3e83e76ea2002ee841989410d12d1e601023 | <|skeleton|>
class LocationAdmin:
def response_add(self, request, obj, post_url_continue=None):
"""This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID."""
<|body_0|>
def response_change(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationAdmin:
def response_add(self, request, obj, post_url_continue=None):
"""This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID."""
IS_POPUP_VAR = '_popup'
TO_FIELD_VAR = '_to_field... | the_stack_v2_python_sparse | danceschool/core/admin.py | django-danceschool/django-danceschool | train | 40 | |
70c89b66030eaa774295370aab09a7d746d2de93 | [
"exclude_names = ['name', 'deployable']\ninclude_names = ['deploy_local_files', 'deploy_local_archive', 'deploy_remote_archive']\nreturn [f.name for f in fields(cls) if f.name not in exclude_names] + include_names",
"warn_unknown_fields(cls.get_valid_config_parser_fields(), sec)\n\ndef gettuple(key: str) -> Tuple... | <|body_start_0|>
exclude_names = ['name', 'deployable']
include_names = ['deploy_local_files', 'deploy_local_archive', 'deploy_remote_archive']
return [f.name for f in fields(cls) if f.name not in exclude_names] + include_names
<|end_body_0|>
<|body_start_1|>
warn_unknown_fields(cls.get... | Engine configuration | Engine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Engine:
"""Engine configuration"""
def get_valid_config_parser_fields(cls) -> Sequence[str]:
"""Returns a list of valid config keys"""
<|body_0|>
def from_config_parser_section(cls, sec: SectionProxy, engines_dir: PurePath) -> 'Engine':
"""Create config from conf... | stack_v2_sparse_classes_36k_train_009732 | 5,448 | permissive | [
{
"docstring": "Returns a list of valid config keys",
"name": "get_valid_config_parser_fields",
"signature": "def get_valid_config_parser_fields(cls) -> Sequence[str]"
},
{
"docstring": "Create config from config parser's section",
"name": "from_config_parser_section",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_006841 | Implement the Python class `Engine` described below.
Class description:
Engine configuration
Method signatures and docstrings:
- def get_valid_config_parser_fields(cls) -> Sequence[str]: Returns a list of valid config keys
- def from_config_parser_section(cls, sec: SectionProxy, engines_dir: PurePath) -> 'Engine': Cr... | Implement the Python class `Engine` described below.
Class description:
Engine configuration
Method signatures and docstrings:
- def get_valid_config_parser_fields(cls) -> Sequence[str]: Returns a list of valid config keys
- def from_config_parser_section(cls, sec: SectionProxy, engines_dir: PurePath) -> 'Engine': Cr... | 70e1a52c018ac3859df48293b509d97cc1c617a8 | <|skeleton|>
class Engine:
"""Engine configuration"""
def get_valid_config_parser_fields(cls) -> Sequence[str]:
"""Returns a list of valid config keys"""
<|body_0|>
def from_config_parser_section(cls, sec: SectionProxy, engines_dir: PurePath) -> 'Engine':
"""Create config from conf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Engine:
"""Engine configuration"""
def get_valid_config_parser_fields(cls) -> Sequence[str]:
"""Returns a list of valid config keys"""
exclude_names = ['name', 'deployable']
include_names = ['deploy_local_files', 'deploy_local_archive', 'deploy_remote_archive']
return [f.n... | the_stack_v2_python_sparse | yascheduler/config/engine.py | tilde-lab/yascheduler | train | 6 |
397712fb8f2369fc535f77090b6f6264002cb1f0 | [
"def inorderSerialize(node):\n if not node:\n return ''\n return inorderSerialize(node.left) + str(node.val) + inorderSerialize(node.right)\n\ndef preorderSerialize(node):\n if not node:\n return ''\n return str(node.val) + preorderSerialize(node.left) + preorderSerialize(node.right)\ns1 =... | <|body_start_0|>
def inorderSerialize(node):
if not node:
return ''
return inorderSerialize(node.left) + str(node.val) + inorderSerialize(node.right)
def preorderSerialize(node):
if not node:
return ''
return str(node.val) ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_009733 | 2,710 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_007796 | 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:... | 1461b10b8910fa90a311939c6df9082a8526f9b1 | <|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 inorderSerialize(node):
if not node:
return ''
return inorderSerialize(node.left) + str(node.val) + inorderSerialize(node.right)
def ... | the_stack_v2_python_sparse | Hard/297_serialize&DeserializeBinaryTree.py | Yucheng7713/CodingPracticeByYuch | train | 0 | |
66da427a98ce2181c375eba5f94231f59d095d1a | [
"std = data.GetInt32(self.COMPRESSION, self.STANDARD_COMP)\nwhile True:\n result = c4d.gui.InputDialog(title='Compression', preset=std)\n if result is None:\n return True\n try:\n result = int(result)\n except ValueError as e:\n c4d.gui.MessageDialog(str(e), c4d.GEMB_OK)\n co... | <|body_start_0|>
std = data.GetInt32(self.COMPRESSION, self.STANDARD_COMP)
while True:
result = c4d.gui.InputDialog(title='Compression', preset=std)
if result is None:
return True
try:
result = int(result)
except ValueError ... | Data class to export a *.xample file | MyXampleSaver | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyXampleSaver:
"""Data class to export a *.xample file"""
def Edit(self, data):
"""Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dialog opened successfully"""
<|body_0|>
def Sa... | stack_v2_sparse_classes_36k_train_009734 | 4,452 | permissive | [
{
"docstring": "Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dialog opened successfully",
"name": "Edit",
"signature": "def Edit(self, data)"
},
{
"docstring": "Called by Cinema 4D, when the plugin sh... | 2 | null | Implement the Python class `MyXampleSaver` described below.
Class description:
Data class to export a *.xample file
Method signatures and docstrings:
- def Edit(self, data): Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dia... | Implement the Python class `MyXampleSaver` described below.
Class description:
Data class to export a *.xample file
Method signatures and docstrings:
- def Edit(self, data): Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dia... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class MyXampleSaver:
"""Data class to export a *.xample file"""
def Edit(self, data):
"""Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dialog opened successfully"""
<|body_0|>
def Sa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyXampleSaver:
"""Data class to export a *.xample file"""
def Edit(self, data):
"""Called by Cinema 4D, to query the option for the exporter. Args: data (c4d.BaseContainer): The settings for the plugin. Returns: True if the dialog opened successfully"""
std = data.GetInt32(self.COMPRESSIO... | the_stack_v2_python_sparse | plugins/py-xample_saver_r23/py-xample_saver_r23.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 |
e3040cef11a8a41dc73c20b319768b85ac1f5024 | [
"for v in variables:\n if v.systematics_funcs == 'suffix':\n v.fillSystematicsSuffix(systematics)\nself.variables_dict = OrderedDict([(v.name, v) for v in variables])",
"ret = OrderedDict()\nfor vname, v in self.variables_dict.items():\n if schema in v.schema:\n ret[vname] = v.getValue(event, ... | <|body_start_0|>
for v in variables:
if v.systematics_funcs == 'suffix':
v.fillSystematicsSuffix(systematics)
self.variables_dict = OrderedDict([(v.name, v) for v in variables])
<|end_body_0|>
<|body_start_1|>
ret = OrderedDict()
for vname, v in self.variable... | Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event | Desc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Desc:
"""Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event"""
def __init__(self, systematics, variables=[]):
"""Creates the event description based on a list of variables Args: systematics (list of string): systematics... | stack_v2_sparse_classes_36k_train_009735 | 34,880 | no_license | [
{
"docstring": "Creates the event description based on a list of variables Args: systematics (list of string): systematics to use for variable lookup variables (list, optional): Variables to use",
"name": "__init__",
"signature": "def __init__(self, systematics, variables=[])"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_019202 | Implement the Python class `Desc` described below.
Class description:
Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event
Method signatures and docstrings:
- def __init__(self, systematics, variables=[]): Creates the event description based on a list of ... | Implement the Python class `Desc` described below.
Class description:
Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event
Method signatures and docstrings:
- def __init__(self, systematics, variables=[]): Creates the event description based on a list of ... | d33786f405792cafee22658b40d04f59e37f799b | <|skeleton|>
class Desc:
"""Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event"""
def __init__(self, systematics, variables=[]):
"""Creates the event description based on a list of variables Args: systematics (list of string): systematics... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Desc:
"""Event description with varying systematics Attributes: variables_dict (dict of string->Var): Variables in the event"""
def __init__(self, systematics, variables=[]):
"""Creates the event description based on a list of variables Args: systematics (list of string): systematics to use for v... | the_stack_v2_python_sparse | Plotting/python/joosep/sparsinator.py | jpata/tthbb13 | train | 2 |
9cfbd306ecfcf57a6173b36cda1914792640c030 | [
"if content_type == CONTENT_TYPE_XML:\n dois, errors = DOIOstiXmlWebParser.parse_dois_from_label(label_text)\nelif content_type == CONTENT_TYPE_JSON:\n dois, errors = DOIOstiJsonWebParser.parse_dois_from_label(label_text)\nelse:\n raise InputFormatException(f'Unsupported content type provided. Value must b... | <|body_start_0|>
if content_type == CONTENT_TYPE_XML:
dois, errors = DOIOstiXmlWebParser.parse_dois_from_label(label_text)
elif content_type == CONTENT_TYPE_JSON:
dois, errors = DOIOstiJsonWebParser.parse_dois_from_label(label_text)
else:
raise InputFormatExce... | Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats. | DOIOstiWebParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DOIOstiWebParser:
"""Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats."""
def parse_dois_from_label(label_text, content_type=CONTENT_TYPE_XML):
"""Parses one or more Doi objects from ... | stack_v2_sparse_classes_36k_train_009736 | 24,762 | permissive | [
{
"docstring": "Parses one or more Doi objects from the provided OSTI-format label. Parameters ---------- label_text : str Text body of the OSTI label to parse. content_type : str The format of the label's content. Both 'xml' and 'json' are currently supported. Returns ------- dois : list of Doi Doi objects par... | 2 | stack_v2_sparse_classes_30k_train_020823 | Implement the Python class `DOIOstiWebParser` described below.
Class description:
Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats.
Method signatures and docstrings:
- def parse_dois_from_label(label_text, content_typ... | Implement the Python class `DOIOstiWebParser` described below.
Class description:
Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats.
Method signatures and docstrings:
- def parse_dois_from_label(label_text, content_typ... | 3241838aa7a189cc1b9542c5171551eacbbd1972 | <|skeleton|>
class DOIOstiWebParser:
"""Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats."""
def parse_dois_from_label(label_text, content_type=CONTENT_TYPE_XML):
"""Parses one or more Doi objects from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DOIOstiWebParser:
"""Class used to parse Doi objects from DOI records returned from the OSTI DOI service. This class supports parsing records in both XML and JSON formats."""
def parse_dois_from_label(label_text, content_type=CONTENT_TYPE_XML):
"""Parses one or more Doi objects from the provided ... | the_stack_v2_python_sparse | src/pds_doi_service/core/outputs/osti/osti_web_parser.py | NASA-PDS/doi-service | train | 0 |
2f1dd4047b8f2b459f1514375ed1d1a629f2fcf2 | [
"self.env = env\nassert len(state_terminal) == env.no_states\nself.state_terminal = state_terminal",
"if abs(state[0] - self.state_terminal[0]) > 1.5:\n return True\nelif abs(state[1] - self.state_terminal[1]) > radians(60):\n return True\nelif abs(state[2] - self.state_terminal[2]) > 1000:\n return True... | <|body_start_0|>
self.env = env
assert len(state_terminal) == env.no_states
self.state_terminal = state_terminal
<|end_body_0|>
<|body_start_1|>
if abs(state[0] - self.state_terminal[0]) > 1.5:
return True
elif abs(state[1] - self.state_terminal[1]) > radians(60):
... | CartPoleBound | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartPoleBound:
def __init__(self, env, state_terminal):
"""Input: env : dynamics of the system"""
<|body_0|>
def end_episode(self, state):
"""Input: state : state at time t"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.env = env
asser... | stack_v2_sparse_classes_36k_train_009737 | 1,738 | no_license | [
{
"docstring": "Input: env : dynamics of the system",
"name": "__init__",
"signature": "def __init__(self, env, state_terminal)"
},
{
"docstring": "Input: state : state at time t",
"name": "end_episode",
"signature": "def end_episode(self, state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005542 | Implement the Python class `CartPoleBound` described below.
Class description:
Implement the CartPoleBound class.
Method signatures and docstrings:
- def __init__(self, env, state_terminal): Input: env : dynamics of the system
- def end_episode(self, state): Input: state : state at time t | Implement the Python class `CartPoleBound` described below.
Class description:
Implement the CartPoleBound class.
Method signatures and docstrings:
- def __init__(self, env, state_terminal): Input: env : dynamics of the system
- def end_episode(self, state): Input: state : state at time t
<|skeleton|>
class CartPole... | 39de89ab859c894e569398636363f1b9731cedfb | <|skeleton|>
class CartPoleBound:
def __init__(self, env, state_terminal):
"""Input: env : dynamics of the system"""
<|body_0|>
def end_episode(self, state):
"""Input: state : state at time t"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartPoleBound:
def __init__(self, env, state_terminal):
"""Input: env : dynamics of the system"""
self.env = env
assert len(state_terminal) == env.no_states
self.state_terminal = state_terminal
def end_episode(self, state):
"""Input: state : state at time t"""
... | the_stack_v2_python_sparse | srcpy/model_free/bounds.py | avadesh02/fml-project | train | 0 | |
46bb0e75a2642b857c6fcf738230900d93dafce1 | [
"super().__init__(interval=interval)\nself._callback = func\nself._num_args = len(inspect.signature(func).parameters)\nif not 0 < self._num_args < 3:\n raise ValueError(f'`func` must be a function accepting one or two arguments, not {self._num_args}')",
"if self._num_args == 1:\n self._callback(field)\nelse... | <|body_start_0|>
super().__init__(interval=interval)
self._callback = func
self._num_args = len(inspect.signature(func).parameters)
if not 0 < self._num_args < 3:
raise ValueError(f'`func` must be a function accepting one or two arguments, not {self._num_args}')
<|end_body_0|... | Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker = CallbackTracker(check_simulation, interval="0:10") Adding :code:`tracker` to the... | CallbackTracker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallbackTracker:
"""Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker = CallbackTracker(check_simulation, int... | stack_v2_sparse_classes_36k_train_009738 | 37,567 | permissive | [
{
"docstring": "Args: func: The function to call periodically. The function signature should be `(state)` or `(state, time)`, where `state` contains the current state as an instance of :class:`~pde.fields.base.FieldBase` and `time` is a float value indicating the current time. Note that only a view of the state... | 2 | stack_v2_sparse_classes_30k_train_003383 | Implement the Python class `CallbackTracker` described below.
Class description:
Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker ... | Implement the Python class `CallbackTracker` described below.
Class description:
Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker ... | d9c931a8361eaf27bc3766daba26edc11756b5f5 | <|skeleton|>
class CallbackTracker:
"""Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker = CallbackTracker(check_simulation, int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallbackTracker:
"""Tracker calling a function periodically Example: The callback tracker can be used to check for conditions during the simulation: .. code-block:: python def check_simulation(state, time): if state.integral < 0: raise StopIteration tracker = CallbackTracker(check_simulation, interval="0:10")... | the_stack_v2_python_sparse | pde/trackers/trackers.py | zwicker-group/py-pde | train | 327 |
4e3db39e3ec945f9491a2106fb84305dad86d1b6 | [
"rslt = []\nif not root:\n return rslt\nrslt.extend(self.inorderTraversal(root.left))\nrslt.append(root.val)\nrslt.extend(self.inorderTraversal(root.right))\nreturn rslt",
"rslt = []\nstack = []\nwhile stack or root:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()... | <|body_start_0|>
rslt = []
if not root:
return rslt
rslt.extend(self.inorderTraversal(root.left))
rslt.append(root.val)
rslt.extend(self.inorderTraversal(root.right))
return rslt
<|end_body_0|>
<|body_start_1|>
rslt = []
stack = []
whi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversalIterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rslt = []
... | stack_v2_sparse_classes_36k_train_009739 | 1,567 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversalIterative",
"signature": "def inorderTraversalIterative(self, root)"
... | 2 | stack_v2_sparse_classes_30k_train_016545 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversalIterative(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversalIterative(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class S... | 4d7e675c795c841f99ca95b8b60c4995bcb632fb | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversalIterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
rslt = []
if not root:
return rslt
rslt.extend(self.inorderTraversal(root.left))
rslt.append(root.val)
rslt.extend(self.inorderTraversal(root.right))
ret... | the_stack_v2_python_sparse | inorderTraversal.py | stephenchenxj/myLeetCode | train | 0 | |
d5b9c59586e5a5032043e02d977a445046533c3d | [
"self.abort_incomplete_multipart_upload = abort_incomplete_multipart_upload\nself.expiration = expiration\nself.filter = filter\nself.id = id\nself.noncurrent_version_expiration = noncurrent_version_expiration\nself.prefix = prefix\nself.status = status",
"if dictionary is None:\n return None\nabort_incomplete... | <|body_start_0|>
self.abort_incomplete_multipart_upload = abort_incomplete_multipart_upload
self.expiration = expiration
self.filter = filter
self.id = id
self.noncurrent_version_expiration = noncurrent_version_expiration
self.prefix = prefix
self.status = status
... | Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before permanently removing all parts of the upload. expiration (ExpirationAction): Sp... | LifecycleRule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifecycleRule:
"""Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before permanently removing all parts of the ... | stack_v2_sparse_classes_36k_train_009740 | 4,612 | permissive | [
{
"docstring": "Constructor for the LifecycleRule class",
"name": "__init__",
"signature": "def __init__(self, abort_incomplete_multipart_upload=None, expiration=None, filter=None, id=None, noncurrent_version_expiration=None, prefix=None, status=None)"
},
{
"docstring": "Creates an instance of t... | 2 | null | Implement the Python class `LifecycleRule` described below.
Class description:
Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before... | Implement the Python class `LifecycleRule` described below.
Class description:
Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LifecycleRule:
"""Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before permanently removing all parts of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LifecycleRule:
"""Implementation of the 'LifecycleRule' model. TODO: type description here. Attributes: abort_incomplete_multipart_upload (AbortIncompleteMultipartUploadAction): Specifies the days since the initiation of an incomplete multipart upload before permanently removing all parts of the upload. expir... | the_stack_v2_python_sparse | cohesity_management_sdk/models/lifecycle_rule.py | cohesity/management-sdk-python | train | 24 |
55fd842a2d81e946e73428538f8ff2bfeb5b511b | [
"for output in self.outputs:\n if output.type in {'stdout', 'stderr'}:\n stream = getattr(self, output.type)\n if stream == path:\n return output.id\n elif output.type == 'File':\n glob = output.outputBinding.glob\n if glob.startswith('$(inputs.'):\n input_id ... | <|body_start_0|>
for output in self.outputs:
if output.type in {'stdout', 'stderr'}:
stream = getattr(self, output.type)
if stream == path:
return output.id
elif output.type == 'File':
glob = output.outputBinding.glob
... | Represent a command line tool. | CommandLineTool | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
<|body_0|>
def to_argv(self, job=None):
"""Generate arguments for system call."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_009741 | 15,381 | permissive | [
{
"docstring": "Return an id of the matching path from default values.",
"name": "get_output_id",
"signature": "def get_output_id(self, path)"
},
{
"docstring": "Generate arguments for system call.",
"name": "to_argv",
"signature": "def to_argv(self, job=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002356 | Implement the Python class `CommandLineTool` described below.
Class description:
Represent a command line tool.
Method signatures and docstrings:
- def get_output_id(self, path): Return an id of the matching path from default values.
- def to_argv(self, job=None): Generate arguments for system call. | Implement the Python class `CommandLineTool` described below.
Class description:
Represent a command line tool.
Method signatures and docstrings:
- def get_output_id(self, path): Return an id of the matching path from default values.
- def to_argv(self, job=None): Generate arguments for system call.
<|skeleton|>
cla... | 36ae4282f2da3eaf444674784b82a5d8a1e0e59c | <|skeleton|>
class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
<|body_0|>
def to_argv(self, job=None):
"""Generate arguments for system call."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandLineTool:
"""Represent a command line tool."""
def get_output_id(self, path):
"""Return an id of the matching path from default values."""
for output in self.outputs:
if output.type in {'stdout', 'stderr'}:
stream = getattr(self, output.type)
... | the_stack_v2_python_sparse | renku/models/cwl/command_line_tool.py | leafty/renku-python | train | 0 |
545d15c4ae69c6b5ce1bdec93aadf562840fdac5 | [
"if node_type == None:\n node_type = node_base\nif edge_type == None:\n edge_type = edge_base\nsuper().__init__()\nself.node_type = node_type\nself.edge_type = edge_type\nself.node_list = []\nself.edge_list = []\nself.mst = None",
"self.unionset = unionset(len(self.node_list), int)\nself.edge_list.sort()\ns... | <|body_start_0|>
if node_type == None:
node_type = node_base
if edge_type == None:
edge_type = edge_base
super().__init__()
self.node_type = node_type
self.edge_type = edge_type
self.node_list = []
self.edge_list = []
self.mst = Non... | mst_base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mst_base:
def __init__(self, node_type=None, edge_type=None):
"""vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix"""
<|body_0|>
def generate_mst(self):
"""The base function for ... | stack_v2_sparse_classes_36k_train_009742 | 1,213 | no_license | [
{
"docstring": "vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix",
"name": "__init__",
"signature": "def __init__(self, node_type=None, edge_type=None)"
},
{
"docstring": "The base function for mst Using Kr... | 2 | stack_v2_sparse_classes_30k_train_003389 | Implement the Python class `mst_base` described below.
Class description:
Implement the mst_base class.
Method signatures and docstrings:
- def __init__(self, node_type=None, edge_type=None): vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adj... | Implement the Python class `mst_base` described below.
Class description:
Implement the mst_base class.
Method signatures and docstrings:
- def __init__(self, node_type=None, edge_type=None): vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adj... | 2bd6aaadb8f6abcc13e9c468adff74c93b0ae6b2 | <|skeleton|>
class mst_base:
def __init__(self, node_type=None, edge_type=None):
"""vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix"""
<|body_0|>
def generate_mst(self):
"""The base function for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mst_base:
def __init__(self, node_type=None, edge_type=None):
"""vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix"""
if node_type == None:
node_type = node_base
if edge_type == None:
... | the_stack_v2_python_sparse | graph_utils/mstpy/mst_base.py | jrahim/graph_clean | train | 0 | |
92872a245f28e297972a39a98b9c5bbf02c48000 | [
"self.start = start\nself.home = home\nself.seed = seed",
"w = Walker(self.start, self.home)\nwhile not w.is_at_home():\n w.move()\nreturn w.get_steps()",
"r.seed(self.seed)\nmoves_count = [self.single_walk() for _ in range(num_walks)]\nreturn moves_count"
] | <|body_start_0|>
self.start = start
self.home = home
self.seed = seed
<|end_body_0|>
<|body_start_1|>
w = Walker(self.start, self.home)
while not w.is_at_home():
w.move()
return w.get_steps()
<|end_body_1|>
<|body_start_2|>
r.seed(self.seed)
... | Simulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
<|body_0|>
def single_walk(self):
... | stack_v2_sparse_classes_36k_train_009743 | 3,229 | no_license | [
{
"docstring": "Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator",
"name": "__init__",
"signature": "def __init__(self, start, home, seed)"
},
{
"docstring": "Simulate s... | 3 | stack_v2_sparse_classes_30k_train_006180 | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def __init__(self, start, home, seed): Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches... | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def __init__(self, start, home, seed): Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches... | 9bfa22c85866eeb019c2c24bc5bbfcd600fadcb5 | <|skeleton|>
class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
<|body_0|>
def single_walk(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
def __init__(self, start, home, seed):
"""Initialise the simulation Arguments -------- start : int The walker's initial position home : int The walk ends when the walker reaches home seed : int Random number generator"""
self.start = start
self.home = home
self.seed... | the_stack_v2_python_sparse | src/petter_hetland_ex/ex05/walker_sim.py | pkhetland/INF200-2019-Exercises | train | 1 | |
551906ef3d545c6fcac7fac953e3000e14bcd2c1 | [
"self.verify_workflow()\nmco_model = self.workflow.mco_model\nmco_communicator = self.create_mco_communicator()\nself._initialize_listeners()\ntry:\n mco_data_values = mco_communicator.receive_from_mco(mco_model)\n kpi_results = self.workflow.execute(mco_data_values)\n mco_communicator.send_to_mco(mco_mode... | <|body_start_0|>
self.verify_workflow()
mco_model = self.workflow.mco_model
mco_communicator = self.create_mco_communicator()
self._initialize_listeners()
try:
mco_data_values = mco_communicator.receive_from_mco(mco_model)
kpi_results = self.workflow.execu... | Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object. | EvaluateOperation | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateOperation:
"""Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object."""
def run(self):
"""Evaluate the workflow."""
<|body_0|>
def create_mco_communicator(self):
"""Create BaseMCOCommunicator instance as... | stack_v2_sparse_classes_36k_train_009744 | 2,000 | permissive | [
{
"docstring": "Evaluate the workflow.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Create BaseMCOCommunicator instance associated with the BaseMCOModel subclass in the Workflow",
"name": "create_mco_communicator",
"signature": "def create_mco_communicator(self)"
}
... | 2 | null | Implement the Python class `EvaluateOperation` described below.
Class description:
Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object.
Method signatures and docstrings:
- def run(self): Evaluate the workflow.
- def create_mco_communicator(self): Create BaseMCOCom... | Implement the Python class `EvaluateOperation` described below.
Class description:
Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object.
Method signatures and docstrings:
- def run(self): Evaluate the workflow.
- def create_mco_communicator(self): Create BaseMCOCom... | 6106bec35d6ad2383138a35205cea44fe529a229 | <|skeleton|>
class EvaluateOperation:
"""Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object."""
def run(self):
"""Evaluate the workflow."""
<|body_0|>
def create_mco_communicator(self):
"""Create BaseMCOCommunicator instance as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluateOperation:
"""Performs the evaluation of a single point in an MCO, based on the system described by a `Workflow` object."""
def run(self):
"""Evaluate the workflow."""
self.verify_workflow()
mco_model = self.workflow.mco_model
mco_communicator = self.create_mco_com... | the_stack_v2_python_sparse | force_bdss/app/evaluate_operation.py | force-h2020/force-bdss | train | 2 |
29273cb3d791805717a7734f398ad65cabb5f61a | [
"import numpy as np\nargs, n = (np.array(args), [])\nfor i in range(len(args)):\n n.append(len(args[i]) + i * 1j)\nn = np.sort(n).imag.astype(int)\nargs = args[n[::-1]]\nfor i in range(len(args)):\n instr = instr.split(args[i])\n for j in range(1, len(instr)):\n instr[0] += replace + instr[j]\n i... | <|body_start_0|>
import numpy as np
args, n = (np.array(args), [])
for i in range(len(args)):
n.append(len(args[i]) + i * 1j)
n = np.sort(n).imag.astype(int)
args = args[n[::-1]]
for i in range(len(args)):
instr = instr.split(args[i])
f... | Str | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Str:
def StrRemove(self, instr, replace='-', *args):
"""instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: replace these str with "replace" return: str Example: a = '$\\Delta a$, b,c d, $h$, e f,g' b = S... | stack_v2_sparse_classes_36k_train_009745 | 3,983 | no_license | [
{
"docstring": "instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: replace these str with \"replace\" return: str Example: a = '$\\\\Delta a$, b,c d, $h$, e f,g' b = StrRemove(a, '', '$', '\\\\') b = StrRemove(b, '-', ' ', ', '... | 4 | null | Implement the Python class `Str` described below.
Class description:
Implement the Str class.
Method signatures and docstrings:
- def StrRemove(self, instr, replace='-', *args): instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: repl... | Implement the Python class `Str` described below.
Class description:
Implement the Str class.
Method signatures and docstrings:
- def StrRemove(self, instr, replace='-', *args): instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: repl... | b49777105a76b5ae03555a9f93f116454c8245a9 | <|skeleton|>
class Str:
def StrRemove(self, instr, replace='-', *args):
"""instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: replace these str with "replace" return: str Example: a = '$\\Delta a$, b,c d, $h$, e f,g' b = S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Str:
def StrRemove(self, instr, replace='-', *args):
"""instr: input instr, must be one str, type(instr)==str replace: replace *args with this str For example, replace='' | replace='-' *args: replace these str with "replace" return: str Example: a = '$\\Delta a$, b,c d, $h$, e f,g' b = StrRemove(a, ''... | the_stack_v2_python_sparse | Basic/Str.py | jizhi/jizhipy | train | 1 | |
233e9be090ecf437b7f261297b80686029700f88 | [
"super().__init__(identifier, name, description)\nif part_of:\n self.part_of(part_of)",
"if self._main_characteristic is None:\n self._main_characteristic = main_characteristic\n main_characteristic.sub_characteristic(self)"
] | <|body_start_0|>
super().__init__(identifier, name, description)
if part_of:
self.part_of(part_of)
<|end_body_0|>
<|body_start_1|>
if self._main_characteristic is None:
self._main_characteristic = main_characteristic
main_characteristic.sub_characteristic(sel... | ISO 25010 software quality sub characteristic | Iso25010SubCharacteristic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Iso25010SubCharacteristic:
"""ISO 25010 software quality sub characteristic"""
def __init__(self, identifier, name, description, part_of=None):
""":param identifier: identifier for the characteristic :param name: name for the characteristic :param description: description for the cha... | stack_v2_sparse_classes_36k_train_009746 | 1,078 | permissive | [
{
"docstring": ":param identifier: identifier for the characteristic :param name: name for the characteristic :param description: description for the characteristic",
"name": "__init__",
"signature": "def __init__(self, identifier, name, description, part_of=None)"
},
{
"docstring": "make sub ch... | 2 | stack_v2_sparse_classes_30k_train_013780 | Implement the Python class `Iso25010SubCharacteristic` described below.
Class description:
ISO 25010 software quality sub characteristic
Method signatures and docstrings:
- def __init__(self, identifier, name, description, part_of=None): :param identifier: identifier for the characteristic :param name: name for the c... | Implement the Python class `Iso25010SubCharacteristic` described below.
Class description:
ISO 25010 software quality sub characteristic
Method signatures and docstrings:
- def __init__(self, identifier, name, description, part_of=None): :param identifier: identifier for the characteristic :param name: name for the c... | e65fddb94513e7c2f54f248b4ce69e9e10ce42f5 | <|skeleton|>
class Iso25010SubCharacteristic:
"""ISO 25010 software quality sub characteristic"""
def __init__(self, identifier, name, description, part_of=None):
""":param identifier: identifier for the characteristic :param name: name for the characteristic :param description: description for the cha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Iso25010SubCharacteristic:
"""ISO 25010 software quality sub characteristic"""
def __init__(self, identifier, name, description, part_of=None):
""":param identifier: identifier for the characteristic :param name: name for the characteristic :param description: description for the characteristic""... | the_stack_v2_python_sparse | python/domain/iso25010/model/sub_characteristic.py | jeroenpeeters/document-as-code | train | 0 |
a6a991b046491acaeb74f204e9a932fa65d2a541 | [
"i = bisect.bisect_left(arr, x) - 1\nret = []\nj = i + 1\nwhile len(ret) < k and i >= 0 and (j < len(arr)):\n a, b = (abs(arr[i] - x), abs(arr[j] - x))\n if a == b or a < b:\n ret.append(arr[i])\n i -= 1\n else:\n ret.append(arr[j])\n j += 1\nif len(ret) < k:\n while len(ret)... | <|body_start_0|>
i = bisect.bisect_left(arr, x) - 1
ret = []
j = i + 1
while len(ret) < k and i >= 0 and (j < len(arr)):
a, b = (abs(arr[i] - x), abs(arr[j] - x))
if a == b or a < b:
ret.append(arr[i])
i -= 1
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findClosestElements2(self, arr: List[int], k: int, x: int) -> List[int]:
"""Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <= arr.length <= 10^4 arr is sorted in ascending order. -10^4 <= arr[i], x <= 10^4"""
<|bod... | stack_v2_sparse_classes_36k_train_009747 | 2,525 | permissive | [
{
"docstring": "Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <= arr.length <= 10^4 arr is sorted in ascending order. -10^4 <= arr[i], x <= 10^4",
"name": "findClosestElements2",
"signature": "def findClosestElements2(self, arr: List[int], k: int, x: ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements2(self, arr: List[int], k: int, x: int) -> List[int]: Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <=... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements2(self, arr: List[int], k: int, x: int) -> List[int]: Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <=... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def findClosestElements2(self, arr: List[int], k: int, x: int) -> List[int]:
"""Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <= arr.length <= 10^4 arr is sorted in ascending order. -10^4 <= arr[i], x <= 10^4"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findClosestElements2(self, arr: List[int], k: int, x: int) -> List[int]:
"""Runtime: 847 ms, faster than 12.34% Memory Usage: 15.4 MB, less than 80.93% 1 <= k <= arr.length 1 <= arr.length <= 10^4 arr is sorted in ascending order. -10^4 <= arr[i], x <= 10^4"""
i = bisect.bisect_l... | the_stack_v2_python_sparse | src/658-FindKClosestElements.py | Jiezhi/myleetcode | train | 1 | |
73c0b537b4cea0625ec2f1e75b908c02115ec6e7 | [
"super().__init__()\nself.enc_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])\nself.pool = nn.MaxPool2d(2)",
"ftrs = []\nfor block in self.enc_blocks:\n x = block(x)\n ftrs.append(x)\n x = self.pool(x)\nreturn ftrs"
] | <|body_start_0|>
super().__init__()
self.enc_blocks = nn.ModuleList([Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])
self.pool = nn.MaxPool2d(2)
<|end_body_0|>
<|body_start_1|>
ftrs = []
for block in self.enc_blocks:
x = block(x)
ftrs.append(x)
... | U-net encoder half | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
<|body_0|>
def forward(self, x):
"""Forward of th... | stack_v2_sparse_classes_36k_train_009748 | 11,891 | no_license | [
{
"docstring": "Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)",
"name": "__init__",
"signature": "def __init__(self, chs=(6, 64, 128, 256, 512, 1024))"
},
{
"docstring": "Forward of the U-net encoder. Inputs: x - Input bat... | 2 | stack_v2_sparse_classes_30k_train_007022 | Implement the Python class `Encoder` described below.
Class description:
U-net encoder half
Method signatures and docstrings:
- def __init__(self, chs=(6, 64, 128, 256, 512, 1024)): Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)
- def forward(se... | Implement the Python class `Encoder` described below.
Class description:
U-net encoder half
Method signatures and docstrings:
- def __init__(self, chs=(6, 64, 128, 256, 512, 1024)): Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)
- def forward(se... | 0b65d43a9bb5e70d7e4e3fcd322b47b173e16fa6 | <|skeleton|>
class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
<|body_0|>
def forward(self, x):
"""Forward of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""U-net encoder half"""
def __init__(self, chs=(6, 64, 128, 256, 512, 1024)):
"""Class for U-net encoder half. Inputs: chs - The channels of the block of the encoder. Default = (6,64,128,256,512,1024)"""
super().__init__()
self.enc_blocks = nn.ModuleList([Block(chs[i], c... | the_stack_v2_python_sparse | models/attackers/inversion_attacker_2.py | RamonDijkstra/AI-FACT | train | 0 |
05972d13a01a975f94d66cb71288d4f13210f062 | [
"description = ' '.join(response.css('.vc_col-sm-6 .wpb_wrapper p *::text').extract())\nlocation = self.location\nif 'virtual' in description.lower():\n location = {'name': 'Virtual', 'address': ''}\nelif 'cancel' not in description.lower() and '301 East Cermak' not in description:\n raise ValueError('Meeting... | <|body_start_0|>
description = ' '.join(response.css('.vc_col-sm-6 .wpb_wrapper p *::text').extract())
location = self.location
if 'virtual' in description.lower():
location = {'name': 'Virtual', 'address': ''}
elif 'cancel' not in description.lower() and '301 East Cermak' no... | ChiMetroPierExpositionSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiMetroPierExpositionSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item):
"""Parse or generate meeting title.... | stack_v2_sparse_classes_36k_train_009749 | 3,441 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse or generate meeting title.",
"name": "_parse_title",
"signa... | 5 | stack_v2_sparse_classes_30k_train_006825 | Implement the Python class `ChiMetroPierExpositionSpider` described below.
Class description:
Implement the ChiMetroPierExpositionSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your... | Implement the Python class `ChiMetroPierExpositionSpider` described below.
Class description:
Implement the ChiMetroPierExpositionSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiMetroPierExpositionSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_title(self, item):
"""Parse or generate meeting title.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChiMetroPierExpositionSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
description = ' '.join(response.css('.vc_col-sm-6 .wpb_wrapper p *::text').extract())
location ... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_metro_pier_exposition.py | City-Bureau/city-scrapers | train | 308 | |
8ed6fa740e83038859ac249d49c091ddce351aa4 | [
"super(SentimentRNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)\nself.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=self.hidden_dim, num_layers=self.n_layers, dropo... | <|body_start_0|>
super(SentimentRNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
self.lstm = nn.LSTM(input_size=embedding_dim, hidde... | The RNN model that will be used to perform Sentiment analysis | SentimentRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentimentRNN:
"""The RNN model that will be used to perform Sentiment analysis"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the model by setting up the layers :param vocab_size: :param output_size: :param embedding_... | stack_v2_sparse_classes_36k_train_009750 | 16,391 | no_license | [
{
"docstring": "Initialize the model by setting up the layers :param vocab_size: :param output_size: :param embedding_dim: :param hidden_dim: :param n_layers: :param drop_prob:",
"name": "__init__",
"signature": "def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=... | 3 | stack_v2_sparse_classes_30k_train_007351 | Implement the Python class `SentimentRNN` described below.
Class description:
The RNN model that will be used to perform Sentiment analysis
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the model by setting up the layers... | Implement the Python class `SentimentRNN` described below.
Class description:
The RNN model that will be used to perform Sentiment analysis
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the model by setting up the layers... | 727cedd3e3aca715b9326f625548bedb5a0c1b9b | <|skeleton|>
class SentimentRNN:
"""The RNN model that will be used to perform Sentiment analysis"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the model by setting up the layers :param vocab_size: :param output_size: :param embedding_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentimentRNN:
"""The RNN model that will be used to perform Sentiment analysis"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the model by setting up the layers :param vocab_size: :param output_size: :param embedding_dim: :param h... | the_stack_v2_python_sparse | recurring_neural_network/sentiment_prediction_rnn/sentiment_rnn.py | sivaneshl/deep_learning_course | train | 0 |
d0cc8b9b807ad16ffff58f24cfc51758d98b67ba | [
"ctx.args = args_to_numpy(input_)\nctx.kwargs = kwargs_to_numpy(input_kwargs)\nctx.save_for_backward(*input_)\nres = qnode(*ctx.args, **ctx.kwargs)\nif not isinstance(res, np.ndarray):\n res = np.array(res)\nfor i in input_:\n if isinstance(i, torch.Tensor):\n if i.is_cuda:\n cuda_device = i... | <|body_start_0|>
ctx.args = args_to_numpy(input_)
ctx.kwargs = kwargs_to_numpy(input_kwargs)
ctx.save_for_backward(*input_)
res = qnode(*ctx.args, **ctx.kwargs)
if not isinstance(res, np.ndarray):
res = np.array(res)
for i in input_:
if isinstance(... | The TorchQNode | _TorchQNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TorchQNode:
"""The TorchQNode"""
def forward(ctx, input_kwargs, *input_):
"""Implements the forward pass QNode evaluation"""
<|body_0|>
def backward(ctx, grad_output):
"""Implements the backwards pass QNode vector-Jacobian product"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_009751 | 12,847 | permissive | [
{
"docstring": "Implements the forward pass QNode evaluation",
"name": "forward",
"signature": "def forward(ctx, input_kwargs, *input_)"
},
{
"docstring": "Implements the backwards pass QNode vector-Jacobian product",
"name": "backward",
"signature": "def backward(ctx, grad_output)"
}
... | 2 | stack_v2_sparse_classes_30k_train_012722 | Implement the Python class `_TorchQNode` described below.
Class description:
The TorchQNode
Method signatures and docstrings:
- def forward(ctx, input_kwargs, *input_): Implements the forward pass QNode evaluation
- def backward(ctx, grad_output): Implements the backwards pass QNode vector-Jacobian product | Implement the Python class `_TorchQNode` described below.
Class description:
The TorchQNode
Method signatures and docstrings:
- def forward(ctx, input_kwargs, *input_): Implements the forward pass QNode evaluation
- def backward(ctx, grad_output): Implements the backwards pass QNode vector-Jacobian product
<|skeleto... | 40f2219b5e048d4bd93df815811ca5ed3f5327fa | <|skeleton|>
class _TorchQNode:
"""The TorchQNode"""
def forward(ctx, input_kwargs, *input_):
"""Implements the forward pass QNode evaluation"""
<|body_0|>
def backward(ctx, grad_output):
"""Implements the backwards pass QNode vector-Jacobian product"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TorchQNode:
"""The TorchQNode"""
def forward(ctx, input_kwargs, *input_):
"""Implements the forward pass QNode evaluation"""
ctx.args = args_to_numpy(input_)
ctx.kwargs = kwargs_to_numpy(input_kwargs)
ctx.save_for_backward(*input_)
res = qnode(*ctx.args, **ctx.kwa... | the_stack_v2_python_sparse | pennylane/interfaces/torch.py | AroosaIjaz/Mypennylane | train | 2 |
3e3b80ddc6f8fd373d322af1dd3d14efc7037c3d | [
"if not pod_spec:\n raise _user_exceptions.FlyteValidationException('A pod spec cannot be undefined')\nif not primary_container_name:\n raise _user_exceptions.FlyteValidationException('A primary container name cannot be undefined')\nsuper(SdkSidecarTask, self).__init__(task_function, task_type, discovery_vers... | <|body_start_0|>
if not pod_spec:
raise _user_exceptions.FlyteValidationException('A pod spec cannot be undefined')
if not primary_container_name:
raise _user_exceptions.FlyteValidationException('A primary container name cannot be undefined')
super(SdkSidecarTask, self)._... | This class includes the additional logic for building a task that executes as a Sidecar Job. | SdkSidecarTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SdkSidecarTask:
"""This class includes the additional logic for building a task that executes as a Sidecar Job."""
def __init__(self, task_function, task_type, discovery_version, retries, interruptible, deprecated, storage_request, cpu_request, gpu_request, memory_request, storage_limit, cpu... | stack_v2_sparse_classes_36k_train_009752 | 5,590 | permissive | [
{
"docstring": ":param _sdk_runnable.SdkRunnableTask sdk_runnable_task: :param generated_pb2.PodSpec pod_spec: :param Text primary_container_name: :raises: flytekit.common.exceptions.user.FlyteValidationException",
"name": "__init__",
"signature": "def __init__(self, task_function, task_type, discovery_... | 2 | stack_v2_sparse_classes_30k_train_015123 | Implement the Python class `SdkSidecarTask` described below.
Class description:
This class includes the additional logic for building a task that executes as a Sidecar Job.
Method signatures and docstrings:
- def __init__(self, task_function, task_type, discovery_version, retries, interruptible, deprecated, storage_r... | Implement the Python class `SdkSidecarTask` described below.
Class description:
This class includes the additional logic for building a task that executes as a Sidecar Job.
Method signatures and docstrings:
- def __init__(self, task_function, task_type, discovery_version, retries, interruptible, deprecated, storage_r... | 2eb9ce7aacaab6e49c1fc901c14c7b0d6b479523 | <|skeleton|>
class SdkSidecarTask:
"""This class includes the additional logic for building a task that executes as a Sidecar Job."""
def __init__(self, task_function, task_type, discovery_version, retries, interruptible, deprecated, storage_request, cpu_request, gpu_request, memory_request, storage_limit, cpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SdkSidecarTask:
"""This class includes the additional logic for building a task that executes as a Sidecar Job."""
def __init__(self, task_function, task_type, discovery_version, retries, interruptible, deprecated, storage_request, cpu_request, gpu_request, memory_request, storage_limit, cpu_limit, gpu_l... | the_stack_v2_python_sparse | flytekit/common/tasks/sidecar_task.py | jbrambleDC/flytekit | train | 1 |
2b022e9fa78a09ed512d34e2c746da312f8ada57 | [
"args = self._build_potential_args({'room_id': room_id, 'topic': topic, 'format': 'json'})\nurl = self._generate_escaped_url(API_TOPIC_PATH, args)\nres = (yield self._fetch_wrapper(url, post=''))\nraise gen.Return(res)",
"self.log.info('Setting room \"%s\" topic to: %s' % (self.option('room'), self.option('topic'... | <|body_start_0|>
args = self._build_potential_args({'room_id': room_id, 'topic': topic, 'format': 'json'})
url = self._generate_escaped_url(API_TOPIC_PATH, args)
res = (yield self._fetch_wrapper(url, post=''))
raise gen.Return(res)
<|end_body_0|>
<|body_start_1|>
self.log.info('... | Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "options": { "room": "Operations", "topic": "Latest Deployment: v1.2" } } **Dr... | Topic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Topic:
"""Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "options": { "room": "Operations", "topic": "... | stack_v2_sparse_classes_36k_train_009753 | 10,230 | permissive | [
{
"docstring": "Posts a message to Hipchat. https://www.hipchat.com/docs/api/method/rooms/topic Args: room_id: (Str/Int) Name or ID of the room to post to. topic: (Str) Required. The topic string, 250 char max Raises: gen.Return(<Dictionary of the response from Hipchat>)",
"name": "_set_topic",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_008457 | Implement the Python class `Topic` described below.
Class description:
Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "optio... | Implement the Python class `Topic` described below.
Class description:
Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "optio... | d0abaf93ff321f12c0504c99eacb89f9288e892b | <|skeleton|>
class Topic:
"""Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "options": { "room": "Operations", "topic": "... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Topic:
"""Sets a HipChat room topic. **Options** - ``room`` - The string-name (or ID) of the room to set the topic of - ``topic`` - String of the topic to send **Examples** .. code-block:: json { "actor": "hipchat.Topic", "desc": "set the room topic", "options": { "room": "Operations", "topic": "Latest Deploy... | the_stack_v2_python_sparse | kingpin/actors/hipchat.py | Nextdoor/kingpin | train | 29 |
58465a548e649d80ee4705d1bbbd92043a7fc0f0 | [
"super(AppPixivAPI, self).__init__(**requests_kwargs)\nsession = requests.Session()\nsession.mount('https://', host_header_ssl.HostHeaderSSLAdapter())\nself.requests = session",
"url = 'https://1.0.0.1/dns-query?ct=application/dns-json&name=%s&type=A&do=false&cd=false' % hostname\nresponse = requests.get(url)\nse... | <|body_start_0|>
super(AppPixivAPI, self).__init__(**requests_kwargs)
session = requests.Session()
session.mount('https://', host_header_ssl.HostHeaderSSLAdapter())
self.requests = session
<|end_body_0|>
<|body_start_1|>
url = 'https://1.0.0.1/dns-query?ct=application/dns-json&n... | ByPassSniApi | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ByPassSniApi:
def __init__(self, **requests_kwargs):
"""initialize requests kwargs if need be"""
<|body_0|>
def require_appapi_hosts(self, hostname='app-api.pixiv.net'):
"""通过1.0.0.1请求真实的ip地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(App... | stack_v2_sparse_classes_36k_train_009754 | 814 | permissive | [
{
"docstring": "initialize requests kwargs if need be",
"name": "__init__",
"signature": "def __init__(self, **requests_kwargs)"
},
{
"docstring": "通过1.0.0.1请求真实的ip地址",
"name": "require_appapi_hosts",
"signature": "def require_appapi_hosts(self, hostname='app-api.pixiv.net')"
}
] | 2 | stack_v2_sparse_classes_30k_train_009093 | Implement the Python class `ByPassSniApi` described below.
Class description:
Implement the ByPassSniApi class.
Method signatures and docstrings:
- def __init__(self, **requests_kwargs): initialize requests kwargs if need be
- def require_appapi_hosts(self, hostname='app-api.pixiv.net'): 通过1.0.0.1请求真实的ip地址 | Implement the Python class `ByPassSniApi` described below.
Class description:
Implement the ByPassSniApi class.
Method signatures and docstrings:
- def __init__(self, **requests_kwargs): initialize requests kwargs if need be
- def require_appapi_hosts(self, hostname='app-api.pixiv.net'): 通过1.0.0.1请求真实的ip地址
<|skeleto... | 5afc5aeed465223f3ab3c4607048937c24f07e99 | <|skeleton|>
class ByPassSniApi:
def __init__(self, **requests_kwargs):
"""initialize requests kwargs if need be"""
<|body_0|>
def require_appapi_hosts(self, hostname='app-api.pixiv.net'):
"""通过1.0.0.1请求真实的ip地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ByPassSniApi:
def __init__(self, **requests_kwargs):
"""initialize requests kwargs if need be"""
super(AppPixivAPI, self).__init__(**requests_kwargs)
session = requests.Session()
session.mount('https://', host_header_ssl.HostHeaderSSLAdapter())
self.requests = session
... | the_stack_v2_python_sparse | pixivpy3/bapi.py | Notsfsssf/pixivpy | train | 5 | |
36e0ac6a1cb1668f19cf3605c7abd74562ab1cbb | [
"if self.exportPng.get() == 1:\n self.exportPngCommand()\nif self.exportRecolored.get() == 1:\n self.exportRecoloredCommand()\nif self.exportSeparate.get() == 1:\n self.exportSeparateCommand()\nself.frame.destroy()",
"self.root = root\nself.app = app\nself.exportPngCommand = exportPng\nself.exportSeparat... | <|body_start_0|>
if self.exportPng.get() == 1:
self.exportPngCommand()
if self.exportRecolored.get() == 1:
self.exportRecoloredCommand()
if self.exportSeparate.get() == 1:
self.exportSeparateCommand()
self.frame.destroy()
<|end_body_0|>
<|body_start_1... | :Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer | ExportMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportMenu:
""":Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer"""
def doneCommand(self):
""":description: Checks which boxes have been checked, and runs the appropriate export command for each."""
<|body_... | stack_v2_sparse_classes_36k_train_009755 | 3,045 | no_license | [
{
"docstring": ":description: Checks which boxes have been checked, and runs the appropriate export command for each.",
"name": "doneCommand",
"signature": "def doneCommand(self)"
},
{
"docstring": ":Description: Create the menu object that shows export options :param root: (tkinter.Tk) the root... | 2 | stack_v2_sparse_classes_30k_train_010971 | Implement the Python class `ExportMenu` described below.
Class description:
:Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer
Method signatures and docstrings:
- def doneCommand(self): :description: Checks which boxes have been checked, and runs th... | Implement the Python class `ExportMenu` described below.
Class description:
:Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer
Method signatures and docstrings:
- def doneCommand(self): :description: Checks which boxes have been checked, and runs th... | 8dda8fc474f3af1fe7ed611c801a541b1723b985 | <|skeleton|>
class ExportMenu:
""":Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer"""
def doneCommand(self):
""":description: Checks which boxes have been checked, and runs the appropriate export command for each."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExportMenu:
""":Description: Menu that contains the functionality for exporting different types of files. :interracts with: Visualizer"""
def doneCommand(self):
""":description: Checks which boxes have been checked, and runs the appropriate export command for each."""
if self.exportPng.ge... | the_stack_v2_python_sparse | src/GUI/export_menu.py | nchaconbgeo/pointcloudpackage | train | 1 |
f17e067131dd4d3dff4b74d43e66543188264620 | [
"try:\n self._enabled = colored == COLOR_ALWAYS or (colored == COLOR_IF_TERMINAL and os.isatty(sys.stdout.fileno()))\nexcept:\n self._enabled = False",
"if self._enabled:\n base = self.BRIGHT_START if bright else self.NORMAL_START\n return base % (color + 30)\nreturn ''",
"if self._enabled:\n ret... | <|body_start_0|>
try:
self._enabled = colored == COLOR_ALWAYS or (colored == COLOR_IF_TERMINAL and os.isatty(sys.stdout.fileno()))
except:
self._enabled = False
<|end_body_0|>
<|body_start_1|>
if self._enabled:
base = self.BRIGHT_START if bright else self.NOR... | Conditionally wraps text in ANSI color escape sequences. | Color | [
"Apache-2.0",
"GPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Color:
"""Conditionally wraps text in ANSI color escape sequences."""
def __init__(self, colored=COLOR_IF_TERMINAL):
"""Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be enabled. If False then this class will not add color cod... | stack_v2_sparse_classes_36k_train_009756 | 4,528 | permissive | [
{
"docstring": "Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be enabled. If False then this class will not add color codes at all.",
"name": "__init__",
"signature": "def __init__(self, colored=COLOR_IF_TERMINAL)"
},
{
"docstring": "Ret... | 4 | null | Implement the Python class `Color` described below.
Class description:
Conditionally wraps text in ANSI color escape sequences.
Method signatures and docstrings:
- def __init__(self, colored=COLOR_IF_TERMINAL): Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be... | Implement the Python class `Color` described below.
Class description:
Conditionally wraps text in ANSI color escape sequences.
Method signatures and docstrings:
- def __init__(self, colored=COLOR_IF_TERMINAL): Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be... | 776196306198f14ec6f10c316950a81b7e417886 | <|skeleton|>
class Color:
"""Conditionally wraps text in ANSI color escape sequences."""
def __init__(self, colored=COLOR_IF_TERMINAL):
"""Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be enabled. If False then this class will not add color cod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Color:
"""Conditionally wraps text in ANSI color escape sequences."""
def __init__(self, colored=COLOR_IF_TERMINAL):
"""Create a new Color object, optionally disabling color output. Args: enabled: True if color output should be enabled. If False then this class will not add color codes at all."""... | the_stack_v2_python_sparse | u-boot/tools/patman/terminal.py | okshall/v3s-linux-sdk | train | 1 |
324a06b3d2277fafc62135f51a8ed116e59a2e3e | [
"super(CronStyleSchedulerTests, self).setUp()\nresponse = self.autoscale_behaviors.create_scaling_group_given(lc_name='cron_style_scheduled', gc_cooldown=0)\nself.group = response.entity\nself.resources.add(self.group, self.empty_scaling_group)",
"self.autoscale_behaviors.create_schedule_policy_given(group_id=sel... | <|body_start_0|>
super(CronStyleSchedulerTests, self).setUp()
response = self.autoscale_behaviors.create_scaling_group_given(lc_name='cron_style_scheduled', gc_cooldown=0)
self.group = response.entity
self.resources.add(self.group, self.empty_scaling_group)
<|end_body_0|>
<|body_start_1... | Verify cron style scheduler policy executes for all policy change types | CronStyleSchedulerTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CronStyleSchedulerTests:
"""Verify cron style scheduler policy executes for all policy change types"""
def setUp(self):
"""Create a scaling group with minentities=0 and cooldown=0"""
<|body_0|>
def test_system_cron_style_change_policy_up_down(self):
"""Create a c... | stack_v2_sparse_classes_36k_train_009757 | 4,892 | permissive | [
{
"docstring": "Create a scaling group with minentities=0 and cooldown=0",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Create a cron style schedule policy via change to scale up by 2, followed by a cron style schedule policy to scale down by -2, each policy with 0 cooldown... | 5 | null | Implement the Python class `CronStyleSchedulerTests` described below.
Class description:
Verify cron style scheduler policy executes for all policy change types
Method signatures and docstrings:
- def setUp(self): Create a scaling group with minentities=0 and cooldown=0
- def test_system_cron_style_change_policy_up_d... | Implement the Python class `CronStyleSchedulerTests` described below.
Class description:
Verify cron style scheduler policy executes for all policy change types
Method signatures and docstrings:
- def setUp(self): Create a scaling group with minentities=0 and cooldown=0
- def test_system_cron_style_change_policy_up_d... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class CronStyleSchedulerTests:
"""Verify cron style scheduler policy executes for all policy change types"""
def setUp(self):
"""Create a scaling group with minentities=0 and cooldown=0"""
<|body_0|>
def test_system_cron_style_change_policy_up_down(self):
"""Create a c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CronStyleSchedulerTests:
"""Verify cron style scheduler policy executes for all policy change types"""
def setUp(self):
"""Create a scaling group with minentities=0 and cooldown=0"""
super(CronStyleSchedulerTests, self).setUp()
response = self.autoscale_behaviors.create_scaling_gr... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/system/schedule_policies/test_system_cron_style_scheduler.py | rackerlabs/otter | train | 20 |
9202dd169ff81ccdaf8155abdac6880fbee61188 | [
"wc.OpenClipboard()\nvalue = wc.GetClipboardData(win32con.CF_TEXT)\nwc.CloseClipboard()\nreturn value",
"wc.OpenClipboard()\nwc.EmptyClipboard()\nwc.SetClipboardData(win32con.CF_UNICODETEXT, value)\nwc.CloseClipboard()"
] | <|body_start_0|>
wc.OpenClipboard()
value = wc.GetClipboardData(win32con.CF_TEXT)
wc.CloseClipboard()
return value
<|end_body_0|>
<|body_start_1|>
wc.OpenClipboard()
wc.EmptyClipboard()
wc.SetClipboardData(win32con.CF_UNICODETEXT, value)
wc.CloseClipboard... | 设置剪切板内容和获取剪切板内容 | ClipBoard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClipBoard:
"""设置剪切板内容和获取剪切板内容"""
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_text(value):
"""设置剪切板的内容"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wc.OpenClipboard()
value = wc.GetClipboardData(win32con.CF_TEXT)
wc.Close... | stack_v2_sparse_classes_36k_train_009758 | 964 | no_license | [
{
"docstring": "获取剪切板的内容",
"name": "get_text",
"signature": "def get_text()"
},
{
"docstring": "设置剪切板的内容",
"name": "set_text",
"signature": "def set_text(value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016356 | Implement the Python class `ClipBoard` described below.
Class description:
设置剪切板内容和获取剪切板内容
Method signatures and docstrings:
- def get_text(): 获取剪切板的内容
- def set_text(value): 设置剪切板的内容 | Implement the Python class `ClipBoard` described below.
Class description:
设置剪切板内容和获取剪切板内容
Method signatures and docstrings:
- def get_text(): 获取剪切板的内容
- def set_text(value): 设置剪切板的内容
<|skeleton|>
class ClipBoard:
"""设置剪切板内容和获取剪切板内容"""
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_t... | 3dd5d0aefb579569f80eee0f52eecbd0eea6b39e | <|skeleton|>
class ClipBoard:
"""设置剪切板内容和获取剪切板内容"""
def get_text():
"""获取剪切板的内容"""
<|body_0|>
def set_text(value):
"""设置剪切板的内容"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClipBoard:
"""设置剪切板内容和获取剪切板内容"""
def get_text():
"""获取剪切板的内容"""
wc.OpenClipboard()
value = wc.GetClipboardData(win32con.CF_TEXT)
wc.CloseClipboard()
return value
def set_text(value):
"""设置剪切板的内容"""
wc.OpenClipboard()
wc.EmptyClipboard()... | the_stack_v2_python_sparse | util/clipboard.py | chaixin2018/pytest-demo | train | 0 |
9b6669348c7f9843d70cc19274bda6349adfcbdc | [
"if isinstance(key, int):\n return UpdateNotificationReason(key)\nif key not in UpdateNotificationReason._member_map_:\n return extend_enum(UpdateNotificationReason, key, default)\nreturn UpdateNotificationReason[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not... | <|body_start_0|>
if isinstance(key, int):
return UpdateNotificationReason(key)
if key not in UpdateNotificationReason._member_map_:
return extend_enum(UpdateNotificationReason, key, default)
return UpdateNotificationReason[key]
<|end_body_0|>
<|body_start_1|>
if ... | [UpdateNotificationReason] Update Notification Reasons Registry | UpdateNotificationReason | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNotificationReason:
"""[UpdateNotificationReason] Update Notification Reasons Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :m... | stack_v2_sparse_classes_36k_train_009759 | 2,499 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason'"
},
{
"docstring": "Lookup function used when value ... | 2 | null | Implement the Python class `UpdateNotificationReason` described below.
Class description:
[UpdateNotificationReason] Update Notification Reasons Registry
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason': Backport support for original codes. Args: key: Key ... | Implement the Python class `UpdateNotificationReason` described below.
Class description:
[UpdateNotificationReason] Update Notification Reasons Registry
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason': Backport support for original codes. Args: key: Key ... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class UpdateNotificationReason:
"""[UpdateNotificationReason] Update Notification Reasons Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNotificationReason:
"""[UpdateNotificationReason] Update Notification Reasons Registry"""
def get(key: 'int | str', default: 'int'=-1) -> 'UpdateNotificationReason':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"... | the_stack_v2_python_sparse | pcapkit/const/mh/upn_reason.py | JarryShaw/PyPCAPKit | train | 204 |
ad02cdc019016d48d77336ada50b490c2d6bbb87 | [
"super().__init__(**kwargs)\nself.create_model(**kwargs)\nself.initialize_tensorkeys_for_functions()",
"config = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.intra_op_parallelism_threads = 112\nconfig.inter_op_parallelism_threads = 1\nself.sess = tf.Session(config=config)\nself.X = tf.placehol... | <|body_start_0|>
super().__init__(**kwargs)
self.create_model(**kwargs)
self.initialize_tensorkeys_for_functions()
<|end_body_0|>
<|body_start_1|>
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.intra_op_parallelism_threads = 112
config.in... | Initialize. Args: **kwargs: Additional parameters to pass to the function | TensorFlow2DUNet | [
"LicenseRef-scancode-protobuf",
"MPL-2.0",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def create_model(self, training_smoothing=32.0, vali... | stack_v2_sparse_classes_36k_train_009760 | 8,194 | permissive | [
{
"docstring": "Initialize. Args: **kwargs: Additional parameters to pass to the function",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Create the TensorFlow 2D U-Net model. Args: training_smoothing (float): (Default=32.0) validation_smoothing (float): (Def... | 2 | null | Implement the Python class `TensorFlow2DUNet` described below.
Class description:
Initialize. Args: **kwargs: Additional parameters to pass to the function
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize. Args: **kwargs: Additional parameters to pass to the function
- def create_model(sel... | Implement the Python class `TensorFlow2DUNet` described below.
Class description:
Initialize. Args: **kwargs: Additional parameters to pass to the function
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize. Args: **kwargs: Additional parameters to pass to the function
- def create_model(sel... | bd73b749a9ea1b92dbcdd07e639752101d769fc0 | <|skeleton|>
class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def create_model(self, training_smoothing=32.0, vali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
super().__init__(**kwargs)
self.create_model(**kwargs)
self.initi... | the_stack_v2_python_sparse | openfl-workspace/tf_2dunet/src/tf_2dunet.py | PDuckworth/openfl | train | 0 |
10042a84a6380ee5227649cf9603f90105972e8f | [
"candidate = cnt = 0\nfor num in nums:\n if candidate == num:\n cnt += 1\n elif cnt:\n cnt -= 1\n if cnt == 0:\n candidate, cnt = (num, 1)\nreturn candidate",
"if len(nums) == 1:\n return nums[0]\nif not nums:\n return None\na = self.majorityElement1(nums[:len(nums) // 2])\nb =... | <|body_start_0|>
candidate = cnt = 0
for num in nums:
if candidate == num:
cnt += 1
elif cnt:
cnt -= 1
if cnt == 0:
candidate, cnt = (num, 1)
return candidate
<|end_body_0|>
<|body_start_1|>
if len(nums)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
candidate = cnt = 0
for num... | stack_v2_sparse_classes_36k_train_009761 | 2,464 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement1",
"signature": "def majorityElement1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement1",
"signature": "def majorityElement1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009855 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement1(self, nums): :type nums: List[int] :rtype: int
- def majorityElement1(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 majorityElement1(self, nums): :type nums: List[int] :rtype: int
- def majorityElement1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def m... | 5e4dd3a845dfd161f4aff59093bff1706082ff45 | <|skeleton|>
class Solution:
def majorityElement1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement1(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 majorityElement1(self, nums):
""":type nums: List[int] :rtype: int"""
candidate = cnt = 0
for num in nums:
if candidate == num:
cnt += 1
elif cnt:
cnt -= 1
if cnt == 0:
candidate, cnt = (n... | the_stack_v2_python_sparse | leetcode/algrithm/169. Majority Element.py | lmycd/leetcode | train | 0 | |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(Conv2dSubsampling, self).__init__()\nself.conv = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=odim, kernel_size=3, stride=2), nn.ReLU(), nn.Conv2d(in_channels=odim, out_channels=odim, kernel_size=3, stride=2), nn.ReLU())\nself.out = nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim)",
"x = x.unsqu... | <|body_start_0|>
super(Conv2dSubsampling, self).__init__()
self.conv = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=odim, kernel_size=3, stride=2), nn.ReLU(), nn.Conv2d(in_channels=odim, out_channels=odim, kernel_size=3, stride=2), nn.ReLU())
self.out = nn.Linear(odim * (((idim - 1) // 2 ... | Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension. | Conv2dSubsampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, idim: int, odim: int) -> None:
... | stack_v2_sparse_classes_36k_train_009762 | 33,189 | permissive | [
{
"docstring": "Construct a Conv2dSubsampling object.",
"name": "__init__",
"signature": "def __init__(self, idim: int, odim: int) -> None"
},
{
"docstring": "Subsample x. Args: x: Input tensor of dimension (batch_size, input_length, num_features). (#batch, time, idim). Returns: torch.Tensor: Su... | 2 | stack_v2_sparse_classes_30k_train_021093 | Implement the Python class `Conv2dSubsampling` described below.
Class description:
Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension.
Method signatures and ... | Implement the Python class `Conv2dSubsampling` described below.
Class description:
Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension.
Method signatures and ... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, idim: int, odim: int) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2dSubsampling:
"""Convolutional 2D subsampling (to 1/4 length). Modified from https://github.com/espnet/espnet/blob/master/espnet/nets/pytorch_backend/transformer/subsampling.py Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, idim: int, odim: int) -> None:
"""Constr... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
71a72a789de5512dded3a006aa6158d210a103f4 | [
"specs = super().getInputSpecification()\nspecs.name = 'gaussianize'\nspecs.description = 'transforms the data into a normal distribution using quantile mapping.'\nspecs.addParam('nQuantiles', param_type=InputTypes.IntegerType, descr='number of quantiles to use in the transformation. If \\\\xmlAttr{nQuantiles}\\n ... | <|body_start_0|>
specs = super().getInputSpecification()
specs.name = 'gaussianize'
specs.description = 'transforms the data into a normal distribution using quantile mapping.'
specs.addParam('nQuantiles', param_type=InputTypes.IntegerType, descr='number of quantiles to use in the transf... | Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution | Gaussianize | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gaussianize:
"""Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, ... | stack_v2_sparse_classes_36k_train_009763 | 8,927 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Reads... | 3 | null | Implement the Python class `Gaussianize` described below.
Class description:
Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class... | Implement the Python class `Gaussianize` described below.
Class description:
Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class Gaussianize:
"""Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gaussianize:
"""Uses scikit-learn's preprocessing.QuantileTransformer to transform data to a normal distribution"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use ... | the_stack_v2_python_sparse | ravenframework/TSA/Transformers/Distributions.py | idaholab/raven | train | 201 |
663326abd6b5ee22266712a5e1f6b306c981bf23 | [
"self.policy = policy\nself.mtype = mtype\nself.value = value",
"if dictionary is None:\n return None\npolicy = dictionary.get('policy')\nmtype = dictionary.get('type')\nvalue = dictionary.get('value')\nreturn cls(policy, mtype, value)"
] | <|body_start_0|>
self.policy = policy
self.mtype = mtype
self.value = value
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
policy = dictionary.get('policy')
mtype = dictionary.get('type')
value = dictionary.get('value')
ret... | Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port', 'ipRange' value (string): The 'value' of what you want to block. Format of... | Rule6Model | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule6Model:
"""Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port', 'ipRange' value (string): The 'value... | stack_v2_sparse_classes_36k_train_009764 | 2,207 | permissive | [
{
"docstring": "Constructor for the Rule6Model class",
"name": "__init__",
"signature": "def __init__(self, policy=None, mtype=None, value=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obt... | 2 | null | Implement the Python class `Rule6Model` described below.
Class description:
Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port... | Implement the Python class `Rule6Model` described below.
Class description:
Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class Rule6Model:
"""Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port', 'ipRange' value (string): The 'value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule6Model:
"""Implementation of the 'Rule6' model. TODO: type model description here. Attributes: policy (Policy5Enum): 'Deny' traffic specified by this rule mtype (Type4Enum): Type of the L7 rule. One of: 'application', 'applicationCategory', 'host', 'port', 'ipRange' value (string): The 'value' of what you... | the_stack_v2_python_sparse | meraki_sdk/models/rule_6_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
8bacbd7cd4a91835eb711df14c4471f9cedbde07 | [
"l = len(s)\ndp = [[False for j in range(l)] for i in range(l)]\nfor i in range(l):\n for j in range(i, l):\n dp[i][i] = True\n if j == i + 1:\n dp[i][j] = s[i] == s[j]\nfor j in range(2, l):\n for i in range(0, j - 1):\n dp[i][j] = dp[i + 1][j - 1] and s[i] == s[j]\nleft = 0\n... | <|body_start_0|>
l = len(s)
dp = [[False for j in range(l)] for i in range(l)]
for i in range(l):
for j in range(i, l):
dp[i][i] = True
if j == i + 1:
dp[i][j] = s[i] == s[j]
for j in range(2, l):
for i in range(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
"""定义 dp[i][j] 表示区间 [... | stack_v2_sparse_classes_36k_train_009765 | 5,539 | no_license | [
{
"docstring": "定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": "定义 dp[i][j] 表示区间 [i,j] 是否为回文串... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): 定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rt... | 860590239da0618c52967a55eda8d6bbe00bfa96 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
"""定义 dp[i][j] 表示区间 [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
"""定义 dp[i][j] 表示区间 [i,j] 是否为回文串 状态转移方程为: dp[i][j] = 1 if i == j = s[i] == s[j] if j = i+1 = s[i] == s[j] && dp[i+1][j-1] if j > i+1 :type s: str :rtype: str"""
l = len(s)
dp = [[False for j in range(l)] for i in range(l)]
for i in rang... | the_stack_v2_python_sparse | LeetCode/p0005/IIII/longest-palindromic-substring.py | Ynjxsjmh/PracticeMakesPerfect | train | 0 | |
a70f6ff75b028687c49e1c35242b06ead51d780b | [
"data = parse(filename)\nif len(data) < 20:\n print(data)\nreturn None",
"data = parse(filename)\nif len(data) < 20:\n print(data)\nreturn None"
] | <|body_start_0|>
data = parse(filename)
if len(data) < 20:
print(data)
return None
<|end_body_0|>
<|body_start_1|>
data = parse(filename)
if len(data) < 20:
print(data)
return None
<|end_body_1|>
| AoC 2021 Day 05 | Day05 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day05:
"""AoC 2021 Day 05"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 05 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 05 part 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_009766 | 1,230 | no_license | [
{
"docstring": "Given a filename, solve 2021 day 05 part 1",
"name": "part1",
"signature": "def part1(filename: str) -> int"
},
{
"docstring": "Given a filename, solve 2021 day 05 part 2",
"name": "part2",
"signature": "def part2(filename: str) -> int"
}
] | 2 | null | Implement the Python class `Day05` described below.
Class description:
AoC 2021 Day 05
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 05 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 05 part 2 | Implement the Python class `Day05` described below.
Class description:
AoC 2021 Day 05
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 05 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 05 part 2
<|skeleton|>
class Day05:
"""AoC 202... | e89db235837d2d05848210a18c9c2a4456085570 | <|skeleton|>
class Day05:
"""AoC 2021 Day 05"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 05 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 05 part 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Day05:
"""AoC 2021 Day 05"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 05 part 1"""
data = parse(filename)
if len(data) < 20:
print(data)
return None
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 05... | the_stack_v2_python_sparse | 2021/python2021/aoc/template2.py | mreishus/aoc | train | 16 |
4aebfc1a554229de866032799e8c66c1fba916dd | [
"self.config_file = config_file\nself.config = self.load_semantic_kitti_config(config_file)\nlabels2id, id2label = self._remap_classes()\nself.labels2id = labels2id\nself.id2label = id2label\nself.label2color = self._color_map()\nself.labels2ground = self._label_to_ground_remap()",
"if len(filename) == 0:\n lo... | <|body_start_0|>
self.config_file = config_file
self.config = self.load_semantic_kitti_config(config_file)
labels2id, id2label = self._remap_classes()
self.labels2id = labels2id
self.id2label = id2label
self.label2color = self._color_map()
self.labels2ground = sel... | Class that load the semantic kitti config file and helps to handle class ids | SemanticKittiConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemanticKittiConfig:
"""Class that load the semantic kitti config file and helps to handle class ids"""
def __init__(self, config_file):
"""Parameters ---------- config_file: str to config file"""
<|body_0|>
def load_semantic_kitti_config(filename=''):
"""Functio... | stack_v2_sparse_classes_36k_train_009767 | 9,534 | no_license | [
{
"docstring": "Parameters ---------- config_file: str to config file",
"name": "__init__",
"signature": "def __init__(self, config_file)"
},
{
"docstring": "Function that load configuration file of semantic kitti dataset Parameters ---------- filename: str file to load Returns ------- config: d... | 5 | stack_v2_sparse_classes_30k_train_009816 | Implement the Python class `SemanticKittiConfig` described below.
Class description:
Class that load the semantic kitti config file and helps to handle class ids
Method signatures and docstrings:
- def __init__(self, config_file): Parameters ---------- config_file: str to config file
- def load_semantic_kitti_config(... | Implement the Python class `SemanticKittiConfig` described below.
Class description:
Class that load the semantic kitti config file and helps to handle class ids
Method signatures and docstrings:
- def __init__(self, config_file): Parameters ---------- config_file: str to config file
- def load_semantic_kitti_config(... | 0c2b85e453f7b58275a07592ac1ab7cee7f1651f | <|skeleton|>
class SemanticKittiConfig:
"""Class that load the semantic kitti config file and helps to handle class ids"""
def __init__(self, config_file):
"""Parameters ---------- config_file: str to config file"""
<|body_0|>
def load_semantic_kitti_config(filename=''):
"""Functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemanticKittiConfig:
"""Class that load the semantic kitti config file and helps to handle class ids"""
def __init__(self, config_file):
"""Parameters ---------- config_file: str to config file"""
self.config_file = config_file
self.config = self.load_semantic_kitti_config(config_... | the_stack_v2_python_sparse | smutsia/utils/semantickitti.py | liubigli/smutsia | train | 0 |
e293d75b38929b4ffe54897e47016ab1df2ac729 | [
"super().__init__()\nself.emb_size = emb_size\nself.activation = activation\nself.initializer = initializer\nself.right_to_left = right_to_left\nself.memory_hack = memory_hack\nwith tf.variable_scope('feature_module_left'):\n self.feature_module_left = snt.nets.MLP([self.emb_size], activate_final=True, activatio... | <|body_start_0|>
super().__init__()
self.emb_size = emb_size
self.activation = activation
self.initializer = initializer
self.right_to_left = right_to_left
self.memory_hack = memory_hack
with tf.variable_scope('feature_module_left'):
self.feature_modul... | Partial bipartite graph convolution (either left-to-right or right-to-left). | BipartiteGraphConvolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BipartiteGraphConvolution:
"""Partial bipartite graph convolution (either left-to-right or right-to-left)."""
def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True):
"""For memory_hack see issue https://github.com/ds4dm/lea... | stack_v2_sparse_classes_36k_train_009768 | 9,039 | no_license | [
{
"docstring": "For memory_hack see issue https://github.com/ds4dm/learn2branch/issues/4",
"name": "__init__",
"signature": "def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True)"
},
{
"docstring": "Perfoms a partial graph convolution... | 2 | null | Implement the Python class `BipartiteGraphConvolution` described below.
Class description:
Partial bipartite graph convolution (either left-to-right or right-to-left).
Method signatures and docstrings:
- def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True... | Implement the Python class `BipartiteGraphConvolution` described below.
Class description:
Partial bipartite graph convolution (either left-to-right or right-to-left).
Method signatures and docstrings:
- def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True... | 21a497bd67d82aab27cb883386601db0a062c9d1 | <|skeleton|>
class BipartiteGraphConvolution:
"""Partial bipartite graph convolution (either left-to-right or right-to-left)."""
def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True):
"""For memory_hack see issue https://github.com/ds4dm/lea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BipartiteGraphConvolution:
"""Partial bipartite graph convolution (either left-to-right or right-to-left)."""
def __init__(self, emb_size, activation, initializer, right_to_left=False, memory_hack=False, sum_aggregation=True):
"""For memory_hack see issue https://github.com/ds4dm/learn2branch/iss... | the_stack_v2_python_sparse | liaison/agents/models/bipartite_gcn.py | aravic/liaison | train | 0 |
8142956fb3ad4e9b09fad295d4a94e62325fb930 | [
"self._z_lens = z_lens\nself._ds_dds_mean = ds_dds_mean\nself._ds_dds_sigma2 = ds_dds_sigma ** 2\nself.num_data = 1",
"ds_dds = ddt / dd / (1 + self._z_lens)\nif aniso_scaling is not None:\n scaling = aniso_scaling[0]\nelse:\n scaling = 1\nds_dds_ = ds_dds / scaling\nreturn -(ds_dds_ - self._ds_dds_mean) **... | <|body_start_0|>
self._z_lens = z_lens
self._ds_dds_mean = ds_dds_mean
self._ds_dds_sigma2 = ds_dds_sigma ** 2
self.num_data = 1
<|end_body_0|>
<|body_start_1|>
ds_dds = ddt / dd / (1 + self._z_lens)
if aniso_scaling is not None:
scaling = aniso_scaling[0]
... | class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gaussian. Attention: Gaussian uncertainties in velocity dispersion do not translate into Gaussi... | DsDdsGaussianLikelihood | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DsDdsGaussianLikelihood:
"""class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gaussian. Attention: Gaussian uncertainties ... | stack_v2_sparse_classes_36k_train_009769 | 1,852 | permissive | [
{
"docstring": ":param z_lens: lens redshift :param z_source: source redshift :param ds_dds_mean: mean of Ds/Dds distance ratio :param ds_dds_sigma: 1-sigma uncertainty in the Ds/Dds distance ratio",
"name": "__init__",
"signature": "def __init__(self, z_lens, z_source, ds_dds_mean, ds_dds_sigma)"
},
... | 2 | stack_v2_sparse_classes_30k_train_019282 | Implement the Python class `DsDdsGaussianLikelihood` described below.
Class description:
class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gauss... | Implement the Python class `DsDdsGaussianLikelihood` described below.
Class description:
class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gauss... | 3f31c0ae7540387fe98f778035d415c3cff38756 | <|skeleton|>
class DsDdsGaussianLikelihood:
"""class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gaussian. Attention: Gaussian uncertainties ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DsDdsGaussianLikelihood:
"""class to handle cosmographic likelihood coming from modeling lenses with imaging and kinematic data but no time delays. Thus Ddt is not constrained but the kinematics can constrain Ds/Dds. The likelihood in Ds/Dds is assumed Gaussian. Attention: Gaussian uncertainties in velocity d... | the_stack_v2_python_sparse | hierarc/Likelihood/LensLikelihood/ds_dds_gauss_likelihood.py | jiwoncpark/hierArc | train | 0 |
c611fbe845c124d7062a73f83fe515366d9a8173 | [
"uncond_recodes = [self.schema_type_code_recoder, self.schema_build_id_recoder, self.tabblkst_recoder, self.tabblkcou_recoder, self.tabtractce_recoder, self.tabblkgrpce_recoder, self.tabblk_recoder]\nniu_fill_recodes = [self.rtype_hu_recoder, self.hh_status_recoder]\nfor recode in uncond_recodes:\n row = recode(... | <|body_start_0|>
uncond_recodes = [self.schema_type_code_recoder, self.schema_build_id_recoder, self.tabblkst_recoder, self.tabblkcou_recoder, self.tabtractce_recoder, self.tabblkgrpce_recoder, self.tabblk_recoder]
niu_fill_recodes = [self.rtype_hu_recoder, self.hh_status_recoder]
for recode in ... | H12020MDFHousehold2020Recoder | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_009770 | 22,269 | permissive | [
{
"docstring": "mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object",
"name": "recode",
"signature": "def recode(self, row, nullfill=False)"
},
{
"docstring": ... | 2 | null | Implement the Python class `H12020MDFHousehold2020Recoder` described below.
Class description:
Implement the H12020MDFHousehold2020Recoder class.
Method signatures and docstrings:
- def recode(self, row, nullfill=False): mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the req... | Implement the Python class `H12020MDFHousehold2020Recoder` described below.
Class description:
Implement the H12020MDFHousehold2020Recoder class.
Method signatures and docstrings:
- def recode(self, row, nullfill=False): mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the req... | 7f7ba44055da15d13b191180249e656e1bd398c6 | <|skeleton|>
class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
uncond_recodes = [self.schema... | the_stack_v2_python_sparse | das_decennial/programs/writer/hh2010_to_mdfunit2020.py | p-b-j/uscb-das-container-public | train | 1 | |
0e809e6cbc6da974c911954f052cd10b11e89109 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = self.__nb_objects",
"if not list_dictionaries:\n return '[]'\nelse:\n list_dict = json.dumps(list_dictionaries)\n return list_dict",
"create_list = []\nif not list_objs:\n with open('{}.json'.format(cls.__name__)... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
<|end_body_0|>
<|body_start_1|>
if not list_dictionaries:
return '[]'
else:
list_dict = json.dumps(list_dictionaries)
... | This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will provide the id in case it is found. | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will provide the id in case it is found."""
... | stack_v2_sparse_classes_36k_train_009771 | 3,578 | no_license | [
{
"docstring": "Constructor method to initialize the attribute of the instantiated object with one parameter: Parameter: id (integer): Is a public instance attribute",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Static method using the json.dumps() method th... | 6 | stack_v2_sparse_classes_30k_train_008245 | Implement the Python class `Base` described below.
Class description:
This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will pr... | Implement the Python class `Base` described below.
Class description:
This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will pr... | c7b666ec88abfb82f0d575bcc811a7174d02ac3f | <|skeleton|>
class Base:
"""This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will provide the id in case it is found."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""This class will be the "base" of all other classes in this project. Purpose: manage id attribute in all classes and to avoid duplicating the same code. Created of private class attribute called __nb_objects = 0 which will be a 'counter' that will provide the id in case it is found."""
def __init... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | dianaparr/holbertonschool-higher_level_programming | train | 0 |
c255ec6f58a666e9ed62024a798ec158a6ea10ca | [
"self.defaults = defaults\nself.decimal_separator = decimal_separator\nself.thousands_separator = thousands_separator",
"if i.to_unit is not None:\n units = [i.to_unit]\nelse:\n units = [u for u in self.defaults.defaults(i.dimensionality) if u != i.from_unit]\nif not units:\n raise NoToUnits()\nresults =... | <|body_start_0|>
self.defaults = defaults
self.decimal_separator = decimal_separator
self.thousands_separator = thousands_separator
<|end_body_0|>
<|body_start_1|>
if i.to_unit is not None:
units = [i.to_unit]
else:
units = [u for u in self.defaults.defau... | Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units for conversions. thousands_separator (str): Thousands separator character in... | Converter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units for conversions. thousands_separator (s... | stack_v2_sparse_classes_36k_train_009772 | 20,753 | permissive | [
{
"docstring": "Create new `Converter`. Args: defaults (defaults.Defaults): Default units for conversions. decimal_separator (str, optional): Decimal separator character in query. thousands_separator (str, optional): Thousands separator character in query.",
"name": "__init__",
"signature": "def __init_... | 6 | stack_v2_sparse_classes_30k_train_004943 | Implement the Python class `Converter` described below.
Class description:
Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units ... | Implement the Python class `Converter` described below.
Class description:
Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units ... | 97407f4ec8dbca5abbc6952b2b56cf3918624177 | <|skeleton|>
class Converter:
"""Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units for conversions. thousands_separator (s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Converter:
"""Parse query and convert. Parses user input into an `Input` object, then converts this into one or more `Conversion` objects. Attributes: decimal_separator (str): Decimal separator character in input. defaults (defaults.Defaults): Default units for conversions. thousands_separator (str): Thousand... | the_stack_v2_python_sparse | src/convert.py | deanishe/alfred-convert | train | 781 |
79a2ebda5eff5eb20b3c4462cf776a9d3950548b | [
"self.comms = comms\nself.logger = logger\nself.verbose = verbose\nself.name = 'POM2_CommonML_Master'\nself.platform = comms.name\nself.all_workers_addresses = comms.workers_ids\nself.workers_addresses = comms.workers_ids\nself.Nworkers = len(self.workers_addresses)\nself.reset()\nself.public_key = None\nself.state... | <|body_start_0|>
self.comms = comms
self.logger = logger
self.verbose = verbose
self.name = 'POM2_CommonML_Master'
self.platform = comms.name
self.all_workers_addresses = comms.workers_ids
self.workers_addresses = comms.workers_ids
self.Nworkers = len(self... | This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`. | POM2_CommonML_Master | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class POM2_CommonML_Master:
"""This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`."""
def __init__(self, comms, logger, verbose=False):
"""Create a :class:`POM2_CommonML_Master` instance. Parameters ---------- comms: :cla... | stack_v2_sparse_classes_36k_train_009773 | 16,515 | permissive | [
{
"docstring": "Create a :class:`POM2_CommonML_Master` instance. Parameters ---------- comms: :class:`Comms_master` Object providing communications functionalities. logger: :class:`mylogging.Logger` Logging object instance. verbose: boolean Indicates whether to print messages on screen nor not.",
"name": "_... | 3 | null | Implement the Python class `POM2_CommonML_Master` described below.
Class description:
This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`.
Method signatures and docstrings:
- def __init__(self, comms, logger, verbose=False): Create a :class:`POM2_Com... | Implement the Python class `POM2_CommonML_Master` described below.
Class description:
This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`.
Method signatures and docstrings:
- def __init__(self, comms, logger, verbose=False): Create a :class:`POM2_Com... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class POM2_CommonML_Master:
"""This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`."""
def __init__(self, comms, logger, verbose=False):
"""Create a :class:`POM2_CommonML_Master` instance. Parameters ---------- comms: :cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class POM2_CommonML_Master:
"""This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`."""
def __init__(self, comms, logger, verbose=False):
"""Create a :class:`POM2_CommonML_Master` instance. Parameters ---------- comms: :class:`Comms_mas... | the_stack_v2_python_sparse | MMLL/models/POM2/CommonML/POM2_CommonML.py | Musketeer-H2020/MMLL-Robust | train | 0 |
17e8d4b0fe5ec5300eff2823bc2a05624f3c7c81 | [
"if not hasattr(self, '_flask_secret'):\n token = str(self.random.randint(1, 1e+16))\n self._flask_secret = md5(token.encode('utf-8')).hexdigest()\nreturn self._flask_secret",
"self.app_file = '{}.py'.format(self.app.split(':')[0])\nassert os.path.isfile(self.app_file), 'module must exist'\nif self.python_v... | <|body_start_0|>
if not hasattr(self, '_flask_secret'):
token = str(self.random.randint(1, 1e+16))
self._flask_secret = md5(token.encode('utf-8')).hexdigest()
return self._flask_secret
<|end_body_0|>
<|body_start_1|>
self.app_file = '{}.py'.format(self.app.split(':')[0])... | Class for python Flask web apps | FlaskApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlaskApp:
"""Class for python Flask web apps"""
def flask_secret(self):
"""Provides flask_secret on-demand with caching"""
<|body_0|>
def flask_setup(self):
"""Setup for flask apps"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not hasattr(s... | stack_v2_sparse_classes_36k_train_009774 | 9,323 | permissive | [
{
"docstring": "Provides flask_secret on-demand with caching",
"name": "flask_secret",
"signature": "def flask_secret(self)"
},
{
"docstring": "Setup for flask apps",
"name": "flask_setup",
"signature": "def flask_setup(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004857 | Implement the Python class `FlaskApp` described below.
Class description:
Class for python Flask web apps
Method signatures and docstrings:
- def flask_secret(self): Provides flask_secret on-demand with caching
- def flask_setup(self): Setup for flask apps | Implement the Python class `FlaskApp` described below.
Class description:
Class for python Flask web apps
Method signatures and docstrings:
- def flask_secret(self): Provides flask_secret on-demand with caching
- def flask_setup(self): Setup for flask apps
<|skeleton|>
class FlaskApp:
"""Class for python Flask w... | 468035038afe00c6e7842b7e68ec45355ee1a224 | <|skeleton|>
class FlaskApp:
"""Class for python Flask web apps"""
def flask_secret(self):
"""Provides flask_secret on-demand with caching"""
<|body_0|>
def flask_setup(self):
"""Setup for flask apps"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlaskApp:
"""Class for python Flask web apps"""
def flask_secret(self):
"""Provides flask_secret on-demand with caching"""
if not hasattr(self, '_flask_secret'):
token = str(self.random.randint(1, 1e+16))
self._flask_secret = md5(token.encode('utf-8')).hexdigest()
... | the_stack_v2_python_sparse | picoCTF-shell/hacksport/problem.py | zxc135781/picoCTF | train | 1 |
47c0d013e2ebd8bdc59d631807068ee06d5acdee | [
"f1, f2, res = (1, 1, 1)\nfor _ in range(1, n):\n res = f1 + f2\n f1, f2 = (f2, res)\nreturn res",
"if n in self.memo:\n res = self.memo[n]\nelse:\n a = self.climbStairs(n - 1)\n b = self.climbStairs(n - 2)\n res = self.memo[n] = a + b\nreturn res"
] | <|body_start_0|>
f1, f2, res = (1, 1, 1)
for _ in range(1, n):
res = f1 + f2
f1, f2 = (f2, res)
return res
<|end_body_0|>
<|body_start_1|>
if n in self.memo:
res = self.memo[n]
else:
a = self.climbStairs(n - 1)
b = self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs_1(self, n: int) -> int:
"""" 1. 递推"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 # 所以路径数量,是前两者的路径数量之和"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f1, f2, res = (1, ... | stack_v2_sparse_classes_36k_train_009775 | 1,533 | no_license | [
{
"docstring": "\" 1. 递推",
"name": "climbStairs_1",
"signature": "def climbStairs_1(self, n: int) -> int"
},
{
"docstring": "2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 # 所以路径数量,是前两者的路径数量之和",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs_1(self, n: int) -> int: " 1. 递推
- def climbStairs(self, n: int) -> int: 2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 # 所以路径数量,是前两者的路径数量之和 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs_1(self, n: int) -> int: " 1. 递推
- def climbStairs(self, n: int) -> int: 2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 # 所以路径数量,是前两者的路径数量之和
<|skeleton|>
class Sol... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def climbStairs_1(self, n: int) -> int:
"""" 1. 递推"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 # 所以路径数量,是前两者的路径数量之和"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs_1(self, n: int) -> int:
"""" 1. 递推"""
f1, f2, res = (1, 1, 1)
for _ in range(1, n):
res = f1 + f2
f1, f2 = (f2, res)
return res
def climbStairs(self, n: int) -> int:
"""2.递归 # 第 n 阶,可以通过 n-1 阶跨一步达到,也可以通过 n-2 阶跨两步达到 ... | the_stack_v2_python_sparse | .leetcode/70.爬楼梯.py | xiaoruijiang/algorithm | train | 0 | |
c1b9d9f1f1633ad28b112500e10f66e5350476ea | [
"self.validate_parameters(request=request)\n_query_builder = Configuration.get_base_uri()\n_query_builder += '/validation/no/bankid/parse'\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json', 'content-type': 'application/json; charset=utf-8'}\n_request = self.http_client.post... | <|body_start_0|>
self.validate_parameters(request=request)
_query_builder = Configuration.get_base_uri()
_query_builder += '/validation/no/bankid/parse'
_query_url = APIHelper.clean_url(_query_builder)
_headers = {'accept': 'application/json', 'content-type': 'application/json; c... | A Controller to access Endpoints in the idfy_rest_client API. | NorwegianBankIDController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NorwegianBankIDController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def no_bank_id_validation_parse_sdo(self, request):
"""Does a POST request to /validation/no/bankid/parse. This service validates and parses the signatures on the SDOdata, to validate/parse... | stack_v2_sparse_classes_36k_train_009776 | 4,300 | permissive | [
{
"docstring": "Does a POST request to /validation/no/bankid/parse. This service validates and parses the signatures on the SDOdata, to validate/parse the SDO we use the validation component from bankID norway. This endpoint parses the SDO to readable data and provides you with information about the signatures ... | 2 | null | Implement the Python class `NorwegianBankIDController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def no_bank_id_validation_parse_sdo(self, request): Does a POST request to /validation/no/bankid/parse. This service validates an... | Implement the Python class `NorwegianBankIDController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def no_bank_id_validation_parse_sdo(self, request): Does a POST request to /validation/no/bankid/parse. This service validates an... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class NorwegianBankIDController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def no_bank_id_validation_parse_sdo(self, request):
"""Does a POST request to /validation/no/bankid/parse. This service validates and parses the signatures on the SDOdata, to validate/parse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NorwegianBankIDController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def no_bank_id_validation_parse_sdo(self, request):
"""Does a POST request to /validation/no/bankid/parse. This service validates and parses the signatures on the SDOdata, to validate/parse the SDO we u... | the_stack_v2_python_sparse | idfy_rest_client/controllers/norwegian_bank_id_controller.py | dealflowteam/Idfy | train | 0 |
d733014a1e531a098d057a58d33201308abd1c0f | [
"model = model if isinstance(model, SpaceForDialogModeling) else Model.from_pretrained(model)\nself.model = model\nif preprocessor is None:\n preprocessor = DialogModelingPreprocessor(model.model_dir)\nsuper().__init__(model=model, preprocessor=preprocessor, **kwargs)\nself.preprocessor = preprocessor",
"sys_r... | <|body_start_0|>
model = model if isinstance(model, SpaceForDialogModeling) else Model.from_pretrained(model)
self.model = model
if preprocessor is None:
preprocessor = DialogModelingPreprocessor(model.model_dir)
super().__init__(model=model, preprocessor=preprocessor, **kwar... | DialogModelingPipeline | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling... | stack_v2_sparse_classes_36k_train_009777 | 2,107 | permissive | [
{
"docstring": "Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling): Supply either a local model dir or a model id from the model hub, or a SpaceForDialogModeling instance. preprocessor (DialogModelingPreprocessor): An op... | 2 | stack_v2_sparse_classes_30k_val_000862 | Implement the Python class `DialogModelingPipeline` described below.
Class description:
Implement the DialogModelingPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs): Use `model` and `preprocessor`... | Implement the Python class `DialogModelingPipeline` described below.
Class description:
Implement the DialogModelingPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs): Use `model` and `preprocessor`... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling): Supply eith... | the_stack_v2_python_sparse | ai/modelscope/modelscope/pipelines/nlp/dialog_modeling_pipeline.py | alldatacenter/alldata | train | 774 | |
1589d5646a09cfe8091a95331f4faeb138279e63 | [
"with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as f:\n xsd = f.read()\netree.clear_error_log()\nschema_root = etree.XML(xsd)\nschema = etree.XMLSchema(schema_root)\nparser = etree.XMLParser(schema=schema, encoding='utf8')\ntry:\n root = etree.fromstring(bytes(xml, 'utf8'), parser)\n if root.tag ... | <|body_start_0|>
with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as f:
xsd = f.read()
etree.clear_error_log()
schema_root = etree.XML(xsd)
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema=schema, encoding='utf8')
try:
... | XmlReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlReader:
def parse_schedule(xml, filename):
"""Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.ScheduleNode"""
<|body_0|>
def parse_dynamic_worker(xml, parent):
"""Parses a... | stack_v2_sparse_classes_36k_train_009778 | 4,365 | permissive | [
{
"docstring": "Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.ScheduleNode",
"name": "parse_schedule",
"signature": "def parse_schedule(xml, filename)"
},
{
"docstring": "Parses a schedule definition i... | 3 | null | Implement the Python class `XmlReader` described below.
Class description:
Implement the XmlReader class.
Method signatures and docstrings:
- def parse_schedule(xml, filename): Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.... | Implement the Python class `XmlReader` described below.
Class description:
Implement the XmlReader class.
Method signatures and docstrings:
- def parse_schedule(xml, filename): Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.... | ec0c33cdae4a0afeea37928743abd744ef291a9f | <|skeleton|>
class XmlReader:
def parse_schedule(xml, filename):
"""Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.ScheduleNode"""
<|body_0|>
def parse_dynamic_worker(xml, parent):
"""Parses a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlReader:
def parse_schedule(xml, filename):
"""Parses a schedule definition in XML. :param str xml: The XML with a schedule definition :param str filename: :rtype: enarksh.xml_reader.node.ScheduleNode"""
with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as f:
xsd = f.read(... | the_stack_v2_python_sparse | enarksh/xml_reader/XmlReader.py | SetBased/py-enarksh | train | 3 | |
101eda68574eb2a7bcd72e0282e2a0a74879d1f2 | [
"dist = []\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n dist.append(abs(nums[i] - nums[j]))\n\ndef quick_select(arr, s, e, k):\n pivot = arr[e]\n i, j = (s, e - 1)\n while i <= j:\n if arr[i] <= pivot:\n i += 1\n elif arr[j] > pivot:\n j -=... | <|body_start_0|>
dist = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
dist.append(abs(nums[i] - nums[j]))
def quick_select(arr, s, e, k):
pivot = arr[e]
i, j = (s, e - 1)
while i <= j:
if arr[i] <=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
"""11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)"""
<|body_0|>
def smallestDistancePair(self, nums: List[int], k: int) -> int:
"""11/28/2022 18:31 Time Complexity: O(n*... | stack_v2_sparse_classes_36k_train_009779 | 3,962 | no_license | [
{
"docstring": "11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)",
"name": "smallestDistancePair",
"signature": "def smallestDistancePair(self, nums: List[int], k: int) -> int"
},
{
"docstring": "11/28/2022 18:31 Time Complexity: O(n*logn) + O(n*logm) where m = max(nums)",
... | 2 | stack_v2_sparse_classes_30k_train_003739 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestDistancePair(self, nums: List[int], k: int) -> int: 11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)
- def smallestDistancePair(self, nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestDistancePair(self, nums: List[int], k: int) -> int: 11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)
- def smallestDistancePair(self, nums: List... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
"""11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)"""
<|body_0|>
def smallestDistancePair(self, nums: List[int], k: int) -> int:
"""11/28/2022 18:31 Time Complexity: O(n*... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
"""11/28/2022 18:19, TLE Time Complexity: O(n^2) Space Complexity: O(n^2)"""
dist = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
dist.append(abs(nums[i] - nums[j]))
... | the_stack_v2_python_sparse | leetcode/solved/719_Find_K-th_Smallest_Pair_Distance/solution.py | sungminoh/algorithms | train | 0 | |
2953b686abaa2b3c6de42c0caabe3de2bd560112 | [
"n = len(stations)\nF = [0] * (n + 1)\nF[0] = startFuel\nfor i, (loc, cap) in enumerate(stations):\n for t in range(i, -1, -1):\n if F[t] >= loc:\n F[t + 1] = max(F[t + 1], F[t] + cap)\nfor i, d in enumerate(F):\n if d >= target:\n return i\nreturn -1",
"i = res = 0\npq = []\ncur = ... | <|body_start_0|>
n = len(stations)
F = [0] * (n + 1)
F[0] = startFuel
for i, (loc, cap) in enumerate(stations):
for t in range(i, -1, -1):
if F[t] >= loc:
F[t + 1] = max(F[t + 1], F[t] + cap)
for i, d in enumerate(F):
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minRefuelStopsDP(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int"""
<|body_0|>
def minRefuelStops(self, target, startFuel, stations):
""":type target: int :type startFuel: int :ty... | stack_v2_sparse_classes_36k_train_009780 | 3,918 | no_license | [
{
"docstring": ":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int",
"name": "minRefuelStopsDP",
"signature": "def minRefuelStopsDP(self, target, startFuel, stations)"
},
{
"docstring": ":type target: int :type startFuel: int :type stations: List[List[int]] :rtype... | 2 | stack_v2_sparse_classes_30k_train_016097 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minRefuelStopsDP(self, target, startFuel, stations): :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int
- def minRefuelStops(self, target, sta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minRefuelStopsDP(self, target, startFuel, stations): :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int
- def minRefuelStops(self, target, sta... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def minRefuelStopsDP(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int"""
<|body_0|>
def minRefuelStops(self, target, startFuel, stations):
""":type target: int :type startFuel: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minRefuelStopsDP(self, target, startFuel, stations):
""":type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int"""
n = len(stations)
F = [0] * (n + 1)
F[0] = startFuel
for i, (loc, cap) in enumerate(stations):
for t i... | the_stack_v2_python_sparse | M/MinimumNumberofRefuelingStops.py | bssrdf/pyleet | train | 2 | |
3d53c1aec4a26c471e66d8c60b20d73e7b36de34 | [
"self.SUBJECT = 'MOSJA00291'\nsuper(OASEMailInitialLoginID, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)\nself.create_mail_text(user_name, login_id, expire_h)",
"self.MAILTEXT = get_message('MOSJA00292', self.lang_mode, showMsgId=False, user_name=user_name, login_id=log... | <|body_start_0|>
self.SUBJECT = 'MOSJA00291'
super(OASEMailInitialLoginID, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)
self.create_mail_text(user_name, login_id, expire_h)
<|end_body_0|>
<|body_start_1|>
self.MAILTEXT = get_message('MOSJA0029... | [クラス概要] ログインID通知メール | OASEMailInitialLoginID | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OASEMailInitialLoginID:
"""[クラス概要] ログインID通知メール"""
def __init__(self, addr_from, addr_to, user_name, login_id, expire_h, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ログインID exp... | stack_v2_sparse_classes_36k_train_009781 | 20,173 | permissive | [
{
"docstring": "[メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ログインID expire_h : int パスワード有効期間(hour) inquiry_url : str お問い合わせ画面 login_url : str ログイン画面 charset : str 文字コード",
"name": "__init__",
"signature": "def __init__(self, addr_from, addr_... | 2 | null | Implement the Python class `OASEMailInitialLoginID` described below.
Class description:
[クラス概要] ログインID通知メール
Method signatures and docstrings:
- def __init__(self, addr_from, addr_to, user_name, login_id, expire_h, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛... | Implement the Python class `OASEMailInitialLoginID` described below.
Class description:
[クラス概要] ログインID通知メール
Method signatures and docstrings:
- def __init__(self, addr_from, addr_to, user_name, login_id, expire_h, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class OASEMailInitialLoginID:
"""[クラス概要] ログインID通知メール"""
def __init__(self, addr_from, addr_to, user_name, login_id, expire_h, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ログインID exp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OASEMailInitialLoginID:
"""[クラス概要] ログインID通知メール"""
def __init__(self, addr_from, addr_to, user_name, login_id, expire_h, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_from : str 送信者メールアドレス addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ログインID expire_h : int パ... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/oase_mail.py | exastro-suite/oase | train | 10 |
9e818d8d579dfdbbc06aabbb4b31adfc07882d72 | [
"self.vec = vec2d\nself.row = 0\nself.col = 0\ni = 0\nwhile self.row != len(self.vec):\n if len(self.vec[self.row]) != 0:\n self.col = 0\n break\n self.row += 1",
"ret = self.vec[self.row][self.col]\nself.col += 1\nreturn ret",
"if self.row == len(self.vec):\n return False\nif self.col !=... | <|body_start_0|>
self.vec = vec2d
self.row = 0
self.col = 0
i = 0
while self.row != len(self.vec):
if len(self.vec[self.row]) != 0:
self.col = 0
break
self.row += 1
<|end_body_0|>
<|body_start_1|>
ret = self.vec[sel... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_009782 | 7,345 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_021054 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 5195b032d8000a3d888e2d4068984011bebd3b84 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec = vec2d
self.row = 0
self.col = 0
i = 0
while self.row != len(self.vec):
if len(self.vec[self.row]) != 0:
self.col =... | the_stack_v2_python_sparse | leetcode_python/Array/flatten-2d-vector.py | ChillOrb/CS_basics | train | 1 | |
5af3c46571d8cc5ff809cd1bc7207ec760d36137 | [
"self.pump = Pump('127.0.0.1', 8000)\nself.sensor = Sensor('127.1.1.3', 9000)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=110)\nself.pump.get_state = MagicMock(return_value='PUMP_OFF')\nself.controller.tick ... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.1.1.3', 9000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=110)
... | Module tests for the water-regulation module | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""setup :return:"""
<|body_0|>
def test_tick(self):
"""test tick of Controller class :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump('127... | stack_v2_sparse_classes_36k_train_009783 | 1,056 | no_license | [
{
"docstring": "setup :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test tick of Controller class :return:",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | null | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): setup :return:
- def test_tick(self): test tick of Controller class :return: | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): setup :return:
- def test_tick(self): test tick of Controller class :return:
<|skeleton|>
class ModuleTests:
"""Module tests for the water... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""setup :return:"""
<|body_0|>
def test_tick(self):
"""test tick of Controller class :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""setup :return:"""
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.1.1.3', 9000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, ... | the_stack_v2_python_sparse | students/marc_charbo/assignment_6/assign_6/waterregulation/integrationtest.py | aurel1212/Sp2018-Online | train | 0 |
9c92fbd9297794a203831d22c596a06ad3f1623d | [
"Presentation.__init__(self, pere, detail, attribut, False)\nif pere and detail:\n self.construire(detail)",
"detail = self.objet\nsalle = detail.parent\nnouveau_nom = supprimer_accents(arguments)\nif not nouveau_nom:\n self.pere << '|err|Vous devez indiquer un nouveau nom.|ff|'\n return\nif nouveau_nom ... | <|body_start_0|>
Presentation.__init__(self, pere, detail, attribut, False)
if pere and detail:
self.construire(detail)
<|end_body_0|>
<|body_start_1|>
detail = self.objet
salle = detail.parent
nouveau_nom = supprimer_accents(arguments)
if not nouveau_nom:
... | Ce contexte permet d'éditer un detail observable d'une salle. | EdtDetail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdtDetail:
"""Ce contexte permet d'éditer un detail observable d'une salle."""
def __init__(self, pere, detail=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_renommer_detail(self, arguments):
"""Renomme le détail courant. Syntaxe : /n <n... | stack_v2_sparse_classes_36k_train_009784 | 7,487 | permissive | [
{
"docstring": "Constructeur de l'éditeur",
"name": "__init__",
"signature": "def __init__(self, pere, detail=None, attribut=None)"
},
{
"docstring": "Renomme le détail courant. Syntaxe : /n <nouveau nom>",
"name": "opt_renommer_detail",
"signature": "def opt_renommer_detail(self, argume... | 4 | stack_v2_sparse_classes_30k_train_003547 | Implement the Python class `EdtDetail` described below.
Class description:
Ce contexte permet d'éditer un detail observable d'une salle.
Method signatures and docstrings:
- def __init__(self, pere, detail=None, attribut=None): Constructeur de l'éditeur
- def opt_renommer_detail(self, arguments): Renomme le détail cou... | Implement the Python class `EdtDetail` described below.
Class description:
Ce contexte permet d'éditer un detail observable d'une salle.
Method signatures and docstrings:
- def __init__(self, pere, detail=None, attribut=None): Constructeur de l'éditeur
- def opt_renommer_detail(self, arguments): Renomme le détail cou... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class EdtDetail:
"""Ce contexte permet d'éditer un detail observable d'une salle."""
def __init__(self, pere, detail=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_renommer_detail(self, arguments):
"""Renomme le détail courant. Syntaxe : /n <n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdtDetail:
"""Ce contexte permet d'éditer un detail observable d'une salle."""
def __init__(self, pere, detail=None, attribut=None):
"""Constructeur de l'éditeur"""
Presentation.__init__(self, pere, detail, attribut, False)
if pere and detail:
self.construire(detail)
... | the_stack_v2_python_sparse | src/primaires/salle/editeurs/redit/edt_detail.py | vincent-lg/tsunami | train | 5 |
8aeff0b9ef4ccbf9a8a6c374cb3566705965f099 | [
"self.num_layer = num_layer\nself.num_filter = num_filter\nself.unit_dim = unit_dim\nself.window_size = window_size\nself.dropout = dropout\nself.num_gpus = num_gpus\nself.default_gpu_id = default_gpu_id\nself.regularizer = regularizer\nself.random_seed = random_seed\nself.trainable = trainable\nself.scope = scope\... | <|body_start_0|>
self.num_layer = num_layer
self.num_filter = num_filter
self.unit_dim = unit_dim
self.window_size = window_size
self.dropout = dropout
self.num_gpus = num_gpus
self.default_gpu_id = default_gpu_id
self.regularizer = regularizer
sel... | stacked convolution highway layer | StackedConvHighway | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackedConvHighway:
"""stacked convolution highway layer"""
def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_conv_highway'):
"""initialize stacked convolution high... | stack_v2_sparse_classes_36k_train_009785 | 9,944 | permissive | [
{
"docstring": "initialize stacked convolution highway layer",
"name": "__init__",
"signature": "def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_conv_highway')"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_017764 | Implement the Python class `StackedConvHighway` described below.
Class description:
stacked convolution highway layer
Method signatures and docstrings:
- def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='st... | Implement the Python class `StackedConvHighway` described below.
Class description:
stacked convolution highway layer
Method signatures and docstrings:
- def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='st... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class StackedConvHighway:
"""stacked convolution highway layer"""
def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_conv_highway'):
"""initialize stacked convolution high... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackedConvHighway:
"""stacked convolution highway layer"""
def __init__(self, num_layer, num_filter, window_size, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_conv_highway'):
"""initialize stacked convolution highway layer"""
... | the_stack_v2_python_sparse | sequence_labeling/layer/highway.py | stevezheng23/sequence_labeling_tf | train | 18 |
56e4ef4c248796422637fe18700f4d37960c9834 | [
"self.output_name = output_name\nself.metric_name = metric_name\nself.split_name = split_name\nself.dataset_name = dataset_name\nself.minimum_metric = minimum_metric\nself.best_metric = 10000000000.0",
"if metric_value is not None and metric_value < self.minimum_metric and (metric_value < self.best_metric):\n ... | <|body_start_0|>
self.output_name = output_name
self.metric_name = metric_name
self.split_name = split_name
self.dataset_name = dataset_name
self.minimum_metric = minimum_metric
self.best_metric = 10000000000.0
<|end_body_0|>
<|body_start_1|>
if metric_value is n... | ModelWithLowestMetric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be... | stack_v2_sparse_classes_36k_train_009786 | 9,199 | permissive | [
{
"docstring": "Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be considered for the best model minimum_metric: consider only the metric lower than this threshold output_name: the output to b... | 2 | stack_v2_sparse_classes_30k_train_015018 | Implement the Python class `ModelWithLowestMetric` described below.
Class description:
Implement the ModelWithLowestMetric class.
Method signatures and docstrings:
- def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2): Args: dataset_name: the dataset name to be considered for th... | Implement the Python class `ModelWithLowestMetric` described below.
Class description:
Implement the ModelWithLowestMetric class.
Method signatures and docstrings:
- def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2): Args: dataset_name: the dataset name to be considered for th... | 11c59dea0072d940b036166be22b392bb9e3b066 | <|skeleton|>
class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be considered fo... | the_stack_v2_python_sparse | src/trw/callbacks/callback_save_last_model.py | civodlu/trw | train | 12 | |
ada0d47fc4faf5d3a118e4f791e4cda621ee4016 | [
"export_type = self.kwargs.get('format')\nif self.action == 'data' and export_type == 'geojson':\n serializer_class = GeoJsonSerializer\nelse:\n serializer_class = self.serializer_class\nreturn serializer_class",
"queryset = self.filter_queryset(self.get_queryset())\npage = self.paginate_queryset(queryset)\... | <|body_start_0|>
export_type = self.kwargs.get('format')
if self.action == 'data' and export_type == 'geojson':
serializer_class = GeoJsonSerializer
else:
serializer_class = self.serializer_class
return serializer_class
<|end_body_0|>
<|body_start_1|>
que... | Merged XForms viewset: create, list, retrieve, destroy | MergedXFormViewSet | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergedXFormViewSet:
"""Merged XForms viewset: create, list, retrieve, destroy"""
def get_serializer_class(self):
"""Get appropriate serializer class"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List endpoint for Merged XForms"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_009787 | 3,891 | permissive | [
{
"docstring": "Get appropriate serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List endpoint for Merged XForms",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Return ... | 4 | null | Implement the Python class `MergedXFormViewSet` described below.
Class description:
Merged XForms viewset: create, list, retrieve, destroy
Method signatures and docstrings:
- def get_serializer_class(self): Get appropriate serializer class
- def list(self, request, *args, **kwargs): List endpoint for Merged XForms
- ... | Implement the Python class `MergedXFormViewSet` described below.
Class description:
Merged XForms viewset: create, list, retrieve, destroy
Method signatures and docstrings:
- def get_serializer_class(self): Get appropriate serializer class
- def list(self, request, *args, **kwargs): List endpoint for Merged XForms
- ... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class MergedXFormViewSet:
"""Merged XForms viewset: create, list, retrieve, destroy"""
def get_serializer_class(self):
"""Get appropriate serializer class"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List endpoint for Merged XForms"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergedXFormViewSet:
"""Merged XForms viewset: create, list, retrieve, destroy"""
def get_serializer_class(self):
"""Get appropriate serializer class"""
export_type = self.kwargs.get('format')
if self.action == 'data' and export_type == 'geojson':
serializer_class = Geo... | the_stack_v2_python_sparse | onadata/apps/api/viewsets/merged_xform_viewset.py | onaio/onadata | train | 177 |
a72b9884d256ad81624016c36f77d6624057ca7f | [
"command = f'prlimit --noheadings --pid={pid}'\nmessage = f\"Node {node[u'host']} failed to run: {command}\"\nexec_cmd_no_error(node, command, sudo=True, message=message)",
"command = f'prlimit --{resource}={limit} --pid={pid}'\nmessage = f\"Node {node[u'host']} failed to run: {command}\"\nexec_cmd_no_error(node,... | <|body_start_0|>
command = f'prlimit --noheadings --pid={pid}'
message = f"Node {node[u'host']} failed to run: {command}"
exec_cmd_no_error(node, command, sudo=True, message=message)
<|end_body_0|>
<|body_start_1|>
command = f'prlimit --{resource}={limit} --pid={pid}'
message = ... | Class contains methods for getting or setting process resource limits. | LimitUtil | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimitUtil:
"""Class contains methods for getting or setting process resource limits."""
def get_pid_limit(node, pid):
"""Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :type pid: int"""
<|body_0|>
def set_pid_limi... | stack_v2_sparse_classes_36k_train_009788 | 1,813 | permissive | [
{
"docstring": "Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :type pid: int",
"name": "get_pid_limit",
"signature": "def get_pid_limit(node, pid)"
},
{
"docstring": "Set process resource limits. :param node: Node in the topology. :param... | 2 | null | Implement the Python class `LimitUtil` described below.
Class description:
Class contains methods for getting or setting process resource limits.
Method signatures and docstrings:
- def get_pid_limit(node, pid): Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :... | Implement the Python class `LimitUtil` described below.
Class description:
Class contains methods for getting or setting process resource limits.
Method signatures and docstrings:
- def get_pid_limit(node, pid): Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LimitUtil:
"""Class contains methods for getting or setting process resource limits."""
def get_pid_limit(node, pid):
"""Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :type pid: int"""
<|body_0|>
def set_pid_limi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LimitUtil:
"""Class contains methods for getting or setting process resource limits."""
def get_pid_limit(node, pid):
"""Get process resource limits. :param node: Node in the topology. :param pid: Process ID. :type node: dict :type pid: int"""
command = f'prlimit --noheadings --pid={pid}'... | the_stack_v2_python_sparse | resources/libraries/python/LimitUtil.py | FDio/csit | train | 28 |
571246d3a845424403bf6567980060a9a903bfd8 | [
"self.namespace = namespace\nself.method = method\nself.arg_generator = arg_generator",
"raw = self.arg_generator.raw\nrequest = self.arg_generator.CreateRequest(self.namespace)\nlimit = self.arg_generator.Limit(self.namespace)\npage_size = self.arg_generator.PageSize(self.namespace)\nreturn self.method.Call(requ... | <|body_start_0|>
self.namespace = namespace
self.method = method
self.arg_generator = arg_generator
<|end_body_0|>
<|body_start_1|>
raw = self.arg_generator.raw
request = self.arg_generator.CreateRequest(self.namespace)
limit = self.arg_generator.Limit(self.namespace)
... | Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags were added and manually extract them. T... | MethodRef | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags we... | stack_v2_sparse_classes_36k_train_009789 | 5,259 | permissive | [
{
"docstring": "Creates the MethodRef. Args: namespace: The argparse namespace that holds the parsed args. method: APIMethod, The method. arg_generator: arg_marshalling.AutoArgumentGenerator, The generator for this method.",
"name": "__init__",
"signature": "def __init__(self, namespace, method, arg_gen... | 2 | null | Implement the Python class `MethodRef` described below.
Class description:
Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doe... | Implement the Python class `MethodRef` described below.
Class description:
Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doe... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags we... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MethodRef:
"""Encapsulates a method specified on the command line with all its flags. This makes use of an ArgumentGenerator to generate and parse all the flags that correspond to a method. It provides a simple interface to the command so the implementor doesn't need to be aware of which flags were added and ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/meta/apis/flags.py | bopopescu/socialliteapp | train | 0 |
365a65f7a3f5594c7090eeadb273a2173e59488e | [
"schedule_type = 'cron'\nschedule_value = '0 */6 * * *'\nschedule_policy_cron_style = self.autoscale_behaviors.create_schedule_policy_given(group_id=self.group.id, sp_change=self.sp_change, schedule_cron=schedule_value)\nself.assertEquals(schedule_policy_cron_style['status_code'], 201, msg='Create schedule scaling ... | <|body_start_0|>
schedule_type = 'cron'
schedule_value = '0 */6 * * *'
schedule_policy_cron_style = self.autoscale_behaviors.create_schedule_policy_given(group_id=self.group.id, sp_change=self.sp_change, schedule_cron=schedule_value)
self.assertEquals(schedule_policy_cron_style['status_c... | Verify create schedule policy. | CreateScheduleScalingPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateScheduleScalingPolicy:
"""Verify create schedule policy."""
def test_create_schedule_cron_style_scaling_policy(self):
"""Create a scaling policy of type schedule and via cron style, verify response code 201, headers and data."""
<|body_0|>
def test_create_schedule_... | stack_v2_sparse_classes_36k_train_009790 | 4,893 | permissive | [
{
"docstring": "Create a scaling policy of type schedule and via cron style, verify response code 201, headers and data.",
"name": "test_create_schedule_cron_style_scaling_policy",
"signature": "def test_create_schedule_cron_style_scaling_policy(self)"
},
{
"docstring": "Create a scaling policy ... | 2 | null | Implement the Python class `CreateScheduleScalingPolicy` described below.
Class description:
Verify create schedule policy.
Method signatures and docstrings:
- def test_create_schedule_cron_style_scaling_policy(self): Create a scaling policy of type schedule and via cron style, verify response code 201, headers and d... | Implement the Python class `CreateScheduleScalingPolicy` described below.
Class description:
Verify create schedule policy.
Method signatures and docstrings:
- def test_create_schedule_cron_style_scaling_policy(self): Create a scaling policy of type schedule and via cron style, verify response code 201, headers and d... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class CreateScheduleScalingPolicy:
"""Verify create schedule policy."""
def test_create_schedule_cron_style_scaling_policy(self):
"""Create a scaling policy of type schedule and via cron style, verify response code 201, headers and data."""
<|body_0|>
def test_create_schedule_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateScheduleScalingPolicy:
"""Verify create schedule policy."""
def test_create_schedule_cron_style_scaling_policy(self):
"""Create a scaling policy of type schedule and via cron style, verify response code 201, headers and data."""
schedule_type = 'cron'
schedule_value = '0 */6... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/functional/scheduler/test_create_schedule_policy.py | rackerlabs/otter | train | 20 |
7a09780d23b7c1a6fa3c8883149960bd40442331 | [
"super().__init__()\nself.cnn_type = cnn_type\nself.n_channels = n_channels\nself.output_dim = output_dim\nif cnn_type == 'wideresnet':\n self.cnn = torchvision.models.wide_resnet50_2()\n self.cnn.conv1 = nn.Conv2d(n_channels, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n self.cnn.fc... | <|body_start_0|>
super().__init__()
self.cnn_type = cnn_type
self.n_channels = n_channels
self.output_dim = output_dim
if cnn_type == 'wideresnet':
self.cnn = torchvision.models.wide_resnet50_2()
self.cnn.conv1 = nn.Conv2d(n_channels, 64, kernel_size=(7, 7... | StrokeAsImageEncoderCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrokeAsImageEncoderCNN:
def __init__(self, cnn_type, n_channels, output_dim):
"""Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, which can vary depending on if pre, post, full images are used output_dim (int): output dim"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_009791 | 40,451 | permissive | [
{
"docstring": "Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, which can vary depending on if pre, post, full images are used output_dim (int): output dim",
"name": "__init__",
"signature": "def __init__(self, cnn_type, n_channels, output_dim)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_006295 | Implement the Python class `StrokeAsImageEncoderCNN` described below.
Class description:
Implement the StrokeAsImageEncoderCNN class.
Method signatures and docstrings:
- def __init__(self, cnn_type, n_channels, output_dim): Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, whic... | Implement the Python class `StrokeAsImageEncoderCNN` described below.
Class description:
Implement the StrokeAsImageEncoderCNN class.
Method signatures and docstrings:
- def __init__(self, cnn_type, n_channels, output_dim): Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, whic... | b0c7f25d13e1713b883335c278d1e0db67c50bbe | <|skeleton|>
class StrokeAsImageEncoderCNN:
def __init__(self, cnn_type, n_channels, output_dim):
"""Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, which can vary depending on if pre, post, full images are used output_dim (int): output dim"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrokeAsImageEncoderCNN:
def __init__(self, cnn_type, n_channels, output_dim):
"""Args: cnn_type (str): wideresnet, cbam, or se n_channels (int): Number of input channels, which can vary depending on if pre, post, full images are used output_dim (int): output dim"""
super().__init__()
... | the_stack_v2_python_sparse | src/models/base/stroke_models.py | sosuperic/sketching-with-language | train | 0 | |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"theme = Theme.objects.all()\nserializer = ThemeListSerializer(theme, many=True)\nreturn Response(serializer.data)",
"queryset = Theme.objects.all()\ntheme = get_object_or_404(queryset, pk=pk)\nserializer = ThemeSerializer(theme)\nreturn Response(serializer.data)"
] | <|body_start_0|>
theme = Theme.objects.all()
serializer = ThemeListSerializer(theme, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = Theme.objects.all()
theme = get_object_or_404(queryset, pk=pk)
serializer = ThemeSerializer(theme)
... | ThemeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThemeView:
def list(self, request):
"""Получение списка тем"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение темы по идентификатору pk - идентификатор темы"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
theme = Theme.objects.all()
... | stack_v2_sparse_classes_36k_train_009792 | 12,404 | no_license | [
{
"docstring": "Получение списка тем",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение темы по идентификатору pk - идентификатор темы",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013456 | Implement the Python class `ThemeView` described below.
Class description:
Implement the ThemeView class.
Method signatures and docstrings:
- def list(self, request): Получение списка тем
- def retrieve(self, request, pk=None): Получение темы по идентификатору pk - идентификатор темы | Implement the Python class `ThemeView` described below.
Class description:
Implement the ThemeView class.
Method signatures and docstrings:
- def list(self, request): Получение списка тем
- def retrieve(self, request, pk=None): Получение темы по идентификатору pk - идентификатор темы
<|skeleton|>
class ThemeView:
... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class ThemeView:
def list(self, request):
"""Получение списка тем"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение темы по идентификатору pk - идентификатор темы"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThemeView:
def list(self, request):
"""Получение списка тем"""
theme = Theme.objects.all()
serializer = ThemeListSerializer(theme, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение темы по идентификатору pk - идентификат... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
5c42dbb93b57ea8ea4b85e8945c89c589c9a037b | [
"num = str(num)\nn = len(num)\nif n <= 1:\n return n\ndp = [0] * n\ndp[0] = 1\nif int(num[:2]) > 25:\n dp[1] = 1\nelse:\n dp[1] = 2\nfor i in range(2, n):\n if int(num[i - 1:i + 1]) <= 25 and int(num[i - 1]) != 0:\n dp[i] = dp[i - 1] + dp[i - 2]\n else:\n dp[i] = dp[i - 1]\nreturn dp[n ... | <|body_start_0|>
num = str(num)
n = len(num)
if n <= 1:
return n
dp = [0] * n
dp[0] = 1
if int(num[:2]) > 25:
dp[1] = 1
else:
dp[1] = 2
for i in range(2, n):
if int(num[i - 1:i + 1]) <= 25 and int(num[i - 1])... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def translateNum(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = str(num)
n = len(num)
if n <= 1:
... | stack_v2_sparse_classes_36k_train_009793 | 1,620 | no_license | [
{
"docstring": ":type num: int :rtype: int",
"name": "translateNum0",
"signature": "def translateNum0(self, num)"
},
{
"docstring": ":type num: int :rtype: int",
"name": "translateNum",
"signature": "def translateNum(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019091 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def translateNum0(self, num): :type num: int :rtype: int
- def translateNum(self, num): :type num: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def translateNum0(self, num): :type num: int :rtype: int
- def translateNum(self, num): :type num: int :rtype: int
<|skeleton|>
class Solution:
def translateNum0(self, num)... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def translateNum(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
num = str(num)
n = len(num)
if n <= 1:
return n
dp = [0] * n
dp[0] = 1
if int(num[:2]) > 25:
dp[1] = 1
else:
dp[1] = 2
for i in r... | the_stack_v2_python_sparse | 剑指 Offer 46. 把数字翻译成字符串.py | yangyuxiang1996/leetcode | train | 0 | |
3873f1d51d531597781ee96be4bd04838f03b659 | [
"self.tragaperras = [['╔══', '═══', '══╗'], ['║ ', 'T_P', ' ║'], ['╚══', '═══', '══╝']]\nself.baccarat = [['╔══', '═══', '═══', '══╗'], ['║ B', 'ACC', 'ARA', 'T ║'], ['╚══', '═══', '═══', '══╝']]\nself.dados = [['╔══', '═══', '══╗'], ['║ ', 'DA2', ' ║'], ['╚══', '═══', '══╝']]\nself.ruleta = [['╔══', '═══', '══... | <|body_start_0|>
self.tragaperras = [['╔══', '═══', '══╗'], ['║ ', 'T_P', ' ║'], ['╚══', '═══', '══╝']]
self.baccarat = [['╔══', '═══', '═══', '══╗'], ['║ B', 'ACC', 'ARA', 'T ║'], ['╚══', '═══', '═══', '══╝']]
self.dados = [['╔══', '═══', '══╗'], ['║ ', 'DA2', ' ║'], ['╚══', '═══', '══╝']]
... | O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR | objetos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class objetos:
"""O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR"""
def __init__(self):
"""En el constructor de este objeto tenemos la lista de listas que pr... | stack_v2_sparse_classes_36k_train_009794 | 35,890 | no_license | [
{
"docstring": "En el constructor de este objeto tenemos la lista de listas que printeara cada maquina en el -mapa- Tambien tenemos",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Este metodo se utiliza para exportar las listas de las maquinas que crea el constructor ,... | 2 | stack_v2_sparse_classes_30k_train_014268 | Implement the Python class `objetos` described below.
Class description:
O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR
Method signatures and docstrings:
- def __init__(self): En el con... | Implement the Python class `objetos` described below.
Class description:
O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR
Method signatures and docstrings:
- def __init__(self): En el con... | e7649910ea6d71c7f62b659d4ca535e14ea1e554 | <|skeleton|>
class objetos:
"""O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR"""
def __init__(self):
"""En el constructor de este objeto tenemos la lista de listas que pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class objetos:
"""O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O CONSTRUCTOR"""
def __init__(self):
"""En el constructor de este objeto tenemos la lista de listas que printeara cada ... | the_stack_v2_python_sparse | Juanca/Tycoon/clases_tycoon.py | Casino-Pythoniani/Casino | train | 0 |
73518cb01ee0bc33dcf8578a349d5b6411a1ba4c | [
"if application_namespace:\n return '{}:detail'.format(application_namespace)\nelse:\n return '{}:detail'.format(self._meta.app_label)",
"from django.urls import reverse\nif not language:\n language = get_current_language() or get_default_language()\nslug, language = self.known_translation_getter('slug',... | <|body_start_0|>
if application_namespace:
return '{}:detail'.format(application_namespace)
else:
return '{}:detail'.format(self._meta.app_label)
<|end_body_0|>
<|body_start_1|>
from django.urls import reverse
if not language:
language = get_current_l... | Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin | AllinkDetailMixin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllinkDetailMixin:
"""Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin"""
def get_detail_view(self, application_namespace=None):
""":param application_namespace: an application_namespace, e.g 'news' - this is u... | stack_v2_sparse_classes_36k_train_009795 | 11,084 | permissive | [
{
"docstring": ":param application_namespace: an application_namespace, e.g 'news' - this is usually supplied, when calling from a app_content plugin with a specific apphook :return: fully qualified detail view identifier, e.g 'news:detail'",
"name": "get_detail_view",
"signature": "def get_detail_view(... | 2 | null | Implement the Python class `AllinkDetailMixin` described below.
Class description:
Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin
Method signatures and docstrings:
- def get_detail_view(self, application_namespace=None): :param application_na... | Implement the Python class `AllinkDetailMixin` described below.
Class description:
Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin
Method signatures and docstrings:
- def get_detail_view(self, application_namespace=None): :param application_na... | 710ad306ebf681dadcbb58a5d36321025a33c2dc | <|skeleton|>
class AllinkDetailMixin:
"""Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin"""
def get_detail_view(self, application_namespace=None):
""":param application_namespace: an application_namespace, e.g 'news' - this is u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllinkDetailMixin:
"""Mixin for models with detail view - always used in combination with aldryn_translation_tools.models.TranslationHelperMixin"""
def get_detail_view(self, application_namespace=None):
""":param application_namespace: an application_namespace, e.g 'news' - this is usually suppli... | the_stack_v2_python_sparse | allink_core/core/models/mixins.py | allink/allink-core | train | 7 |
337e71895257bd1b1d22287bfd661960cd2effcb | [
"if root == None:\n return ''\nq = queue.Queue()\nl = []\nl.append(str(root.val))\nq.put(root.left)\nq.put(root.right)\nwhile not q.empty():\n n = q.get()\n if n == None:\n l.append('_')\n continue\n l.append(str(n.val))\n q.put(n.left)\n q.put(n.right)\nreturn ' '.join(l)",
"if da... | <|body_start_0|>
if root == None:
return ''
q = queue.Queue()
l = []
l.append(str(root.val))
q.put(root.left)
q.put(root.right)
while not q.empty():
n = q.get()
if n == None:
l.append('_')
continu... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_009796 | 1,818 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 35c88dc747e7afa4fdd51d538bc80c4712eb1172 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
q = queue.Queue()
l = []
l.append(str(root.val))
q.put(root.left)
q.put(root.right)
while not q.emp... | the_stack_v2_python_sparse | leetcode/300/297_serialize_deserialize_bintree_slow.py | andysitu/algo-problems | train | 0 | |
62fc32750d76a972ec4b871be9557336c8e3c0c3 | [
"self.authentication_error_message = authentication_error_message\nself.authentication_status = authentication_status\nself.environment = environment\nself.host_settings_check_results = host_settings_check_results\nself.refresh_error_message = refresh_error_message",
"if dictionary is None:\n return None\nauth... | <|body_start_0|>
self.authentication_error_message = authentication_error_message
self.authentication_status = authentication_status
self.environment = environment
self.host_settings_check_results = host_settings_check_results
self.refresh_error_message = refresh_error_message
<|... | Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the registration of the application is not successful. authentication_status (Authentica... | RegisteredAppInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisteredAppInfo:
"""Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the registration of the application is not ... | stack_v2_sparse_classes_36k_train_009797 | 7,517 | permissive | [
{
"docstring": "Constructor for the RegisteredAppInfo class",
"name": "__init__",
"signature": "def __init__(self, authentication_error_message=None, authentication_status=None, environment=None, host_settings_check_results=None, refresh_error_message=None)"
},
{
"docstring": "Creates an instanc... | 2 | stack_v2_sparse_classes_30k_train_003335 | Implement the Python class `RegisteredAppInfo` described below.
Class description:
Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the ... | Implement the Python class `RegisteredAppInfo` described below.
Class description:
Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the ... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class RegisteredAppInfo:
"""Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the registration of the application is not ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisteredAppInfo:
"""Implementation of the 'RegisteredAppInfo' model. TODO: type model description here. Attributes: authentication_error_message (string): Specifies an authentication error message. This indicates the given credentials are rejected and the registration of the application is not successful. a... | the_stack_v2_python_sparse | cohesity_management_sdk/models/registered_app_info.py | hsantoyo2/management-sdk-python | train | 0 |
633d8f3244543bb65f6a10999e6bff4183f15520 | [
"t0_t1 = (0, 2.5)\ny0 = [0.99, 0.01, 0]\nobp = ode_hessian.ODEBackpropProblem(dim_y=3, tf_dy_dt=_tf_sir_dy_dt, tf_L_y0y1=_tf_sir_loss)\ndp_backprop = obp.dp_backprop(y0, t0_t1, odeint_kwargs=dict(rtol=1e-12, atol=1e-12), include_hessian_d2ydot_dy2_term=True)\ny1_via_dp, loss_via_dp, grad_via_dp, hessian_via_dp = dp... | <|body_start_0|>
t0_t1 = (0, 2.5)
y0 = [0.99, 0.01, 0]
obp = ode_hessian.ODEBackpropProblem(dim_y=3, tf_dy_dt=_tf_sir_dy_dt, tf_L_y0y1=_tf_sir_loss)
dp_backprop = obp.dp_backprop(y0, t0_t1, odeint_kwargs=dict(rtol=1e-12, atol=1e-12), include_hessian_d2ydot_dy2_term=True)
y1_via_d... | Basic tests for ODEBackpropProblem differential programming. | DifferentialProgrammingTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
<|body_0|>
def test_obp_dp_d2ydot_dy2(self):
"""Shows that ODEBackpro... | stack_v2_sparse_classes_36k_train_009798 | 9,913 | permissive | [
{
"docstring": "Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().",
"name": "test_obp_dp",
"signature": "def test_obp_dp(self)"
},
{
"docstring": "Shows that ODEBackpropProblem.dp_backprop() needs the s_i F_i,kl term.",
"name": "test_obp_dp_d2ydot_dy2",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_013540 | Implement the Python class `DifferentialProgrammingTest` described below.
Class description:
Basic tests for ODEBackpropProblem differential programming.
Method signatures and docstrings:
- def test_obp_dp(self): Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().
- def test_obp_dp_d2ydot_dy2(self): ... | Implement the Python class `DifferentialProgrammingTest` described below.
Class description:
Basic tests for ODEBackpropProblem differential programming.
Method signatures and docstrings:
- def test_obp_dp(self): Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop().
- def test_obp_dp_d2ydot_dy2(self): ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
<|body_0|>
def test_obp_dp_d2ydot_dy2(self):
"""Shows that ODEBackpro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DifferentialProgrammingTest:
"""Basic tests for ODEBackpropProblem differential programming."""
def test_obp_dp(self):
"""Tests that ODEBackpropProblem.dp_backprop() agrees with .backprop()."""
t0_t1 = (0, 2.5)
y0 = [0.99, 0.01, 0]
obp = ode_hessian.ODEBackpropProblem(dim_... | the_stack_v2_python_sparse | m_theory/m_theory_lib/ode/ode_hessian_test.py | Jimmy-INL/google-research | train | 1 |
6f7df5c9b484cd3ae428083c4ec33156fa4b85db | [
"self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]\nself.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\nreturn (self.input_arr, self.output)",
"input_arr, output_arr = self.setUp()\noutput = zigzagTraverse(input_arr)\nself.assertEqual(output, output_arr)"
] | <|body_start_0|>
self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]
self.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
return (self.input_arr, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, output_arr = self.setUp()
outpu... | Class with unittests for ZigzagTraverse.py | test_ZigzagTraverse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_36k_train_009799 | 1,088 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_ZigzagTraverse` described below.
Class description:
Class with unittests for ZigzagTraverse.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_ZigzagTraverse` described below.
Class description:
Class with unittests for ZigzagTraverse.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_ZigzagTraverse:
""... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_ZigzagTraverse:
"""Class with unittests for ZigzagTraverse.py"""
def setUp(self):
"""Sets up input."""
self.input_arr = [[1, 3, 4, 10], [2, 5, 9, 11], [6, 8, 12, 15], [7, 13, 14, 16]]
self.output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
return (self.i... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Hard/ZigzagTraverse/test_ZigzagTraverse.py | JakubKazimierski/PythonPortfolio | train | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.