blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2c8a7388339745243238b4d5af28053188297fae | [
"OCRequest.__init__(self)\nself.host_ip = os_pub_ip\nself.tenant_id = tenant_id\nself.tenant_token = tenant_token",
"_url = 'http://' + self.host_ip + ':8004/v1/' + self.tenant_id + '/stacks'\n_headers = {'Content-type': 'application/json', 'x-auth-token': self.tenant_token}\n_body = None\nresponse = self.request... | <|body_start_0|>
OCRequest.__init__(self)
self.host_ip = os_pub_ip
self.tenant_id = tenant_id
self.tenant_token = tenant_token
<|end_body_0|>
<|body_start_1|>
_url = 'http://' + self.host_ip + ':8004/v1/' + self.tenant_id + '/stacks'
_headers = {'Content-type': 'applicat... | This class contains basic operation on stack like stack list, show, stack resource list, etc. | HeatLibrary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
<|body_0|>
def stack_list(self):
"""To get t... | stack_v2_sparse_classes_75kplus_train_001500 | 6,881 | no_license | [
{
"docstring": "It requires the ID and token of the tenant.",
"name": "__init__",
"signature": "def __init__(self, os_pub_ip, tenant_id, tenant_token)"
},
{
"docstring": "To get the list of created stacks. Return: List of all stacks created in the tenant.",
"name": "stack_list",
"signatu... | 6 | stack_v2_sparse_classes_30k_train_019876 | Implement the Python class `HeatLibrary` described below.
Class description:
This class contains basic operation on stack like stack list, show, stack resource list, etc.
Method signatures and docstrings:
- def __init__(self, os_pub_ip, tenant_id, tenant_token): It requires the ID and token of the tenant.
- def stack... | Implement the Python class `HeatLibrary` described below.
Class description:
This class contains basic operation on stack like stack list, show, stack resource list, etc.
Method signatures and docstrings:
- def __init__(self, os_pub_ip, tenant_id, tenant_token): It requires the ID and token of the tenant.
- def stack... | cd5f98de9b82ffeb267e9f2e1fd9c84a3c24d7bf | <|skeleton|>
class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
<|body_0|>
def stack_list(self):
"""To get t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
OCRequest.__init__(self)
self.host_ip = os_pub_ip
self... | the_stack_v2_python_sparse | merge-master-fw-norule/ATF/atf/lib/lib_heat.py | deekshithpatnala/nsd_atf | train | 0 |
1e7c09fbab53137d472dc26fb752c5fe458a4540 | [
"BaseResource.__init__(self, *args, **kw)\nself._rsc = eval(open('%s.txt' % self.basesourcefile, 'r').read().replace('\\r\\n', '\\n'))\nself._code = open('%s.py' % self.basesourcefile, 'r').read()",
"fle = open(os.path.join(basedir, self.name) + '.rsrc.py', 'w')\nlog.info(\"Writing '%s'\" % os.path.join(basedir, ... | <|body_start_0|>
BaseResource.__init__(self, *args, **kw)
self._rsc = eval(open('%s.txt' % self.basesourcefile, 'r').read().replace('\r\n', '\n'))
self._code = open('%s.py' % self.basesourcefile, 'r').read()
<|end_body_0|>
<|body_start_1|>
fle = open(os.path.join(basedir, self.name) + '... | Represents a Python Card resource object | Resource | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""Represents a Python Card resource object"""
def __init__(self, *args, **kw):
"""Initialize the PythonCard resource"""
<|body_0|>
def writeToFile(self, basedir, write_code=0):
"""Write ourselves out to a directory"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_001501 | 2,155 | permissive | [
{
"docstring": "Initialize the PythonCard resource",
"name": "__init__",
"signature": "def __init__(self, *args, **kw)"
},
{
"docstring": "Write ourselves out to a directory",
"name": "writeToFile",
"signature": "def writeToFile(self, basedir, write_code=0)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034496 | Implement the Python class `Resource` described below.
Class description:
Represents a Python Card resource object
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialize the PythonCard resource
- def writeToFile(self, basedir, write_code=0): Write ourselves out to a directory | Implement the Python class `Resource` described below.
Class description:
Represents a Python Card resource object
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialize the PythonCard resource
- def writeToFile(self, basedir, write_code=0): Write ourselves out to a directory
<|skeleton|>
cl... | 847ce71e85093ea5ee668ec61dbfba760ffa6bbd | <|skeleton|>
class Resource:
"""Represents a Python Card resource object"""
def __init__(self, *args, **kw):
"""Initialize the PythonCard resource"""
<|body_0|>
def writeToFile(self, basedir, write_code=0):
"""Write ourselves out to a directory"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
"""Represents a Python Card resource object"""
def __init__(self, *args, **kw):
"""Initialize the PythonCard resource"""
BaseResource.__init__(self, *args, **kw)
self._rsc = eval(open('%s.txt' % self.basesourcefile, 'r').read().replace('\r\n', '\n'))
self._code =... | the_stack_v2_python_sparse | vb2py/targets/pythoncard/resource.py | rayzamgh/sumurProjection | train | 1 |
1a1b4036aa581d87abc3673229fef35287eeef37 | [
"tfrecord_cache_files = dataset_util.get_cache_files_coco(data_dir, cache_dir)\nif not tfrecord_cache_files.is_cached():\n label_map = dataset_util.get_label_map_coco(data_dir)\n cache_writer = dataset_util.COCOCacheFilesWriter(label_map=label_map, max_num_images=max_num_images)\n cache_writer.write_files(... | <|body_start_0|>
tfrecord_cache_files = dataset_util.get_cache_files_coco(data_dir, cache_dir)
if not tfrecord_cache_files.is_cached():
label_map = dataset_util.get_label_map_coco(data_dir)
cache_writer = dataset_util.COCOCacheFilesWriter(label_map=label_map, max_num_images=max_n... | Dataset library for object detector. | Dataset | [
"Apache-2.0",
"dtoa"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Dataset library for object detector."""
def from_coco_folder(cls, data_dir: str, max_num_images: Optional[int]=None, cache_dir: Optional[str]=None) -> 'Dataset':
"""Loads images and labels from the given directory in COCO format. - https://cocodataset.org/#home Folder str... | stack_v2_sparse_classes_75kplus_train_001502 | 6,432 | permissive | [
{
"docstring": "Loads images and labels from the given directory in COCO format. - https://cocodataset.org/#home Folder structure should be: <data_dir>/ images/ <file0>.jpg ... labels.json The `labels.json` annotations file should should have the following format: { \"categories\": [{\"id\": 0, \"name\": \"back... | 3 | stack_v2_sparse_classes_30k_train_006043 | Implement the Python class `Dataset` described below.
Class description:
Dataset library for object detector.
Method signatures and docstrings:
- def from_coco_folder(cls, data_dir: str, max_num_images: Optional[int]=None, cache_dir: Optional[str]=None) -> 'Dataset': Loads images and labels from the given directory i... | Implement the Python class `Dataset` described below.
Class description:
Dataset library for object detector.
Method signatures and docstrings:
- def from_coco_folder(cls, data_dir: str, max_num_images: Optional[int]=None, cache_dir: Optional[str]=None) -> 'Dataset': Loads images and labels from the given directory i... | 007824594bf1d07c7c1467df03a43886f8a4b3ad | <|skeleton|>
class Dataset:
"""Dataset library for object detector."""
def from_coco_folder(cls, data_dir: str, max_num_images: Optional[int]=None, cache_dir: Optional[str]=None) -> 'Dataset':
"""Loads images and labels from the given directory in COCO format. - https://cocodataset.org/#home Folder str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
"""Dataset library for object detector."""
def from_coco_folder(cls, data_dir: str, max_num_images: Optional[int]=None, cache_dir: Optional[str]=None) -> 'Dataset':
"""Loads images and labels from the given directory in COCO format. - https://cocodataset.org/#home Folder structure should... | the_stack_v2_python_sparse | mediapipe/model_maker/python/vision/object_detector/dataset.py | google/mediapipe | train | 23,940 |
39ca9ce0e74aaddfe5b6ff9f8d6b85641d882ce7 | [
"if not elemental_features:\n elemental_features = [preset.e_coh, preset.G, preset.a0, preset.ar, preset.mean_delta_bl, preset.mean_bl]\nif not structural_features:\n structural_features = [preset.d_gb, preset.d_rot, preset.sin_theta, preset.cos_theta]\nself.elem_features = elemental_features\nself.struc_feat... | <|body_start_0|>
if not elemental_features:
elemental_features = [preset.e_coh, preset.G, preset.a0, preset.ar, preset.mean_delta_bl, preset.mean_bl]
if not structural_features:
structural_features = [preset.d_gb, preset.d_rot, preset.sin_theta, preset.cos_theta]
self.ele... | The describers that describes the grain boundary db entry with selected structural and elemental features. | GBDescriber | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBDescriber:
"""The describers that describes the grain boundary db entry with selected structural and elemental features."""
def __init__(self, structural_features: list | None=None, elemental_features: list | None=None, **kwargs):
"""Args: structural_features (list): list of struct... | stack_v2_sparse_classes_75kplus_train_001503 | 14,714 | permissive | [
{
"docstring": "Args: structural_features (list): list of structural features elemental_features (list): list of elemental features **kwargs (dict): parameters for BaseDescriber.",
"name": "__init__",
"signature": "def __init__(self, structural_features: list | None=None, elemental_features: list | None... | 3 | stack_v2_sparse_classes_30k_train_004325 | Implement the Python class `GBDescriber` described below.
Class description:
The describers that describes the grain boundary db entry with selected structural and elemental features.
Method signatures and docstrings:
- def __init__(self, structural_features: list | None=None, elemental_features: list | None=None, **... | Implement the Python class `GBDescriber` described below.
Class description:
The describers that describes the grain boundary db entry with selected structural and elemental features.
Method signatures and docstrings:
- def __init__(self, structural_features: list | None=None, elemental_features: list | None=None, **... | 6ae3c7029b939e1183684358a3ae2fef41053be5 | <|skeleton|>
class GBDescriber:
"""The describers that describes the grain boundary db entry with selected structural and elemental features."""
def __init__(self, structural_features: list | None=None, elemental_features: list | None=None, **kwargs):
"""Args: structural_features (list): list of struct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GBDescriber:
"""The describers that describes the grain boundary db entry with selected structural and elemental features."""
def __init__(self, structural_features: list | None=None, elemental_features: list | None=None, **kwargs):
"""Args: structural_features (list): list of structural features... | the_stack_v2_python_sparse | maml/apps/gbe/describer.py | materialsvirtuallab/maml | train | 266 |
109c73f67e8bdf304c8c847e55ba47b815b50fad | [
"if len(self.args) < 2:\n raise ValueError('OrdRule needs TWO arguments at least')\nif self.args[0].__class__.__name__ != 'RuleRangeArg':\n print(self.args[0])\n raise ValueError('The first argument of OrdRule must be RuleRangeArg')\nfor index, arg in enumerate(self.args[1:]):\n arg_name = arg.__class__... | <|body_start_0|>
if len(self.args) < 2:
raise ValueError('OrdRule needs TWO arguments at least')
if self.args[0].__class__.__name__ != 'RuleRangeArg':
print(self.args[0])
raise ValueError('The first argument of OrdRule must be RuleRangeArg')
for index, arg in ... | 有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠 | OrdRule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrdRule:
"""有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠"""
def validate(self):
"""参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1) 关键词 (KeywordArg) 2) 概念 (ConceptArg) 3) 规则 (ArgRule, Bag... | stack_v2_sparse_classes_75kplus_train_001504 | 4,472 | permissive | [
{
"docstring": "参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1) 关键词 (KeywordArg) 2) 概念 (ConceptArg) 3) 规则 (ArgRule, BagRule, OrRule, OrdRule, SeqRule) 4) 规则过滤器 (RuleFilter)",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "递归来组合结果. ... | 3 | null | Implement the Python class `OrdRule` described below.
Class description:
有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠
Method signatures and docstrings:
- def validate(self): 参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1... | Implement the Python class `OrdRule` described below.
Class description:
有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠
Method signatures and docstrings:
- def validate(self): 参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1... | e60de7b4457efd5a85165e89a4477c14f52c471b | <|skeleton|>
class OrdRule:
"""有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠"""
def validate(self):
"""参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1) 关键词 (KeywordArg) 2) 概念 (ConceptArg) 3) 规则 (ArgRule, Bag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrdRule:
"""有序不连续规则, 包括2个特性: 1. 有序. 是指规则中的参数前后顺序是敏感的 2. 不连续. 是指规则参数不需要紧密连续, 中间可以出现若干其他无关词条 3. 不重叠. 匹配的元素和元素之间不能出现重叠"""
def validate(self):
"""参数的合法性检验, 不合法抛出异常. 1. 参数至少要 2 个 2. 第 1 个参数必须是规则范围 (RuleRangeArg) 3. 第 2 个及以后的参数可以是: 1) 关键词 (KeywordArg) 2) 概念 (ConceptArg) 3) 规则 (ArgRule, BagRule, OrRule,... | the_stack_v2_python_sparse | lre/rule/ord_rule.py | ovixiao/lre | train | 0 |
6cdee17592c047d2631f19480d6eb5153e012823 | [
"super(MultiLayerPerceptron, self).__init__()\nself.W1 = tf.layers.Dense(units=mlp_size, use_bias=True, name='W1', activation=tf.nn.relu)\nself.project = tf.layers.Dense(units=out_size, use_bias=True, name='pre_softmax')\nself.train = train\nself.dropout = dropout",
"pre_out = self.W1(inputs)\nif self.train:\n ... | <|body_start_0|>
super(MultiLayerPerceptron, self).__init__()
self.W1 = tf.layers.Dense(units=mlp_size, use_bias=True, name='W1', activation=tf.nn.relu)
self.project = tf.layers.Dense(units=out_size, use_bias=True, name='pre_softmax')
self.train = train
self.dropout = dropout
<|e... | Classification layer with bottleneck relu layer. | MultiLayerPerceptron | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLayerPerceptron:
"""Classification layer with bottleneck relu layer."""
def __init__(self, mlp_size, out_size, dropout, train):
"""Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : number of classes dropout (float) : dropout rate train (bo... | stack_v2_sparse_classes_75kplus_train_001505 | 7,981 | no_license | [
{
"docstring": "Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : number of classes dropout (float) : dropout rate train (bool) : model is in training phase",
"name": "__init__",
"signature": "def __init__(self, mlp_size, out_size, dropout, train)"
},
{
"d... | 2 | null | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Classification layer with bottleneck relu layer.
Method signatures and docstrings:
- def __init__(self, mlp_size, out_size, dropout, train): Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : n... | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Classification layer with bottleneck relu layer.
Method signatures and docstrings:
- def __init__(self, mlp_size, out_size, dropout, train): Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : n... | 8e65b814b87fb5f237291612364c9774de258e8b | <|skeleton|>
class MultiLayerPerceptron:
"""Classification layer with bottleneck relu layer."""
def __init__(self, mlp_size, out_size, dropout, train):
"""Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : number of classes dropout (float) : dropout rate train (bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLayerPerceptron:
"""Classification layer with bottleneck relu layer."""
def __init__(self, mlp_size, out_size, dropout, train):
"""Instantiate layer. Args: mlp_size (int) : dimension for bottleneck layer out_size (int) : number of classes dropout (float) : dropout rate train (bool) : model i... | the_stack_v2_python_sparse | models/leam.py | julian-risch/JCDL2020 | train | 3 |
643a9d11f5dc0ae1fb93dced0a289dbdd3aa9942 | [
"super().__init__(name=name)\nself._depth = depth\nself._num_layers = 2\nself._kernel_shapes = [kernel_shape] * 2\nself._strides = [stride, 1]\nself._padding = snt.SAME\nself._activation = activation\nself._extra_params = extra_params\nself._downsample_input = False\nif stride != 1:\n self._downsample_input = Tr... | <|body_start_0|>
super().__init__(name=name)
self._depth = depth
self._num_layers = 2
self._kernel_shapes = [kernel_shape] * 2
self._strides = [stride, 1]
self._padding = snt.SAME
self._activation = activation
self._extra_params = extra_params
self... | ResUnit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resunit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, use_weight_norm=False, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the str... | stack_v2_sparse_classes_75kplus_train_001506 | 3,128 | permissive | [
{
"docstring": "Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf function): activation used for the internal layers. **extra_params: all the additional keyword arguments will be passed to snt.Conv2D lay... | 2 | null | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resunit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, use_weight_norm=False, **extra_params): Args: depth (int): the depth of the resUnit.... | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resunit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, use_weight_norm=False, **extra_params): Args: depth (int): the depth of the resUnit.... | a10c33346803239db8a64c104db7f22ec4e05bef | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resunit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, use_weight_norm=False, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResUnit:
def __init__(self, depth, name='resunit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, use_weight_norm=False, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation... | the_stack_v2_python_sparse | argo/core/network/ResUnit.py | ricvo/argo | train | 0 | |
ac71f931bc9652d38471ea8358004b698e9077bb | [
"if values is None:\n values = {}\nfor band in self.BANDS:\n if band not in values.keys():\n values[band] = []\nsuper().__init__(values)",
"if new_dict is None:\n return\nfor band in self.BANDS:\n if band not in new_dict.keys() or not new_dict[band]:\n continue\n if not self[band]:\n ... | <|body_start_0|>
if values is None:
values = {}
for band in self.BANDS:
if band not in values.keys():
values[band] = []
super().__init__(values)
<|end_body_0|>
<|body_start_1|>
if new_dict is None:
return
for band in self.BANDS... | Value class which contains values of single day over all supported bands. | Value | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Value:
"""Value class which contains values of single day over all supported bands."""
def __init__(self, values: Optional[Dict[str, Any]]=None) -> None:
"""Initialise the value class."""
<|body_0|>
def update(self, new_dict: Optional[Dict[str, Any]]=None, **F: Any) -> N... | stack_v2_sparse_classes_75kplus_train_001507 | 3,010 | no_license | [
{
"docstring": "Initialise the value class.",
"name": "__init__",
"signature": "def __init__(self, values: Optional[Dict[str, Any]]=None) -> None"
},
{
"docstring": "D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: ... | 2 | null | Implement the Python class `Value` described below.
Class description:
Value class which contains values of single day over all supported bands.
Method signatures and docstrings:
- def __init__(self, values: Optional[Dict[str, Any]]=None) -> None: Initialise the value class.
- def update(self, new_dict: Optional[Dict... | Implement the Python class `Value` described below.
Class description:
Value class which contains values of single day over all supported bands.
Method signatures and docstrings:
- def __init__(self, values: Optional[Dict[str, Any]]=None) -> None: Initialise the value class.
- def update(self, new_dict: Optional[Dict... | baa21e5d44fb323b28940c94a7dc93271338825f | <|skeleton|>
class Value:
"""Value class which contains values of single day over all supported bands."""
def __init__(self, values: Optional[Dict[str, Any]]=None) -> None:
"""Initialise the value class."""
<|body_0|>
def update(self, new_dict: Optional[Dict[str, Any]]=None, **F: Any) -> N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Value:
"""Value class which contains values of single day over all supported bands."""
def __init__(self, values: Optional[Dict[str, Any]]=None) -> None:
"""Initialise the value class."""
if values is None:
values = {}
for band in self.BANDS:
if band not in... | the_stack_v2_python_sparse | src/radix_co2_reduction/data/dictionary.py | shawnxiao-yara/radix-co2-reduction | train | 0 |
4c6855354357693bd544c2cd985aa4c3c795fd87 | [
"resp = requests.get(verify_url.format('json', '', cred[1], 'TestApp', test_number))\nassert resp.status_code == 200\nassert resp.headers['Content-Type'] == 'application/json'\nassert resp.json()['status'] == '2'\nassert resp.json()['error_text'] == missing_apikey_msg\nresp = requests.get(verify_url_without_apikey.... | <|body_start_0|>
resp = requests.get(verify_url.format('json', '', cred[1], 'TestApp', test_number))
assert resp.status_code == 200
assert resp.headers['Content-Type'] == 'application/json'
assert resp.json()['status'] == '2'
assert resp.json()['error_text'] == missing_apikey_msg... | This class contains only JSON format API testcases. | TestVerifyApiAuthJson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVerifyApiAuthJson:
"""This class contains only JSON format API testcases."""
def test_empty_apikey(self, cred):
"""Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each request should fail with status code 2."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001508 | 3,370 | no_license | [
{
"docstring": "Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each request should fail with status code 2.",
"name": "test_empty_apikey",
"signature": "def test_empty_apikey(self, cred)"
},
{
"docstring": "Test Verify Request with empty api_sec... | 4 | stack_v2_sparse_classes_30k_train_045730 | Implement the Python class `TestVerifyApiAuthJson` described below.
Class description:
This class contains only JSON format API testcases.
Method signatures and docstrings:
- def test_empty_apikey(self, cred): Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each reque... | Implement the Python class `TestVerifyApiAuthJson` described below.
Class description:
This class contains only JSON format API testcases.
Method signatures and docstrings:
- def test_empty_apikey(self, cred): Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each reque... | a51f99c9595cf3b7910a262006a6584f4929eb70 | <|skeleton|>
class TestVerifyApiAuthJson:
"""This class contains only JSON format API testcases."""
def test_empty_apikey(self, cred):
"""Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each request should fail with status code 2."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestVerifyApiAuthJson:
"""This class contains only JSON format API testcases."""
def test_empty_apikey(self, cred):
"""Test Verify Request with empty api_key value and without api_key parm in the query string at all. Each request should fail with status code 2."""
resp = requests.get(veri... | the_stack_v2_python_sparse | nexmo_verify_api_auth_testing.py | alx-fokin/api-testing-example | train | 0 |
7e2642811b17392adf07f375f495fd57aeb24639 | [
"super().__init__()\nself.name: str = name\nself.params: dict = data",
"if self.params == {}:\n return {self.name: None}\nreturn {self.name: self.params}"
] | <|body_start_0|>
super().__init__()
self.name: str = name
self.params: dict = data
<|end_body_0|>
<|body_start_1|>
if self.params == {}:
return {self.name: None}
return {self.name: self.params}
<|end_body_1|>
| Configuration Dataset class. | Dataset | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
<|body_0|>
def serialize(self, serialization_type: str='default') -> Dict[str, Any]:
"""Serialize Dataset cla... | stack_v2_sparse_classes_75kplus_train_001509 | 4,560 | permissive | [
{
"docstring": "Initialize Configuration Dataset class.",
"name": "__init__",
"signature": "def __init__(self, name: str, data: Dict[str, Any]={}) -> None"
},
{
"docstring": "Serialize Dataset class.",
"name": "serialize",
"signature": "def serialize(self, serialization_type: str='defaul... | 2 | stack_v2_sparse_classes_30k_train_004391 | Implement the Python class `Dataset` described below.
Class description:
Configuration Dataset class.
Method signatures and docstrings:
- def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class.
- def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ... | Implement the Python class `Dataset` described below.
Class description:
Configuration Dataset class.
Method signatures and docstrings:
- def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class.
- def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
<|body_0|>
def serialize(self, serialization_type: str='default') -> Dict[str, Any]:
"""Serialize Dataset cla... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
"""Configuration Dataset class."""
def __init__(self, name: str, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataset class."""
super().__init__()
self.name: str = name
self.params: dict = data
def serialize(self, serialization_type: str='def... | the_stack_v2_python_sparse | neural_compressor/ux/utils/workload/dataloader.py | Skp80/neural-compressor | train | 0 |
abf103845299e7eb8edd6df81b7b2244f466e5d9 | [
"tf.reset_default_graph()\noptim = tf.train.GradientDescentOptimizer(0.001)\nglobal_step = tf.train.get_or_create_global_step()\nsparse_optim = sparse_optimizers.SparseRigLOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac)\nx = tf.ones((1, n_inp))\ny = layers.masked_fully_connected(x, n_out,... | <|body_start_0|>
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.001)
global_step = tf.train.get_or_create_global_step()
sparse_optim = sparse_optimizers.SparseRigLOptimizer(optim, start_iter, end_iter, freq_iter, drop_fraction=drop_frac)
x = tf.ones((1, n_in... | SparseRigLOptimizerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseRigLOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMaskedGradientCalculation(self, n_inp, n_out):
"""Checking whether maske... | stack_v2_sparse_classes_75kplus_train_001510 | 25,606 | permissive | [
{
"docstring": "Setups a trivial training procedure for sparse training.",
"name": "_setup_graph",
"signature": "def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2)"
},
{
"docstring": "Checking whether masked_grad is calculated after apply_gradients.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_010758 | Implement the Python class `SparseRigLOptimizerTest` described below.
Class description:
Implement the SparseRigLOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2): Setups a trivial training procedure for sparse training.
- d... | Implement the Python class `SparseRigLOptimizerTest` described below.
Class description:
Implement the SparseRigLOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2): Setups a trivial training procedure for sparse training.
- d... | d39fc7d46505cb3196cb1edeb32ed0b6dd44c0f9 | <|skeleton|>
class SparseRigLOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testMaskedGradientCalculation(self, n_inp, n_out):
"""Checking whether maske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseRigLOptimizerTest:
def _setup_graph(self, n_inp, n_out, drop_frac, start_iter=1, end_iter=4, freq_iter=2):
"""Setups a trivial training procedure for sparse training."""
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.001)
global_step = tf.train.get_o... | the_stack_v2_python_sparse | rigl/sparse_optimizers_test.py | google-research/rigl | train | 324 | |
9cf85d447e02c39d246ba74eb7acf10fec829814 | [
"res = ApiResponse()\nscheduleObj = Schedule.objects.get(id=scheduleId)\ncronSchedule = scheduleObj.cronSchedule\nptask = PeriodicTask.objects.update_or_create(name=anomalyDefId, defaults={'crontab': cronSchedule, 'task': anomalyDetectionJob.name, 'args': f'[\"{anomalyDefId}\"]'})\nanomalyDefObj = AnomalyDefinition... | <|body_start_0|>
res = ApiResponse()
scheduleObj = Schedule.objects.get(id=scheduleId)
cronSchedule = scheduleObj.cronSchedule
ptask = PeriodicTask.objects.update_or_create(name=anomalyDefId, defaults={'crontab': cronSchedule, 'task': anomalyDetectionJob.name, 'args': f'["{anomalyDefId}"... | AnomalyDefJobServices | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnomalyDefJobServices:
def addAnomalyDefJob(anomalyDefId: str, scheduleId: int):
"""Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to create job :param scheduleId: ID of schedule"""
<|body_0|>
def deleteAnomalyDefJob(anomalyDefId: int)... | stack_v2_sparse_classes_75kplus_train_001511 | 9,645 | permissive | [
{
"docstring": "Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to create job :param scheduleId: ID of schedule",
"name": "addAnomalyDefJob",
"signature": "def addAnomalyDefJob(anomalyDefId: str, scheduleId: int)"
},
{
"docstring": "Service to update cronta... | 2 | stack_v2_sparse_classes_30k_train_000488 | Implement the Python class `AnomalyDefJobServices` described below.
Class description:
Implement the AnomalyDefJobServices class.
Method signatures and docstrings:
- def addAnomalyDefJob(anomalyDefId: str, scheduleId: int): Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to crea... | Implement the Python class `AnomalyDefJobServices` described below.
Class description:
Implement the AnomalyDefJobServices class.
Method signatures and docstrings:
- def addAnomalyDefJob(anomalyDefId: str, scheduleId: int): Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to crea... | 4c10cd804d6ca31a21d14d65670fa4c6b9a5d011 | <|skeleton|>
class AnomalyDefJobServices:
def addAnomalyDefJob(anomalyDefId: str, scheduleId: int):
"""Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to create job :param scheduleId: ID of schedule"""
<|body_0|>
def deleteAnomalyDefJob(anomalyDefId: int)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnomalyDefJobServices:
def addAnomalyDefJob(anomalyDefId: str, scheduleId: int):
"""Service to add a new AnomalyDefJob :param anomalyDefId: ID of the AnomalyDef for which to create job :param scheduleId: ID of schedule"""
res = ApiResponse()
scheduleObj = Schedule.objects.get(id=schedu... | the_stack_v2_python_sparse | api/anomaly/services/anomalyDefinitions.py | Slach/CueObserve | train | 0 | |
f53ea2587f2719320761e9f84a99e894305c0324 | [
"self.layout = layout\nself.reader = VolumeReader()\nself.writer = writer",
"layout = argdef(layout, self.layout)\nwriter = _select_writer(x, self.writer, layout + '_')\nx, info = self.reader(x)\naffine = argdef(affine, info.get('affine'))\nif affine is None:\n return writer(x, info=info)\naffine, x = change_l... | <|body_start_0|>
self.layout = layout
self.reader = VolumeReader()
self.writer = writer
<|end_body_0|>
<|body_start_1|>
layout = argdef(layout, self.layout)
writer = _select_writer(x, self.writer, layout + '_')
x, info = self.reader(x)
affine = argdef(affine, inf... | Reorient a volume to match a target layout. | Reorienter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reorienter:
"""Reorient a volume to match a target layout."""
def __init__(self, layout='RAS', writer=None):
"""Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWriter, optional Writer object. Selected based on the input... | stack_v2_sparse_classes_75kplus_train_001512 | 3,613 | permissive | [
{
"docstring": "Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWriter, optional Writer object. Selected based on the input type by default.",
"name": "__init__",
"signature": "def __init__(self, layout='RAS', writer=None)"
},
{
"d... | 2 | null | Implement the Python class `Reorienter` described below.
Class description:
Reorient a volume to match a target layout.
Method signatures and docstrings:
- def __init__(self, layout='RAS', writer=None): Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWr... | Implement the Python class `Reorienter` described below.
Class description:
Reorient a volume to match a target layout.
Method signatures and docstrings:
- def __init__(self, layout='RAS', writer=None): Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWr... | fb3582b0657479d2a493d0c7c397a81215f66857 | <|skeleton|>
class Reorienter:
"""Reorient a volume to match a target layout."""
def __init__(self, layout='RAS', writer=None):
"""Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWriter, optional Writer object. Selected based on the input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reorienter:
"""Reorient a volume to match a target layout."""
def __init__(self, layout='RAS', writer=None):
"""Parameters ---------- layout : str, default='RAS' Name of a layout. See ``affine_layout_matrix``. writer : VolumeWriter, optional Writer object. Selected based on the input type by defa... | the_stack_v2_python_sparse | nntools/space/object.py | balbasty/nntools | train | 0 |
24946af70bd19f4df06148cc31a255e1e471b47b | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_route_map_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_route_map_by_ids(ids)\n only_main_property = True\n obj_model = None\ns... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_route_map_by_id... | RouteMapDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMap."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Upda... | stack_v2_sparse_classes_75kplus_train_001513 | 9,414 | permissive | [
{
"docstring": "Returns a list of RouteMaps by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new RouteMap.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update RouteMap... | 4 | stack_v2_sparse_classes_30k_val_002965 | Implement the Python class `RouteMapDBView` described below.
Class description:
Implement the RouteMapDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMaps by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMap.
- def put(self, ... | Implement the Python class `RouteMapDBView` described below.
Class description:
Implement the RouteMapDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of RouteMaps by ids ou dict.
- def post(self, request, *args, **kwargs): Create new RouteMap.
- def put(self, ... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new RouteMap."""
<|body_1|>
def put(self, request, *args, **kwargs):
"""Upda... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RouteMapDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of RouteMaps by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_route_map_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
... | the_stack_v2_python_sparse | networkapi/api_route_map/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
b097669829826d57218b56d17b47a55831c33581 | [
"self.derivatives = derivatives\nfor param_str in params:\n if not hasattr(self, param_str):\n setattr(self, param_str, self._make_param_function(param_str))\nsuper().__init__(params=params)",
"def param_function(ext, module, g_inp, g_out, bpQuantities):\n \"\"\"Calculates gradient with the help of d... | <|body_start_0|>
self.derivatives = derivatives
for param_str in params:
if not hasattr(self, param_str):
setattr(self, param_str, self._make_param_function(param_str))
super().__init__(params=params)
<|end_body_0|>
<|body_start_1|>
def param_function(ext, mo... | Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface for parameter "param1":: param1(ext, module... | GradBaseModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradBaseModule:
"""Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface f... | stack_v2_sparse_classes_75kplus_train_001514 | 2,424 | permissive | [
{
"docstring": "Initializes all methods. If the param method has already been defined, it is left unchanged. Args: derivatives(backpack.core.derivatives.basederivatives.BaseParameterDerivatives): # noqa: B950 Derivatives object assigned to self.derivatives. params (list[str]): list of strings with parameter nam... | 2 | stack_v2_sparse_classes_30k_train_020917 | Implement the Python class `GradBaseModule` described below.
Class description:
Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external modu... | Implement the Python class `GradBaseModule` described below.
Class description:
Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external modu... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class GradBaseModule:
"""Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradBaseModule:
"""Calculates the gradient. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface for parameter ... | the_stack_v2_python_sparse | backpack/extensions/firstorder/gradient/base.py | f-dangel/backpack | train | 505 |
0fd4ff92e290d8dddf392d0ed55e56290fb149eb | [
"def pre_search(t):\n if not t:\n self.res += '()'\n return\n elif not t.left and (not t.right):\n self.res += '('\n self.res += str(t.val)\n self.res += ')'\n elif not t.left:\n self.res += '('\n self.res += str(t.val)\n self.res += '()'\n if ... | <|body_start_0|>
def pre_search(t):
if not t:
self.res += '()'
return
elif not t.left and (not t.right):
self.res += '('
self.res += str(t.val)
self.res += ')'
elif not t.left:
sel... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def tree2str(self, t):
""":type t: TreeNode :rtype: str"""
<|body_0|>
def tree2str2(self, t):
""":type t: TreeNode :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def pre_search(t):
if not t:
self.re... | stack_v2_sparse_classes_75kplus_train_001515 | 1,490 | no_license | [
{
"docstring": ":type t: TreeNode :rtype: str",
"name": "tree2str",
"signature": "def tree2str(self, t)"
},
{
"docstring": ":type t: TreeNode :rtype: str",
"name": "tree2str2",
"signature": "def tree2str2(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031457 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tree2str(self, t): :type t: TreeNode :rtype: str
- def tree2str2(self, t): :type t: TreeNode :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tree2str(self, t): :type t: TreeNode :rtype: str
- def tree2str2(self, t): :type t: TreeNode :rtype: str
<|skeleton|>
class Solution:
def tree2str(self, t):
"""... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def tree2str(self, t):
""":type t: TreeNode :rtype: str"""
<|body_0|>
def tree2str2(self, t):
""":type t: TreeNode :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def tree2str(self, t):
""":type t: TreeNode :rtype: str"""
def pre_search(t):
if not t:
self.res += '()'
return
elif not t.left and (not t.right):
self.res += '('
self.res += str(t.val)
... | the_stack_v2_python_sparse | tree2str.py | NeilWangziyu/Leetcode_py | train | 2 | |
d52cfbcfe594aba53d7984b5d2186546d83ddf40 | [
"count = maxWidth\nstart = end = 0\nresult = []\nfor word in words:\n length = len(word)\n nSpaces = end - start - 1\n if length + nSpaces + 1 > count:\n average = count / (nSpaces or 1)\n remainder = count - average * (nSpaces or 1)\n string = words[start] + (nSpaces == 0) * average *... | <|body_start_0|>
count = maxWidth
start = end = 0
result = []
for word in words:
length = len(word)
nSpaces = end - start - 1
if length + nSpaces + 1 > count:
average = count / (nSpaces or 1)
remainder = count - average ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_0|>
def fullJustify2(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_001516 | 2,353 | permissive | [
{
"docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]",
"name": "fullJustify",
"signature": "def fullJustify(self, words, maxWidth)"
},
{
"docstring": ":type words: List[str] :type maxWidth: int :rtype: List[str]",
"name": "fullJustify2",
"signature": "def fullJust... | 2 | stack_v2_sparse_classes_30k_train_048673 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str]
- def fullJustify2(self, words, maxWidth): :type words: List[str] :type maxWi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullJustify(self, words, maxWidth): :type words: List[str] :type maxWidth: int :rtype: List[str]
- def fullJustify2(self, words, maxWidth): :type words: List[str] :type maxWi... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_0|>
def fullJustify2(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fullJustify(self, words, maxWidth):
""":type words: List[str] :type maxWidth: int :rtype: List[str]"""
count = maxWidth
start = end = 0
result = []
for word in words:
length = len(word)
nSpaces = end - start - 1
if lengt... | the_stack_v2_python_sparse | 1-100/61-70/68-textJustification/textJustification.py | xuychen/Leetcode | train | 0 | |
a0b2d10e9618fe33fe613467d20fbd98643f536c | [
"self._avg_mag = 0\nself._count = 0\nself._Ips_d = 0\nself._Qps_d = 0\nself._lf_coeff = lf_coeff\nself._costas_mode = costas_mode\nself._freq_mode = freq_mode\nself.costas_err = 0\nself.freq_err = 0\nself.freq_bias = freq_bias\nself.d_lf_out = 0\nself.lf_out = freq_bias\nself._lf = 0\nself._lf_sum = 0\nself._lf_sum... | <|body_start_0|>
self._avg_mag = 0
self._count = 0
self._Ips_d = 0
self._Qps_d = 0
self._lf_coeff = lf_coeff
self._costas_mode = costas_mode
self._freq_mode = freq_mode
self.costas_err = 0
self.freq_err = 0
self.freq_bias = freq_bias
... | Costas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Costas:
def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias):
"""Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ------- Costas object"""
<|body_0|>
def costas_detector(self, Ips, Qps, mode):
... | stack_v2_sparse_classes_75kplus_train_001517 | 5,884 | no_license | [
{
"docstring": "Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ------- Costas object",
"name": "__init__",
"signature": "def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias)"
},
{
"docstring": "Costas discriminator.... | 5 | stack_v2_sparse_classes_30k_train_023238 | Implement the Python class `Costas` described below.
Class description:
Implement the Costas class.
Method signatures and docstrings:
- def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias): Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ... | Implement the Python class `Costas` described below.
Class description:
Implement the Costas class.
Method signatures and docstrings:
- def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias): Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ... | 50189c74f92dddaf88ba9a8ac322d4e21f140746 | <|skeleton|>
class Costas:
def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias):
"""Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ------- Costas object"""
<|body_0|>
def costas_detector(self, Ips, Qps, mode):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Costas:
def __init__(self, lf_coeff, costas_mode, freq_mode, freq_bias):
"""Costas block Parameters ---------- int_time: int lf_coeff: list pd_mode: int costas_mode: int freq_mode: int Returns ------- Costas object"""
self._avg_mag = 0
self._count = 0
self._Ips_d = 0
se... | the_stack_v2_python_sparse | python/blocks/costas_model.py | techeraj-osh/fa18-gps | train | 0 | |
283c28bc1bef0f0d4a6851ce8feed887180c31a8 | [
"mimetype = self.context.resource_mimetype()\nif mimetype:\n mime_parts = mimetype.split('/')\n for view_name in ['%s_%s' % tuple(mime_parts), mime_parts[0], 'default']:\n view = queryMultiAdapter((self.context, self.request), name='resource_%s' % view_name)\n if view:\n return view._... | <|body_start_0|>
mimetype = self.context.resource_mimetype()
if mimetype:
mime_parts = mimetype.split('/')
for view_name in ['%s_%s' % tuple(mime_parts), mime_parts[0], 'default']:
view = queryMultiAdapter((self.context, self.request), name='resource_%s' % view_na... | A view to display a resource. | ATResourceView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
<|body_0|>
def resource(self):
"""Renders the resource."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m... | stack_v2_sparse_classes_75kplus_train_001518 | 1,247 | no_license | [
{
"docstring": "Returns the view for the resource based on its mimetype.",
"name": "resource_view",
"signature": "def resource_view(self)"
},
{
"docstring": "Renders the resource.",
"name": "resource",
"signature": "def resource(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031682 | Implement the Python class `ATResourceView` described below.
Class description:
A view to display a resource.
Method signatures and docstrings:
- def resource_view(self): Returns the view for the resource based on its mimetype.
- def resource(self): Renders the resource. | Implement the Python class `ATResourceView` described below.
Class description:
A view to display a resource.
Method signatures and docstrings:
- def resource_view(self): Returns the view for the resource based on its mimetype.
- def resource(self): Renders the resource.
<|skeleton|>
class ATResourceView:
"""A v... | bd7ca0793d35bbdbc83200d27650fe024d1f432e | <|skeleton|>
class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
<|body_0|>
def resource(self):
"""Renders the resource."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ATResourceView:
"""A view to display a resource."""
def resource_view(self):
"""Returns the view for the resource based on its mimetype."""
mimetype = self.context.resource_mimetype()
if mimetype:
mime_parts = mimetype.split('/')
for view_name in ['%s_%s' %... | the_stack_v2_python_sparse | groundwire/atresources/browser/atresource.py | collective/groundwire.atresources | train | 0 |
36b8d6176fdfeba35e83a351c4015d0ba2ad281a | [
"res = {}\npoint_type = DBSCAN(eps=eps, min_samples=min_samples).fit_predict(points)\nfor point_index, each_point in enumerate(points):\n each_type = point_type[point_index]\n if each_type in res:\n res[each_type].append(each_point)\n else:\n res[each_type] = [each_point]\nreturn res",
"poi... | <|body_start_0|>
res = {}
point_type = DBSCAN(eps=eps, min_samples=min_samples).fit_predict(points)
for point_index, each_point in enumerate(points):
each_type = point_type[point_index]
if each_type in res:
res[each_type].append(each_point)
els... | DbscanUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbscanUtil:
def cluser_saptial_point(points, eps, min_samples=2):
"""空间点的聚类"""
<|body_0|>
def cluser_point_shp(point_path, save_path, eps, min_samples=2):
"""聚类邻近的点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = {}
point_type = DBSCAN... | stack_v2_sparse_classes_75kplus_train_001519 | 2,526 | no_license | [
{
"docstring": "空间点的聚类",
"name": "cluser_saptial_point",
"signature": "def cluser_saptial_point(points, eps, min_samples=2)"
},
{
"docstring": "聚类邻近的点",
"name": "cluser_point_shp",
"signature": "def cluser_point_shp(point_path, save_path, eps, min_samples=2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050954 | Implement the Python class `DbscanUtil` described below.
Class description:
Implement the DbscanUtil class.
Method signatures and docstrings:
- def cluser_saptial_point(points, eps, min_samples=2): 空间点的聚类
- def cluser_point_shp(point_path, save_path, eps, min_samples=2): 聚类邻近的点 | Implement the Python class `DbscanUtil` described below.
Class description:
Implement the DbscanUtil class.
Method signatures and docstrings:
- def cluser_saptial_point(points, eps, min_samples=2): 空间点的聚类
- def cluser_point_shp(point_path, save_path, eps, min_samples=2): 聚类邻近的点
<|skeleton|>
class DbscanUtil:
de... | 32e64be10a6cd2856850f6720d70b4c6e7033f4e | <|skeleton|>
class DbscanUtil:
def cluser_saptial_point(points, eps, min_samples=2):
"""空间点的聚类"""
<|body_0|>
def cluser_point_shp(point_path, save_path, eps, min_samples=2):
"""聚类邻近的点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbscanUtil:
def cluser_saptial_point(points, eps, min_samples=2):
"""空间点的聚类"""
res = {}
point_type = DBSCAN(eps=eps, min_samples=min_samples).fit_predict(points)
for point_index, each_point in enumerate(points):
each_type = point_type[point_index]
if eac... | the_stack_v2_python_sparse | DataMining/cluser/DBSCAN.py | newjokker/PyUtil | train | 0 | |
f961ef060265ee1a174f567cfba68f6c9227eaec | [
"try:\n for file in os.listdir(directory):\n if file.endswith('.js'):\n filepath = '%s/%s' % (directory, file)\n self._get_data_from_file(filepath)\n self.file_count += 1\nexcept OSError as e:\n raise IngestError(e)\nif self.file_count == 0:\n raise IngestError('No .... | <|body_start_0|>
try:
for file in os.listdir(directory):
if file.endswith('.js'):
filepath = '%s/%s' % (directory, file)
self._get_data_from_file(filepath)
self.file_count += 1
except OSError as e:
raise ... | Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and May, the format changed to what we call version ... | Version1TweetIngester | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Version1TweetIngester:
"""Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and... | stack_v2_sparse_classes_75kplus_train_001520 | 11,221 | permissive | [
{
"docstring": "Goes through all the *.js files in `directory` and puts the tweet data inside into self.tweets_data. No data is saved to the database until we've successfully loaded JSON from all of the files. Keyword arguments: directory -- The directory to load the files from. Raises: IngestError -- If the di... | 2 | stack_v2_sparse_classes_30k_train_032272 | Implement the Python class `Version1TweetIngester` described below.
Class description:
Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from... | Implement the Python class `Version1TweetIngester` described below.
Class description:
Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from... | 57ee6f6657b41705af71ef67924d8ef06c60ae4f | <|skeleton|>
class Version1TweetIngester:
"""Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Version1TweetIngester:
"""Used for the old (original?) format of twitter archives, which contained three files and five folders, including data/js/tweets/ which contained a .js file for every month, like 2016_02.js. This is what we import the tweet data from. Sometime in 2019, between January and May, the for... | the_stack_v2_python_sparse | ditto/twitter/ingest.py | philgyford/django-ditto | train | 59 |
58100c9577cd0ac7d519ab36bb4923581c227f02 | [
"self.pipeline = pipeline\nsuper().__init__()\nself.daemon = True\nself.start()",
"pipeline = self.pipeline\ncheck_prev_done = len(pipeline.procs) == 1\nif check_prev_done:\n return\nproc = pipeline.proc\nprev_end_time = None\ntimeout = XSH.env.get('XONSH_PROC_FREQUENCY')\nsleeptime = min(timeout * 1000, 0.1)\... | <|body_start_0|>
self.pipeline = pipeline
super().__init__()
self.daemon = True
self.start()
<|end_body_0|>
<|body_start_1|>
pipeline = self.pipeline
check_prev_done = len(pipeline.procs) == 1
if check_prev_done:
return
proc = pipeline.proc
... | Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock. | PrevProcCloser | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrevProcCloser:
"""Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock."""
def __init__(self, pipeline):
"""Parameters ---------- pipeline : CommandPipeline The pipeline whos... | stack_v2_sparse_classes_75kplus_train_001521 | 26,642 | permissive | [
{
"docstring": "Parameters ---------- pipeline : CommandPipeline The pipeline whose prev procs we should close.",
"name": "__init__",
"signature": "def __init__(self, pipeline)"
},
{
"docstring": "Runs the closing algorithm.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046427 | Implement the Python class `PrevProcCloser` described below.
Class description:
Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock.
Method signatures and docstrings:
- def __init__(self, pipeline): Parameter... | Implement the Python class `PrevProcCloser` described below.
Class description:
Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock.
Method signatures and docstrings:
- def __init__(self, pipeline): Parameter... | 60f0145ed893cb73bbfcf336c448238981010d41 | <|skeleton|>
class PrevProcCloser:
"""Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock."""
def __init__(self, pipeline):
"""Parameters ---------- pipeline : CommandPipeline The pipeline whos... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrevProcCloser:
"""Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock."""
def __init__(self, pipeline):
"""Parameters ---------- pipeline : CommandPipeline The pipeline whose prev procs ... | the_stack_v2_python_sparse | xonsh/procs/pipelines.py | xonsh/xonsh | train | 6,374 |
76d61f95b2f041bdddabff067593ee2c7547499a | [
"from torch.nn import ModuleList\nfrom torch.nn import Conv2d\nsuper().__init__()\nassert feature_size != 0 and feature_size & feature_size - 1 == 0, 'latent size not a power of 2'\nif depth >= 4:\n assert feature_size >= np.power(2, depth - 4), 'feature size cannot be produced'\nself.depth = depth\nself.feature... | <|body_start_0|>
from torch.nn import ModuleList
from torch.nn import Conv2d
super().__init__()
assert feature_size != 0 and feature_size & feature_size - 1 == 0, 'latent size not a power of 2'
if depth >= 4:
assert feature_size >= np.power(2, depth - 4), 'feature siz... | Discriminator of the GAN | msg_stylegan2_lm_id_D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class msg_stylegan2_lm_id_D:
"""Discriminator of the GAN"""
def __init__(self, depth=7, feature_size=512, dilation=1, use_spectral_norm=True):
"""constructor for the class :param depth: total depth of the discriminator (Must be equal to the Generator depth) :param feature_size: size of the... | stack_v2_sparse_classes_75kplus_train_001522 | 14,685 | no_license | [
{
"docstring": "constructor for the class :param depth: total depth of the discriminator (Must be equal to the Generator depth) :param feature_size: size of the deepest features extracted (Must be equal to Generator latent_size) :param dilation: amount of dilation to be applied to the 3x3 convolutional blocks o... | 4 | stack_v2_sparse_classes_30k_train_022204 | Implement the Python class `msg_stylegan2_lm_id_D` described below.
Class description:
Discriminator of the GAN
Method signatures and docstrings:
- def __init__(self, depth=7, feature_size=512, dilation=1, use_spectral_norm=True): constructor for the class :param depth: total depth of the discriminator (Must be equal... | Implement the Python class `msg_stylegan2_lm_id_D` described below.
Class description:
Discriminator of the GAN
Method signatures and docstrings:
- def __init__(self, depth=7, feature_size=512, dilation=1, use_spectral_norm=True): constructor for the class :param depth: total depth of the discriminator (Must be equal... | 428abe1fefe5ea4ef00290155e7e59657bc83444 | <|skeleton|>
class msg_stylegan2_lm_id_D:
"""Discriminator of the GAN"""
def __init__(self, depth=7, feature_size=512, dilation=1, use_spectral_norm=True):
"""constructor for the class :param depth: total depth of the discriminator (Must be equal to the Generator depth) :param feature_size: size of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class msg_stylegan2_lm_id_D:
"""Discriminator of the GAN"""
def __init__(self, depth=7, feature_size=512, dilation=1, use_spectral_norm=True):
"""constructor for the class :param depth: total depth of the discriminator (Must be equal to the Generator depth) :param feature_size: size of the deepest feat... | the_stack_v2_python_sparse | src/msg_stylegan2.py | blakecheng/lafin | train | 0 |
060a89f3aa8dd16b53805392963f2c1cb2028ef7 | [
"self.M = 0\nself.G = []\nE = 100000000000000\ny_m = y\nwhile E > error:\n if model == 'CART':\n self.G.append(CART(x, y_m, 'regression', max_depth=1))\n self.M += 1\n y_t = self.fit(x)\n E = np.sum((y_t - y) ** 2)\n y_m = y - y_t",
"y = np.zeros(x.shape[0])\nfor m in range(self.M):\n y =... | <|body_start_0|>
self.M = 0
self.G = []
E = 100000000000000
y_m = y
while E > error:
if model == 'CART':
self.G.append(CART(x, y_m, 'regression', max_depth=1))
self.M += 1
y_t = self.fit(x)
E = np.sum((y_t - y) ** 2)... | GBDT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBDT:
def __init__(self, x, y, model='CART', error=0.001):
"""Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error"""
<|body_0|>
def fit(self, x):
"""Input x: forecast data [N, M] Output y: forecast label [N]"""
<|body_... | stack_v2_sparse_classes_75kplus_train_001523 | 1,040 | no_license | [
{
"docstring": "Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error",
"name": "__init__",
"signature": "def __init__(self, x, y, model='CART', error=0.001)"
},
{
"docstring": "Input x: forecast data [N, M] Output y: forecast label [N]",
"name": "fit",... | 2 | stack_v2_sparse_classes_30k_train_012845 | Implement the Python class `GBDT` described below.
Class description:
Implement the GBDT class.
Method signatures and docstrings:
- def __init__(self, x, y, model='CART', error=0.001): Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error
- def fit(self, x): Input x: forecast da... | Implement the Python class `GBDT` described below.
Class description:
Implement the GBDT class.
Method signatures and docstrings:
- def __init__(self, x, y, model='CART', error=0.001): Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error
- def fit(self, x): Input x: forecast da... | 6920d98411c386269687ea51a96958f803b10b5e | <|skeleton|>
class GBDT:
def __init__(self, x, y, model='CART', error=0.001):
"""Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error"""
<|body_0|>
def fit(self, x):
"""Input x: forecast data [N, M] Output y: forecast label [N]"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GBDT:
def __init__(self, x, y, model='CART', error=0.001):
"""Input x: data [N, M] y: label [N] model: base model, default is 'CART' error: training error"""
self.M = 0
self.G = []
E = 100000000000000
y_m = y
while E > error:
if model == 'CART':
... | the_stack_v2_python_sparse | GBDT.py | chenchuanchang/Machine-Learning | train | 2 | |
26903bf867ae833d581046b7c91e20d657f4cc5e | [
"self.parser.add_argument('groupID', type=int, location='args', required=True, help='groupID验证失败')\nargs = self.parser.parse_args()\ngroupID = args['groupID']\nabort_if_todo_doesnt_exist_api_group(groupID)\nstatus_group = EoApiGroup.query.get(groupID)\nreturn status_group",
"self.parser.add_argument('groupName', ... | <|body_start_0|>
self.parser.add_argument('groupID', type=int, location='args', required=True, help='groupID验证失败')
args = self.parser.parse_args()
groupID = args['groupID']
abort_if_todo_doesnt_exist_api_group(groupID)
status_group = EoApiGroup.query.get(groupID)
return s... | ApiGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiGroup:
def get(self):
"""获取api文档分组 :param groupID : 分组ID :return:"""
<|body_0|>
def post(self):
"""新增api文档分组 :return:"""
<|body_1|>
def put(self):
"""更新api文档分组详情 :return:"""
<|body_2|>
def delete(self):
""":return:"""
... | stack_v2_sparse_classes_75kplus_train_001524 | 11,434 | no_license | [
{
"docstring": "获取api文档分组 :param groupID : 分组ID :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新增api文档分组 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "更新api文档分组详情 :return:",
"name": "put",
"signature": "def put(self... | 4 | stack_v2_sparse_classes_30k_train_009998 | Implement the Python class `ApiGroup` described below.
Class description:
Implement the ApiGroup class.
Method signatures and docstrings:
- def get(self): 获取api文档分组 :param groupID : 分组ID :return:
- def post(self): 新增api文档分组 :return:
- def put(self): 更新api文档分组详情 :return:
- def delete(self): :return: | Implement the Python class `ApiGroup` described below.
Class description:
Implement the ApiGroup class.
Method signatures and docstrings:
- def get(self): 获取api文档分组 :param groupID : 分组ID :return:
- def post(self): 新增api文档分组 :return:
- def put(self): 更新api文档分组详情 :return:
- def delete(self): :return:
<|skeleton|>
clas... | a329cdbc722aca1b498bd00734415149167200dc | <|skeleton|>
class ApiGroup:
def get(self):
"""获取api文档分组 :param groupID : 分组ID :return:"""
<|body_0|>
def post(self):
"""新增api文档分组 :return:"""
<|body_1|>
def put(self):
"""更新api文档分组详情 :return:"""
<|body_2|>
def delete(self):
""":return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiGroup:
def get(self):
"""获取api文档分组 :param groupID : 分组ID :return:"""
self.parser.add_argument('groupID', type=int, location='args', required=True, help='groupID验证失败')
args = self.parser.parse_args()
groupID = args['groupID']
abort_if_todo_doesnt_exist_api_group(group... | the_stack_v2_python_sparse | api/v1/api/Api.py | xiao2912008572/test_platform_api | train | 0 | |
02b6a8203c0724514107d7f971d1ac0a85593762 | [
"def integrate() -> np.ndarray:\n Eg, stepsize = self.norm_pars.E_grid()\n Ex = self.norm_pars.Sn[0] - Eg\n integral = np.power(Eg, 3) * gsf(Eg).values * nld_warpper(Ex) * self.SpinSum(Ex, self.norm_pars.Jtarget)\n integral = np.sum(integral) * stepsize\n return integral\n\ndef nld_warpper(Ex) -> np.... | <|body_start_0|>
def integrate() -> np.ndarray:
Eg, stepsize = self.norm_pars.E_grid()
Ex = self.norm_pars.Sn[0] - Eg
integral = np.power(Eg, 3) * gsf(Eg).values * nld_warpper(Ex) * self.SpinSum(Ex, self.norm_pars.Jtarget)
integral = np.sum(integral) * stepsize
... | Calculate lnlike for Gg Attributes: Gg_model: model Gg | LnlikeGg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LnlikeGg:
"""Calculate lnlike for Gg Attributes: Gg_model: model Gg"""
def Gg_standard(self, nld: Callable[[float], Vector], gsf: Callable[[float], Vector], D0: float) -> float:
"""Compute normalization from <Γγ> (Gg) integral; overwrites parent See NormalizerGSF.Gg_standard, however... | stack_v2_sparse_classes_75kplus_train_001525 | 2,050 | no_license | [
{
"docstring": "Compute normalization from <Γγ> (Gg) integral; overwrites parent See NormalizerGSF.Gg_standard, however, now just using the given nld and gsf; no extra model Args: nld: function providing the nld at the an input energy E gsf: function providing the gsf at the an input energy E D0: D0 to use with... | 2 | null | Implement the Python class `LnlikeGg` described below.
Class description:
Calculate lnlike for Gg Attributes: Gg_model: model Gg
Method signatures and docstrings:
- def Gg_standard(self, nld: Callable[[float], Vector], gsf: Callable[[float], Vector], D0: float) -> float: Compute normalization from <Γγ> (Gg) integral;... | Implement the Python class `LnlikeGg` described below.
Class description:
Calculate lnlike for Gg Attributes: Gg_model: model Gg
Method signatures and docstrings:
- def Gg_standard(self, nld: Callable[[float], Vector], gsf: Callable[[float], Vector], D0: float) -> float: Compute normalization from <Γγ> (Gg) integral;... | 377f254bb2bdbc90e810c82889a5376683560e0e | <|skeleton|>
class LnlikeGg:
"""Calculate lnlike for Gg Attributes: Gg_model: model Gg"""
def Gg_standard(self, nld: Callable[[float], Vector], gsf: Callable[[float], Vector], D0: float) -> float:
"""Compute normalization from <Γγ> (Gg) integral; overwrites parent See NormalizerGSF.Gg_standard, however... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LnlikeGg:
"""Calculate lnlike for Gg Attributes: Gg_model: model Gg"""
def Gg_standard(self, nld: Callable[[float], Vector], gsf: Callable[[float], Vector], D0: float) -> float:
"""Compute normalization from <Γγ> (Gg) integral; overwrites parent See NormalizerGSF.Gg_standard, however, now just us... | the_stack_v2_python_sparse | gledeli/lnlike_Gg.py | anderkve/gledeli | train | 2 |
c6013f131a6b3e35cb594c75e7cd391dcc7d983f | [
"try:\n user = self.get_user(request, username)\nexcept PermissionDenied:\n return redirect(reverse('login') + '?next=' + request.path)\nlinks = Link.objects.select_related('category').filter(user=user).order_by('category__title', 'weight')\npalette = set((link.color for link in links))\ncategorized_links = d... | <|body_start_0|>
try:
user = self.get_user(request, username)
except PermissionDenied:
return redirect(reverse('login') + '?next=' + request.path)
links = Link.objects.select_related('category').filter(user=user).order_by('category__title', 'weight')
palette = set... | LinkView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkView:
def get(self, request, username=None):
"""Get list of links."""
<|body_0|>
def post(self, request, username=None):
"""Form submit."""
<|body_1|>
def delete(self, request, pk, username=None):
"""Delete link."""
<|body_2|>
<|end_... | stack_v2_sparse_classes_75kplus_train_001526 | 30,576 | permissive | [
{
"docstring": "Get list of links.",
"name": "get",
"signature": "def get(self, request, username=None)"
},
{
"docstring": "Form submit.",
"name": "post",
"signature": "def post(self, request, username=None)"
},
{
"docstring": "Delete link.",
"name": "delete",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_019813 | Implement the Python class `LinkView` described below.
Class description:
Implement the LinkView class.
Method signatures and docstrings:
- def get(self, request, username=None): Get list of links.
- def post(self, request, username=None): Form submit.
- def delete(self, request, pk, username=None): Delete link. | Implement the Python class `LinkView` described below.
Class description:
Implement the LinkView class.
Method signatures and docstrings:
- def get(self, request, username=None): Get list of links.
- def post(self, request, username=None): Form submit.
- def delete(self, request, pk, username=None): Delete link.
<|s... | 51a2ae2b29ae5c91a3cf7171f89edf225cc8a6f0 | <|skeleton|>
class LinkView:
def get(self, request, username=None):
"""Get list of links."""
<|body_0|>
def post(self, request, username=None):
"""Form submit."""
<|body_1|>
def delete(self, request, pk, username=None):
"""Delete link."""
<|body_2|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkView:
def get(self, request, username=None):
"""Get list of links."""
try:
user = self.get_user(request, username)
except PermissionDenied:
return redirect(reverse('login') + '?next=' + request.path)
links = Link.objects.select_related('category').fi... | the_stack_v2_python_sparse | tool/views/views.py | mikekeda/tools | train | 0 | |
c31649c33697dc264d0706938ab83fa194bfd7c0 | [
"if len(matrix) == 0:\n return False\nif len(matrix[0]) == 0:\n return False\nreturn any((target in row for row in matrix))",
"if len(matrix) == 0:\n return False\nif len(matrix[0]) == 0:\n return False\nj = -1\nfor row in matrix:\n while j + len(row) and row[j] > target:\n j -= 1\n if ro... | <|body_start_0|>
if len(matrix) == 0:
return False
if len(matrix[0]) == 0:
return False
return any((target in row for row in matrix))
<|end_body_0|>
<|body_start_1|>
if len(matrix) == 0:
return False
if len(matrix[0]) == 0:
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
def sea... | stack_v2_sparse_classes_75kplus_train_001527 | 3,286 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def search... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
def sea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if len(matrix) == 0:
return False
if len(matrix[0]) == 0:
return False
return any((target in row for row in matrix))
def searchMatri... | the_stack_v2_python_sparse | Problems/0200_0299/0240_Search_a_2D_Matrix2/Project_Python3/Search_a_2D_Matrix2.py | NobuyukiInoue/LeetCode | train | 0 | |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"self.slope = -1.0\nself.last_obs = -1.0\nself.last_obs_ind = -1\nself._fitted = False",
"if X.size != y.size:\n raise ValueError(\"'X' and 'y' size must match.\")\nself.last_obs = y[-1]\nself.last_obs_ind = X[-1]\nif y.size > 1:\n self.slope = (y[-1] - y[0]) / (X[-1] - X[0])\nelse:\n self.slope = 0.0\ns... | <|body_start_0|>
self.slope = -1.0
self.last_obs = -1.0
self.last_obs_ind = -1
self._fitted = False
<|end_body_0|>
<|body_start_1|>
if X.size != y.size:
raise ValueError("'X' and 'y' size must match.")
self.last_obs = y[-1]
self.last_obs_ind = X[-1]
... | Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series. | TSNaiveDrift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last o... | stack_v2_sparse_classes_75kplus_train_001528 | 12,299 | permissive | [
{
"docstring": "Init a Naive model with drift.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value... | 3 | stack_v2_sparse_classes_30k_train_018929 | Implement the Python class `TSNaiveDrift` described below.
Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp... | Implement the Python class `TSNaiveDrift` described below.
Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
9c299051abb7e8dab6f12a35b9038c0d49fd05bc | [
"from apysc.expression import expression_file_util\nif not self._last_scope_is_if_or_elif():\n raise ValueError('Elif interface can only use right after If or Elif interfaces.\\n\\nMaybe you are using Int or String, or anything else comparison expression at Elif constructor (e.g., `with Elif(any_value == 10, ...... | <|body_start_0|>
from apysc.expression import expression_file_util
if not self._last_scope_is_if_or_elif():
raise ValueError('Elif interface can only use right after If or Elif interfaces.\n\nMaybe you are using Int or String, or anything else comparison expression at Elif constructor (e.g.,... | Elif | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
... | stack_v2_sparse_classes_75kplus_train_001529 | 1,724 | permissive | [
{
"docstring": "Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.",
"name": "_append_enter_expression",
"signature": "def _append_enter_expression(self) -> None"
},
{
"docstring": "Set expression last scope value.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_007006 | Implement the Python class `Elif` described below.
Class description:
Implement the Elif class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.
- def _set_last_scop... | Implement the Python class `Elif` described below.
Class description:
Implement the Elif class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif.
- def _set_last_scop... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Elif:
def _append_enter_expression(self) -> None:
"""Append else if branch instruction start expression to file. Raises ------ ValueError If the last scope is not If or Elif."""
from apysc.expression import expression_file_util
if not self._last_scope_is_if_or_elif():
raise... | the_stack_v2_python_sparse | apysc/branch/_elif.py | TrendingTechnology/apysc | train | 0 | |
1bc695ef067e4c1b9174d79b3382c084aab0f8a5 | [
"post = create_post(title='motley smells bad')\npost_comment = create_post_comment(post=post)\nself.assertEqual(post_comment.post_title(), 'motley smells bad')",
"anonymous_user = create_anonymous_user(is_blocked=True)\npost_comment = create_post_comment(anonymous_user=anonymous_user)\nself.assertTrue(post_commen... | <|body_start_0|>
post = create_post(title='motley smells bad')
post_comment = create_post_comment(post=post)
self.assertEqual(post_comment.post_title(), 'motley smells bad')
<|end_body_0|>
<|body_start_1|>
anonymous_user = create_anonymous_user(is_blocked=True)
post_comment = cr... | Test cases for post comments | PostCommentCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostCommentCase:
"""Test cases for post comments"""
def test_post_title(self):
"""Tests the comment post title"""
<|body_0|>
def test_is_user_blocked(self):
"""Tests the commented user is blocked and not blocked"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_001530 | 3,246 | no_license | [
{
"docstring": "Tests the comment post title",
"name": "test_post_title",
"signature": "def test_post_title(self)"
},
{
"docstring": "Tests the commented user is blocked and not blocked",
"name": "test_is_user_blocked",
"signature": "def test_is_user_blocked(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012316 | Implement the Python class `PostCommentCase` described below.
Class description:
Test cases for post comments
Method signatures and docstrings:
- def test_post_title(self): Tests the comment post title
- def test_is_user_blocked(self): Tests the commented user is blocked and not blocked | Implement the Python class `PostCommentCase` described below.
Class description:
Test cases for post comments
Method signatures and docstrings:
- def test_post_title(self): Tests the comment post title
- def test_is_user_blocked(self): Tests the commented user is blocked and not blocked
<|skeleton|>
class PostCommen... | eecfaf03287fdb0ee590d7ee61c0c041c0eb819a | <|skeleton|>
class PostCommentCase:
"""Test cases for post comments"""
def test_post_title(self):
"""Tests the comment post title"""
<|body_0|>
def test_is_user_blocked(self):
"""Tests the commented user is blocked and not blocked"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostCommentCase:
"""Test cases for post comments"""
def test_post_title(self):
"""Tests the comment post title"""
post = create_post(title='motley smells bad')
post_comment = create_post_comment(post=post)
self.assertEqual(post_comment.post_title(), 'motley smells bad')
... | the_stack_v2_python_sparse | blog/tests.py | jwdepetro/avocadoist | train | 0 |
38cfe0f5bda3e41a51628ae02c58ccc004238a8e | [
"self.capacity = capacity\nself.node_map = {}\nself.head = None\nself.tail = None",
"if key not in self.node_map:\n return -1\nnode = self.node_map[key]\nif node.next != None:\n if node.prev == None:\n self.head = self.head.next\n self.head.prev = None\n else:\n node.prev.next = node... | <|body_start_0|>
self.capacity = capacity
self.node_map = {}
self.head = None
self.tail = None
<|end_body_0|>
<|body_start_1|>
if key not in self.node_map:
return -1
node = self.node_map[key]
if node.next != None:
if node.prev == None:
... | LRUCache2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_75kplus_train_001531 | 22,676 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_003386 | Implement the Python class `LRUCache2` described below.
Class description:
Implement the LRUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache2` described below.
Class description:
Implement the LRUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache2:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.node_map = {}
self.head = None
self.tail = None
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.node_map:
return -1
... | the_stack_v2_python_sparse | leetcode/leetcode_special.py | Rivarrl/leetcode_python | train | 3 | |
78f5e717712b08efeecae9f439d9373ec3022a19 | [
"url = DAILYMILE_USERINFO + '?oauth_token=%s' % access_token\nres = requests.get(url)\ntry:\n return json.loads(res.text)\nexcept ValueError:\n return None",
"if self.STATE_PARAMETER or self.REDIRECT_STATE:\n name = self.AUTH_BACKEND.name + '_state'\n state = self.request.session.get(name) or self.sta... | <|body_start_0|>
url = DAILYMILE_USERINFO + '?oauth_token=%s' % access_token
res = requests.get(url)
try:
return json.loads(res.text)
except ValueError:
return None
<|end_body_0|>
<|body_start_1|>
if self.STATE_PARAMETER or self.REDIRECT_STATE:
... | NikeAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NikeAuth:
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_0|>
def auth_url(self):
"""Return redirect url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = DAILYMILE_USERINFO + '?oauth_token=%s' % acc... | stack_v2_sparse_classes_75kplus_train_001532 | 3,794 | no_license | [
{
"docstring": "Loads user data from service",
"name": "user_data",
"signature": "def user_data(self, access_token, *args, **kwargs)"
},
{
"docstring": "Return redirect url",
"name": "auth_url",
"signature": "def auth_url(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051135 | Implement the Python class `NikeAuth` described below.
Class description:
Implement the NikeAuth class.
Method signatures and docstrings:
- def user_data(self, access_token, *args, **kwargs): Loads user data from service
- def auth_url(self): Return redirect url | Implement the Python class `NikeAuth` described below.
Class description:
Implement the NikeAuth class.
Method signatures and docstrings:
- def user_data(self, access_token, *args, **kwargs): Loads user data from service
- def auth_url(self): Return redirect url
<|skeleton|>
class NikeAuth:
def user_data(self, ... | e64631edbd49eb38f4520c25a9f6d08fae588bd8 | <|skeleton|>
class NikeAuth:
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_0|>
def auth_url(self):
"""Return redirect url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NikeAuth:
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
url = DAILYMILE_USERINFO + '?oauth_token=%s' % access_token
res = requests.get(url)
try:
return json.loads(res.text)
except ValueError:
return None
... | the_stack_v2_python_sparse | physical/auth_backends/nike.py | wikilife-org/datadonor | train | 3 | |
20650ab387df05d348336c4b4f5f11dbc12393fc | [
"self.event_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()\nself.logger = logging.getLogger('APP')\nself.name: str = name\ntry:\n self.event_loop.add_signal_handler(signal.SIGINT, self.on_signal, signal.SIGINT)\n self.event_loop.add_signal_handler(signal.SIGTERM, self.on_signal, signal.SIGTERM)\ne... | <|body_start_0|>
self.event_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
self.logger = logging.getLogger('APP')
self.name: str = name
try:
self.event_loop.add_signal_handler(signal.SIGINT, self.on_signal, signal.SIGINT)
self.event_loop.add_signal_han... | Standard application setup. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Standard application setup."""
def __init__(self, name: str, config_validator: Optional[Callable]=None):
"""Initialise a new instance of the Application class."""
<|body_0|>
def on_signal(self, signum: int) -> None:
"""Called when a signal is rece... | stack_v2_sparse_classes_75kplus_train_001533 | 2,583 | no_license | [
{
"docstring": "Initialise a new instance of the Application class.",
"name": "__init__",
"signature": "def __init__(self, name: str, config_validator: Optional[Callable]=None)"
},
{
"docstring": "Called when a signal is received.",
"name": "on_signal",
"signature": "def on_signal(self, ... | 3 | null | Implement the Python class `Application` described below.
Class description:
Standard application setup.
Method signatures and docstrings:
- def __init__(self, name: str, config_validator: Optional[Callable]=None): Initialise a new instance of the Application class.
- def on_signal(self, signum: int) -> None: Called ... | Implement the Python class `Application` described below.
Class description:
Standard application setup.
Method signatures and docstrings:
- def __init__(self, name: str, config_validator: Optional[Callable]=None): Initialise a new instance of the Application class.
- def on_signal(self, signum: int) -> None: Called ... | b9e15977c212c8c669514a41b8a6d791f6502ca4 | <|skeleton|>
class Application:
"""Standard application setup."""
def __init__(self, name: str, config_validator: Optional[Callable]=None):
"""Initialise a new instance of the Application class."""
<|body_0|>
def on_signal(self, signum: int) -> None:
"""Called when a signal is rece... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Standard application setup."""
def __init__(self, name: str, config_validator: Optional[Callable]=None):
"""Initialise a new instance of the Application class."""
self.event_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
self.logger = logging.getLogger(... | the_stack_v2_python_sparse | ready_trader_one/application.py | jermainejanszen/ready_trader_one_2020 | train | 1 |
19a34895e7fa45e92962f3cfff2566a06d42ac0e | [
"self.aag_backup_preference_type = aag_backup_preference_type\nself.advanced_settings = advanced_settings\nself.backup_database_volumes_only = backup_database_volumes_only\nself.backup_system_dbs = backup_system_dbs\nself.continue_after_error = continue_after_error\nself.enable_checksum = enable_checksum\nself.enab... | <|body_start_0|>
self.aag_backup_preference_type = aag_backup_preference_type
self.advanced_settings = advanced_settings
self.backup_database_volumes_only = backup_database_volumes_only
self.backup_system_dbs = backup_system_dbs
self.continue_after_error = continue_after_error
... | Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only applicable if 'use_aag_preferences_from_sql_server' is set to false. advanced_settings (... | SqlBackupJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqlBackupJobParams:
"""Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only applicable if 'use_aag_preferences_from_sq... | stack_v2_sparse_classes_75kplus_train_001534 | 9,427 | permissive | [
{
"docstring": "Constructor for the SqlBackupJobParams class",
"name": "__init__",
"signature": "def __init__(self, aag_backup_preference_type=None, advanced_settings=None, backup_database_volumes_only=None, backup_system_dbs=None, continue_after_error=None, enable_checksum=None, enable_incremental_back... | 2 | stack_v2_sparse_classes_30k_train_031165 | Implement the Python class `SqlBackupJobParams` described below.
Class description:
Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only app... | Implement the Python class `SqlBackupJobParams` described below.
Class description:
Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only app... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SqlBackupJobParams:
"""Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only applicable if 'use_aag_preferences_from_sq... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SqlBackupJobParams:
"""Implementation of the 'SqlBackupJobParams' model. Message to capture additional backup job params specific to SQL. Attributes: aag_backup_preference_type (int): Preference type for backing up databases that are part of an AAG. Only applicable if 'use_aag_preferences_from_sql_server' is ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/sql_backup_job_params.py | cohesity/management-sdk-python | train | 24 |
6a930c8a1353c5becbaa2a1cf78191bacd40dd5c | [
"cur = head\na = []\nwhile cur:\n a.append(cur.val)\n cur = cur.next\nfor i in range(len(a)):\n if a[i] != a[len(a) - 1 - i]:\n return False\nreturn True",
"if not head.next:\n return True\ndummy = ListNode()\ndummy.next = head\none, two = (dummy, dummy)\nwhile two and two.next:\n one = one.... | <|body_start_0|>
cur = head
a = []
while cur:
a.append(cur.val)
cur = cur.next
for i in range(len(a)):
if a[i] != a[len(a) - 1 - i]:
return False
return True
<|end_body_0|>
<|body_start_1|>
if not head.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
<|body_0|>
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(1) Solution ... | stack_v2_sparse_classes_75kplus_train_001535 | 2,407 | no_license | [
{
"docstring": "Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head: ListNode) -> bool"
},
{
"docstring": "Time Complexity : O(N), Space Complexity : O(1) Solution : 아래 방식과 동일한데 절반 위치를 구하고 리스트를 분리... | 3 | stack_v2_sparse_classes_30k_train_008443 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교
- def isPalindrome(self, head: ListNode) -> bo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head: ListNode) -> bool: Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교
- def isPalindrome(self, head: ListNode) -> bo... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
<|body_0|>
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(1) Solution ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
"""Time Complexity : O(N), Space Complexity : O(N) Solution : list만들어서 two pointer로 비교"""
cur = head
a = []
while cur:
a.append(cur.val)
cur = cur.next
for i in range(len(a)):
... | the_stack_v2_python_sparse | Leetcode/Palindrome_Linked_List.py | hanwgyu/algorithm_problem_solving | train | 5 | |
8a071d31064ba894c446a0212ab06d415af08d3d | [
"if not root:\n return []\nres = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]\nreturn res",
"if len(data) == 0:\n return None\nroot = TreeNode(data[0])\nroot.left = self.deserialize(data[1])\nroot.right = self.deserialize(data[2])\nreturn root"
] | <|body_start_0|>
if not root:
return []
res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]
return res
<|end_body_0|>
<|body_start_1|>
if len(data) == 0:
return None
root = TreeNode(data[0])
root.left = self.deserialize(d... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_001536 | 5,388 | 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_013181 | 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:... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
res = [root.val] + [self.serialize(root.left)] + [self.serialize(root.right)]
return res
def deserialize(self, data):
"""D... | the_stack_v2_python_sparse | Python/SerializeandDeserializeBinaryTree.py | here0009/LeetCode | train | 1 | |
650d9745a03acc51189b522f64365069285268ff | [
"compra = get_compra_id(id_compra)\nif not compra:\n api.abort(404)\nelse:\n return compra",
"data = request.json\ncompra = update_compra(id_compra, data)\nif not compra:\n api.abort(404)\nelse:\n return compra",
"compra = delete_compra(id_compra)\nif not compra:\n api.abort(404)\nelse:\n retu... | <|body_start_0|>
compra = get_compra_id(id_compra)
if not compra:
api.abort(404)
else:
return compra
<|end_body_0|>
<|body_start_1|>
data = request.json
compra = update_compra(id_compra, data)
if not compra:
api.abort(404)
else... | Compra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compra:
def get(self, id_compra):
"""get a compra given its identifier"""
<|body_0|>
def put(self, id_compra):
"""update a compra given its identifier"""
<|body_1|>
def delete(self, id_compra):
"""delete a compra given its identifier"""
<... | stack_v2_sparse_classes_75kplus_train_001537 | 1,806 | no_license | [
{
"docstring": "get a compra given its identifier",
"name": "get",
"signature": "def get(self, id_compra)"
},
{
"docstring": "update a compra given its identifier",
"name": "put",
"signature": "def put(self, id_compra)"
},
{
"docstring": "delete a compra given its identifier",
... | 3 | stack_v2_sparse_classes_30k_train_022656 | Implement the Python class `Compra` described below.
Class description:
Implement the Compra class.
Method signatures and docstrings:
- def get(self, id_compra): get a compra given its identifier
- def put(self, id_compra): update a compra given its identifier
- def delete(self, id_compra): delete a compra given its ... | Implement the Python class `Compra` described below.
Class description:
Implement the Compra class.
Method signatures and docstrings:
- def get(self, id_compra): get a compra given its identifier
- def put(self, id_compra): update a compra given its identifier
- def delete(self, id_compra): delete a compra given its ... | e3e6d716102280e73932e5eba65b2ff27eec45e0 | <|skeleton|>
class Compra:
def get(self, id_compra):
"""get a compra given its identifier"""
<|body_0|>
def put(self, id_compra):
"""update a compra given its identifier"""
<|body_1|>
def delete(self, id_compra):
"""delete a compra given its identifier"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Compra:
def get(self, id_compra):
"""get a compra given its identifier"""
compra = get_compra_id(id_compra)
if not compra:
api.abort(404)
else:
return compra
def put(self, id_compra):
"""update a compra given its identifier"""
data =... | the_stack_v2_python_sparse | app/main/controller/compra_controller.py | Team-3-TCS/api-my-store | train | 1 | |
12f6fa59b3629c627673e7e4078a8547a6b87181 | [
"env_names = []\nfor env_name in list(external_dccs.keys()):\n env_data = external_dccs[env_name]\n env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))\nreturn env_names",
"if not isinstance(name, str):\n raise TypeError('\"name\" argument in %s.get_env(... | <|body_start_0|>
env_names = []
for env_name in list(external_dccs.keys()):
env_data = external_dccs[env_name]
env_names.append(name_format.replace('%n', env_data['name']).replace('%e', env_data['extensions'][0]))
return env_names
<|end_body_0|>
<|body_start_1|>
... | A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances. | ExternalDCCFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the fo... | stack_v2_sparse_classes_75kplus_train_001538 | 10,666 | permissive | [
{
"docstring": "returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the format of the output variables: %n : the name of the Environment %e : the extension of the Environment :return list: list",
"name": "get_env_names",
"signature": "def get_env_... | 2 | stack_v2_sparse_classes_30k_train_015119 | Implement the Python class `ExternalDCCFactory` described below.
Class description:
A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of DCC names which it is possible to create... | Implement the Python class `ExternalDCCFactory` described below.
Class description:
A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances.
Method signatures and docstrings:
- def get_env_names(cls, name_format='%n'): returns a list of DCC names which it is possible to create... | 7b4cf60cb17f00435ecc3e03d573a9e2d0b44fe0 | <|skeleton|>
class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExternalDCCFactory:
"""A factory for External DCCs. A Factory object for DCCs. Generates :class:`ExternalDCC` instances."""
def get_env_names(cls, name_format='%n'):
"""returns a list of DCC names which it is possible to create one DCC. :param str name_format: A string showing the format of the o... | the_stack_v2_python_sparse | anima/dcc/external.py | eoyilmaz/anima | train | 113 |
270a925b9e09c08294c2a446c3450f625c0f62cb | [
"self.small = []\nself.large = []\nheapq.heapify(self.small)\nheapq.heapify(self.large)",
"min_large = heapq.heappushpop(self.large, num)\nheapq.heappush(self.small, -min_large)\nif len(self.small) > len(self.large):\n heapq.heappush(self.large, -heapq.heappop(self.small))",
"if len(self.large) > len(self.sm... | <|body_start_0|>
self.small = []
self.large = []
heapq.heapify(self.small)
heapq.heapify(self.large)
<|end_body_0|>
<|body_start_1|>
min_large = heapq.heappushpop(self.large, num)
heapq.heappush(self.small, -min_large)
if len(self.small) > len(self.large):
... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_001539 | 1,510 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_020177 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.small = []
self.large = []
heapq.heapify(self.small)
heapq.heapify(self.large)
def addNum(self, num):
""":type num: int :rtype: None"""
min_large = heapq.heappushpop(s... | the_stack_v2_python_sparse | _0295_Find_Median_from_Data_Stream.py | mingweihe/leetcode | train | 3 | |
24324ffa4eec74dc7d46eda2d237b974f6e8e686 | [
"s = specialmanage(self.driver)\ns.open_specialmanage()\nself.assertEqual(s.verify(), True)\ns.modify_obj()\nself.assertEqual(s.sub_tagname(), '企业专业表-修改')\nself.assertEqual(s.company_status(), False)\ns.name_clear()\ns.add_special('Update')\ns.add_save()\nfunction.screenshot(self.driver, 'modify_special_name.jpg')"... | <|body_start_0|>
s = specialmanage(self.driver)
s.open_specialmanage()
self.assertEqual(s.verify(), True)
s.modify_obj()
self.assertEqual(s.sub_tagname(), '企业专业表-修改')
self.assertEqual(s.company_status(), False)
s.name_clear()
s.add_special('Update')
... | Test041_Special_Modify_P1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test041_Special_Modify_P1:
def test_modify_name(self):
"""修改专业名"""
<|body_0|>
def test_back(self):
"""修改专业并返回"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = specialmanage(self.driver)
s.open_specialmanage()
self.assertEqual(s.ve... | stack_v2_sparse_classes_75kplus_train_001540 | 1,131 | no_license | [
{
"docstring": "修改专业名",
"name": "test_modify_name",
"signature": "def test_modify_name(self)"
},
{
"docstring": "修改专业并返回",
"name": "test_back",
"signature": "def test_back(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021049 | Implement the Python class `Test041_Special_Modify_P1` described below.
Class description:
Implement the Test041_Special_Modify_P1 class.
Method signatures and docstrings:
- def test_modify_name(self): 修改专业名
- def test_back(self): 修改专业并返回 | Implement the Python class `Test041_Special_Modify_P1` described below.
Class description:
Implement the Test041_Special_Modify_P1 class.
Method signatures and docstrings:
- def test_modify_name(self): 修改专业名
- def test_back(self): 修改专业并返回
<|skeleton|>
class Test041_Special_Modify_P1:
def test_modify_name(self):... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test041_Special_Modify_P1:
def test_modify_name(self):
"""修改专业名"""
<|body_0|>
def test_back(self):
"""修改专业并返回"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test041_Special_Modify_P1:
def test_modify_name(self):
"""修改专业名"""
s = specialmanage(self.driver)
s.open_specialmanage()
self.assertEqual(s.verify(), True)
s.modify_obj()
self.assertEqual(s.sub_tagname(), '企业专业表-修改')
self.assertEqual(s.company_status(), ... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_Special/Test041_special_modify_P1.py | rrmiracle/GlxssLive | train | 0 | |
c01ddf1193a1d44a0a89c05efc524b313f967a8b | [
"if len(nums) < 2:\n return []\ni, j = (0, len(nums) - 1)\nresult = []\nunique_num = []\nwhile i < j:\n sum = nums[i] + nums[j]\n if sum > target:\n j -= 1\n elif sum < target:\n i += 1\n elif nums[i] in unique_num:\n i += 1\n else:\n result.append([nums[i], nums[j]])\n... | <|body_start_0|>
if len(nums) < 2:
return []
i, j = (0, len(nums) - 1)
result = []
unique_num = []
while i < j:
sum = nums[i] + nums[j]
if sum > target:
j -= 1
elif sum < target:
i += 1
el... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]"""
<|body_0|>
def threeSum(self, nums, target):
"""... | stack_v2_sparse_classes_75kplus_train_001541 | 3,912 | no_license | [
{
"docstring": ":param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":param nums: :param targ... | 3 | stack_v2_sparse_classes_30k_train_004993 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1,... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]"""
<|body_0|>
def threeSum(self, nums, target):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], 0) [[-1, 1], [0, 0]] >>> s.twoSum([-2, -2, -2, -1, 0, 0 ,1], -2) [[-2, 0]]"""
if len(nums) < 2:
return []
i, j = (0, len(nums) - 1)
... | the_stack_v2_python_sparse | 4sum.py | gsy/leetcode | train | 1 | |
d2328f8b7d64c21a461b3abfaff5f48f32412ec7 | [
"refresh_django_db_connection()\njob = Job.objects.get(pk=int(kwargs['job_id']))\njob_track = JobTrack(job_id=job.id)\njob_track.save()\ninput_job = Job.objects.get(pk=int(kwargs['input_job_id']))\nbounds = get_job_db_bounds(input_job)\nsqldf = spark.read.jdbc(settings.COMBINE_DATABASE['jdbc_url'], 'core_record', p... | <|body_start_0|>
refresh_django_db_connection()
job = Job.objects.get(pk=int(kwargs['job_id']))
job_track = JobTrack(job_id=job.id)
job_track.save()
input_job = Job.objects.get(pk=int(kwargs['input_job_id']))
bounds = get_job_db_bounds(input_job)
sqldf = spark.rea... | Spark code for Transform jobs | TransformSpark | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformSpark:
"""Spark code for Transform jobs"""
def spark_function(spark, **kwargs):
"""Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs: job_id (int): Job ID job_input (str): location of avro f... | stack_v2_sparse_classes_75kplus_train_001542 | 28,601 | permissive | [
{
"docstring": "Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs: job_id (int): Job ID job_input (str): location of avro files on disk transformation_id (str): id of Transformation Scenario index_mapper (str): class name from ... | 3 | stack_v2_sparse_classes_30k_val_001530 | Implement the Python class `TransformSpark` described below.
Class description:
Spark code for Transform jobs
Method signatures and docstrings:
- def spark_function(spark, **kwargs): Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs:... | Implement the Python class `TransformSpark` described below.
Class description:
Spark code for Transform jobs
Method signatures and docstrings:
- def spark_function(spark, **kwargs): Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs:... | d3a35783f008b8665030d49c61d41de7b07a342d | <|skeleton|>
class TransformSpark:
"""Spark code for Transform jobs"""
def spark_function(spark, **kwargs):
"""Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs: job_id (int): Job ID job_input (str): location of avro f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformSpark:
"""Spark code for Transform jobs"""
def spark_function(spark, **kwargs):
"""Transform records based on Transformation Scenario. Args: spark (pyspark.sql.session.SparkSession): provided by pyspark context kwargs: job_id (int): Job ID job_input (str): location of avro files on disk ... | the_stack_v2_python_sparse | core/spark/jobs.py | blancoj/combine | train | 0 |
abc4e4ef09fd4da1cc6df66a3f00982d0f022ea4 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.independent_set = dict(((node, False) for node in self.graph.iternodes()))\nself.cardinality = 0\nse... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise ValueError('a loop detected')
self.independent_set = dict(((node, False) ... | Find a maximal independent set. | UnorderedSequentialIndependentSet3 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_001543 | 3,887 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032653 | Implement the Python class `UnorderedSequentialIndependentSet3` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `UnorderedSequentialIndependentSet3` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>
class UnorderedSequentialI... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
... | the_stack_v2_python_sparse | graphtheory/independentsets/isetus.py | kgashok/graphs-dict | train | 0 |
a3514ffc12c733a8ad002fb98ad24e13115460e3 | [
"action = 'ill-brwreq-patron-loan-extension-request'\npermissions = current_app.config['ILS_VIEWS_PERMISSIONS_FACTORY']\nview_permission = permissions(action)\nreturn view_permission(record)",
"self.loader()\nself.validate_loan(record)\nrecord.patron_loan.extension.request()\nrecord.commit()\ndb.session.commit()\... | <|body_start_0|>
action = 'ill-brwreq-patron-loan-extension-request'
permissions = current_app.config['ILS_VIEWS_PERMISSIONS_FACTORY']
view_permission = permissions(action)
return view_permission(record)
<|end_body_0|>
<|body_start_1|>
self.loader()
self.validate_loan(re... | Request extensions endpoint. | RequestPatronLoanExtensionResource | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestPatronLoanExtensionResource:
"""Request extensions endpoint."""
def request_extension_permission_factory(self, record):
"""Request extension permission factory."""
<|body_0|>
def post(self, pid, record, **kwargs):
"""Request extension action implementation... | stack_v2_sparse_classes_75kplus_train_001544 | 6,621 | permissive | [
{
"docstring": "Request extension permission factory.",
"name": "request_extension_permission_factory",
"signature": "def request_extension_permission_factory(self, record)"
},
{
"docstring": "Request extension action implementation.",
"name": "post",
"signature": "def post(self, pid, re... | 2 | stack_v2_sparse_classes_30k_train_012954 | Implement the Python class `RequestPatronLoanExtensionResource` described below.
Class description:
Request extensions endpoint.
Method signatures and docstrings:
- def request_extension_permission_factory(self, record): Request extension permission factory.
- def post(self, pid, record, **kwargs): Request extension ... | Implement the Python class `RequestPatronLoanExtensionResource` described below.
Class description:
Request extensions endpoint.
Method signatures and docstrings:
- def request_extension_permission_factory(self, record): Request extension permission factory.
- def post(self, pid, record, **kwargs): Request extension ... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class RequestPatronLoanExtensionResource:
"""Request extensions endpoint."""
def request_extension_permission_factory(self, record):
"""Request extension permission factory."""
<|body_0|>
def post(self, pid, record, **kwargs):
"""Request extension action implementation... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequestPatronLoanExtensionResource:
"""Request extensions endpoint."""
def request_extension_permission_factory(self, record):
"""Request extension permission factory."""
action = 'ill-brwreq-patron-loan-extension-request'
permissions = current_app.config['ILS_VIEWS_PERMISSIONS_FA... | the_stack_v2_python_sparse | invenio_app_ils/ill/views.py | inveniosoftware/invenio-app-ils | train | 64 |
231b9c86fcad9a224466518886a8356e98813ff4 | [
"for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.proper_dividers_list, arg)\nfor arg, val in self.proper_dividers_values:\n self.assertEqual(prev1.proper_dividers_list(arg), val)",
"for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.proper_dividers_fun, arg)\n... | <|body_start_0|>
for arg in self.non_number_values:
self.assertRaises(TypeError, prev1.proper_dividers_list, arg)
for arg, val in self.proper_dividers_values:
self.assertEqual(prev1.proper_dividers_list(arg), val)
<|end_body_0|>
<|body_start_1|>
for arg in self.non_numbe... | TestProperDividers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProperDividers:
def test_proper_dividers_list(self):
"""Testing proper_dividers_list function"""
<|body_0|>
def test_proper_dividers_fun(self):
"""Testing proper_dividers_fun function"""
<|body_1|>
def test_proper_dividers_map(self):
"""Testi... | stack_v2_sparse_classes_75kplus_train_001545 | 8,451 | no_license | [
{
"docstring": "Testing proper_dividers_list function",
"name": "test_proper_dividers_list",
"signature": "def test_proper_dividers_list(self)"
},
{
"docstring": "Testing proper_dividers_fun function",
"name": "test_proper_dividers_fun",
"signature": "def test_proper_dividers_fun(self)"
... | 4 | stack_v2_sparse_classes_30k_train_008754 | Implement the Python class `TestProperDividers` described below.
Class description:
Implement the TestProperDividers class.
Method signatures and docstrings:
- def test_proper_dividers_list(self): Testing proper_dividers_list function
- def test_proper_dividers_fun(self): Testing proper_dividers_fun function
- def te... | Implement the Python class `TestProperDividers` described below.
Class description:
Implement the TestProperDividers class.
Method signatures and docstrings:
- def test_proper_dividers_list(self): Testing proper_dividers_list function
- def test_proper_dividers_fun(self): Testing proper_dividers_fun function
- def te... | 0cd4bbe3feb63b248d643303433f9fb2fc2def79 | <|skeleton|>
class TestProperDividers:
def test_proper_dividers_list(self):
"""Testing proper_dividers_list function"""
<|body_0|>
def test_proper_dividers_fun(self):
"""Testing proper_dividers_fun function"""
<|body_1|>
def test_proper_dividers_map(self):
"""Testi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProperDividers:
def test_proper_dividers_list(self):
"""Testing proper_dividers_list function"""
for arg in self.non_number_values:
self.assertRaises(TypeError, prev1.proper_dividers_list, arg)
for arg, val in self.proper_dividers_values:
self.assertEqual(pr... | the_stack_v2_python_sparse | Python - advanced course/Solutions/9/9.1.py | maxymilianz/CS-at-University-of-Wroclaw | train | 0 | |
cd36b10f73e74d82c3b5a7486b1da0353763443a | [
"if self.extra_reason_visible:\n tmp_reason = self.extra_reason\nelse:\n tmp_reason = self.reason.reason\nself.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_train': self.cur_train.id, 'start_date': self.start_date, 'end_date': self.end_date, 'type': 'detain'})",
"extra_reason... | <|body_start_0|>
if self.extra_reason_visible:
tmp_reason = self.extra_reason
else:
tmp_reason = self.reason.reason
self.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_train': self.cur_train.id, 'start_date': self.start_date, 'end_date': sel... | 扣车向导 | DetainWizard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
<|body_0|>
def on_change_reason(self):
"""改变扣车原因,如果是其它的话则显示extra_reason :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.extra_reason_visible:
tmp_reason... | stack_v2_sparse_classes_75kplus_train_001546 | 1,700 | no_license | [
{
"docstring": "点击确定按扭 :return:",
"name": "on_ok",
"signature": "def on_ok(self)"
},
{
"docstring": "改变扣车原因,如果是其它的话则显示extra_reason :return:",
"name": "on_change_reason",
"signature": "def on_change_reason(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016876 | Implement the Python class `DetainWizard` described below.
Class description:
扣车向导
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭 :return:
- def on_change_reason(self): 改变扣车原因,如果是其它的话则显示extra_reason :return: | Implement the Python class `DetainWizard` described below.
Class description:
扣车向导
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭 :return:
- def on_change_reason(self): 改变扣车原因,如果是其它的话则显示extra_reason :return:
<|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
<|body_0|>
def on_change_reason(self):
"""改变扣车原因,如果是其它的话则显示extra_reason :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
if self.extra_reason_visible:
tmp_reason = self.extra_reason
else:
tmp_reason = self.reason.reason
self.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_tra... | the_stack_v2_python_sparse | mdias_addons/metro_park_dispatch/models/detain_wizard.py | rezaghanimi/main_mdias | train | 0 |
c7482a4492bc592cc99600fee56a50122fb06b53 | [
"self.kw = kwargs\nStep.__init__(self, *args, routine=routine, **kwargs)\nramsey_settings = self.parse_settings(self.get_requested_settings())\nqbcal.Ramsey.__init__(self, dev=self.dev, **ramsey_settings)",
"kwargs = {}\ntask_list = []\nfor qb in self.qubits:\n task = {}\n task_list_fields = requested_kwarg... | <|body_start_0|>
self.kw = kwargs
Step.__init__(self, *args, routine=routine, **kwargs)
ramsey_settings = self.parse_settings(self.get_requested_settings())
qbcal.Ramsey.__init__(self, dev=self.dev, **ramsey_settings)
<|end_body_0|>
<|body_start_1|>
kwargs = {}
task_list... | A wrapper class for the Ramsey experiment. | RamseyStep | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RamseyStep:
"""A wrapper class for the Ramsey experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step obj): The parent routine Keyword args: qubits (list): list ... | stack_v2_sparse_classes_75kplus_train_001547 | 48,290 | permissive | [
{
"docstring": "Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step obj): The parent routine Keyword args: qubits (list): list of qubits to be used in the routine Configuration parameters (coming from the configuration parameter dictionary): transit... | 4 | stack_v2_sparse_classes_30k_train_007296 | Implement the Python class `RamseyStep` described below.
Class description:
A wrapper class for the Ramsey experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step ob... | Implement the Python class `RamseyStep` described below.
Class description:
A wrapper class for the Ramsey experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step ob... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class RamseyStep:
"""A wrapper class for the Ramsey experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step obj): The parent routine Keyword args: qubits (list): list ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RamseyStep:
"""A wrapper class for the Ramsey experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the RamseyStep class, which also includes initialization of the Ramsey experiment. Args: routine (Step obj): The parent routine Keyword args: qubits (list): list of qubits to ... | the_stack_v2_python_sparse | pycqed/measurement/calibration/automatic_calibration_routines/single_qubit_routines.py | QudevETH/PycQED_py3 | train | 8 |
522efc8c6d716b76948af5d53de41281166899b3 | [
"self.capacity = size\nself.size = 0\nself.queue = deque()\nself.total = 0",
"if self.size < self.capacity:\n self.queue.appendleft(val)\n self.total += val\n self.size += 1\n return self.total / self.size\nelse:\n p = self.queue.pop()\n self.total -= p\n self.queue.appendleft(val)\n self.... | <|body_start_0|>
self.capacity = size
self.size = 0
self.queue = deque()
self.total = 0
<|end_body_0|>
<|body_start_1|>
if self.size < self.capacity:
self.queue.appendleft(val)
self.total += val
self.size += 1
return self.total / s... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.capacity = size
self.siz... | stack_v2_sparse_classes_75kplus_train_001548 | 1,005 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003156 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | f38b598a925ea1c701d44b276749b8254a44974f | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.capacity = size
self.size = 0
self.queue = deque()
self.total = 0
def next(self, val):
""":type val: int :rtype: float"""
if self.size < self.ca... | the_stack_v2_python_sparse | python/moving_average_of_a_data_stream.py | soumasish/leetcodely | train | 10 | |
40a83769de0788500025c30a4d22b458ecd0eb31 | [
"if ExecutorFactory._instance is None:\n max_workers = ExecutorFactory.max_workers()\n ExecutorFactory._instance = ThreadPoolExecutor(max_workers=max_workers)\nreturn ExecutorFactory._instance",
"config = Config()\nval = config.config.get('max-workers')\nif val is None:\n return None\ntry:\n return in... | <|body_start_0|>
if ExecutorFactory._instance is None:
max_workers = ExecutorFactory.max_workers()
ExecutorFactory._instance = ThreadPoolExecutor(max_workers=max_workers)
return ExecutorFactory._instance
<|end_body_0|>
<|body_start_1|>
config = Config()
val = con... | ExecutorFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutorFactory:
def get_or_create() -> Executor:
"""Return the same executor in each call."""
<|body_0|>
def max_workers() -> Optional[int]:
"""Return the max number of workers configured."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Executor... | stack_v2_sparse_classes_75kplus_train_001549 | 1,829 | permissive | [
{
"docstring": "Return the same executor in each call.",
"name": "get_or_create",
"signature": "def get_or_create() -> Executor"
},
{
"docstring": "Return the max number of workers configured.",
"name": "max_workers",
"signature": "def max_workers() -> Optional[int]"
}
] | 2 | null | Implement the Python class `ExecutorFactory` described below.
Class description:
Implement the ExecutorFactory class.
Method signatures and docstrings:
- def get_or_create() -> Executor: Return the same executor in each call.
- def max_workers() -> Optional[int]: Return the max number of workers configured. | Implement the Python class `ExecutorFactory` described below.
Class description:
Implement the ExecutorFactory class.
Method signatures and docstrings:
- def get_or_create() -> Executor: Return the same executor in each call.
- def max_workers() -> Optional[int]: Return the max number of workers configured.
<|skelet... | c9ce6a123b49c1c4e5bd950b388d69e6ff849b5d | <|skeleton|>
class ExecutorFactory:
def get_or_create() -> Executor:
"""Return the same executor in each call."""
<|body_0|>
def max_workers() -> Optional[int]:
"""Return the max number of workers configured."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExecutorFactory:
def get_or_create() -> Executor:
"""Return the same executor in each call."""
if ExecutorFactory._instance is None:
max_workers = ExecutorFactory.max_workers()
ExecutorFactory._instance = ThreadPoolExecutor(max_workers=max_workers)
return Execut... | the_stack_v2_python_sparse | python/pyiceberg/utils/concurrent.py | apache/iceberg | train | 4,358 | |
493dec1c31ec298c00c77ebc95713a1444c2314f | [
"if request.COOKIES.get('site_language'):\n if request.COOKIES['site_language'] == '':\n language = 'fr'\n else:\n language = request.COOKIES['site_language']\n translation.activate(language)\n request.LANGUAGE_CODE = translation.get_language()",
"if not request.COOKIES.get('site_languag... | <|body_start_0|>
if request.COOKIES.get('site_language'):
if request.COOKIES['site_language'] == '':
language = 'fr'
else:
language = request.COOKIES['site_language']
translation.activate(language)
request.LANGUAGE_CODE = translatio... | LanguageCookieMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
<|body_0|>
def process_response(self, request, response):
"""Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/130312... | stack_v2_sparse_classes_75kplus_train_001550 | 1,353 | no_license | [
{
"docstring": "Sets language from the cookie value.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/13031239/388835 )",
"name": "process_response"... | 2 | stack_v2_sparse_classes_30k_train_040655 | Implement the Python class `LanguageCookieMiddleware` described below.
Class description:
Implement the LanguageCookieMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Sets language from the cookie value.
- def process_response(self, request, response): Create cookie if not the... | Implement the Python class `LanguageCookieMiddleware` described below.
Class description:
Implement the LanguageCookieMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Sets language from the cookie value.
- def process_response(self, request, response): Create cookie if not the... | d5aff19e4557fe1eb9e0765e40337df99d5e1935 | <|skeleton|>
class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
<|body_0|>
def process_response(self, request, response):
"""Create cookie if not there already. Also deactivates language. (See http://stackoverflow.com/a/130312... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LanguageCookieMiddleware:
def process_request(self, request):
"""Sets language from the cookie value."""
if request.COOKIES.get('site_language'):
if request.COOKIES['site_language'] == '':
language = 'fr'
else:
language = request.COOKIES[... | the_stack_v2_python_sparse | visualexpcode/visualexpcode/middleware/languages/language_cookie.py | mlemaire79/visualexp | train | 0 | |
3ef2fa290d4c27dcd1517c1dbad1356382573242 | [
"super().__init__(config)\nself.collector_host = config.get('collector_host')\nself.schedds = config.get('schedds', [None])\nself.condor_config = config.get('condor_config')\nself.constraint = config.get('constraint', True)\nself.classad_attrs = config.get('classad_attrs')\nself.correction_map = config.get('correct... | <|body_start_0|>
super().__init__(config)
self.collector_host = config.get('collector_host')
self.schedds = config.get('schedds', [None])
self.condor_config = config.get('condor_config')
self.constraint = config.get('constraint', True)
self.classad_attrs = config.get('cla... | JobQ | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001551 | 3,265 | permissive | [
{
"docstring": "In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs.",
"name": "__init__",
"signature": "def __init__(self, config... | 2 | stack_v2_sparse_classes_30k_train_037484 | Implement the Python class `JobQ` described below.
Class description:
Implement the JobQ class.
Method signatures and docstrings:
- def __init__(self, config): In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values... | Implement the Python class `JobQ` described below.
Class description:
Implement the JobQ class.
Method signatures and docstrings:
- def __init__(self, config): In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values... | 842fdc91a31879084906d71a7d0c317e5035a925 | <|skeleton|>
class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobQ:
def __init__(self, config):
"""In config files such as job_classification.jsonnet or Nersc.jsonnet, put a dictionary named correction_map with keys corresponding to classad_attrs and values that the operators want to be default values for the classad_attrs."""
super().__init__(config)
... | the_stack_v2_python_sparse | src/decisionengine_modules/htcondor/sources/job_q.py | HEPCloud/decisionengine_modules | train | 2 | |
6b6520fb80abd49a50a2d1fe13f9eb7d36e8cd54 | [
"value = None\nfor p in self.property:\n if p.name == name:\n value = p.value\n break\nreturn value",
"found = False\nfor i in range(len(self.property)):\n if self.property[i].name == name:\n self.property[i].value = value\n found = True\n break\nif not found:\n self.pr... | <|body_start_0|>
value = None
for p in self.property:
if p.name == name:
value = p.value
break
return value
<|end_body_0|>
<|body_start_1|>
found = False
for i in range(len(self.property)):
if self.property[i].name == name:... | Represents a generic entry in object form. | AppsPropertyEntry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppsPropertyEntry:
"""Represents a generic entry in object form."""
def _GetProperty(self, name):
"""Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name w... | stack_v2_sparse_classes_75kplus_train_001552 | 1,921 | permissive | [
{
"docstring": "Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name was invalid.",
"name": "_GetProperty",
"signature": "def _GetProperty(self, name)"
},
{
"docstring... | 2 | null | Implement the Python class `AppsPropertyEntry` described below.
Class description:
Represents a generic entry in object form.
Method signatures and docstrings:
- def _GetProperty(self, name): Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:... | Implement the Python class `AppsPropertyEntry` described below.
Class description:
Represents a generic entry in object form.
Method signatures and docstrings:
- def _GetProperty(self, name): Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:... | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | <|skeleton|>
class AppsPropertyEntry:
"""Represents a generic entry in object form."""
def _GetProperty(self, name):
"""Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppsPropertyEntry:
"""Represents a generic entry in object form."""
def _GetProperty(self, name):
"""Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name was invalid.""... | the_stack_v2_python_sparse | python3-alpha/python-libs/gdata/apps/apps_property_entry.py | kuri65536/python-for-android | train | 280 |
33684d71c7d1159b255c60d12c74aa03f8e028b0 | [
"self.s3_output_path = s3_output_path\nself.container_local_output_path = container_local_output_path\nself.hook_parameters = hook_parameters\nself.collection_configs = collection_configs",
"debugger_hook_config_request = {'S3OutputPath': self.s3_output_path}\nif self.container_local_output_path is not None:\n ... | <|body_start_0|>
self.s3_output_path = s3_output_path
self.container_local_output_path = container_local_output_path
self.hook_parameters = hook_parameters
self.collection_configs = collection_configs
<|end_body_0|>
<|body_start_1|>
debugger_hook_config_request = {'S3OutputPath'... | Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/awslabs/sagemaker-debugger/blob/master/docs/ a... | DebuggerHookConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/... | stack_v2_sparse_classes_75kplus_train_001553 | 42,015 | permissive | [
{
"docstring": "Initialize the DebuggerHookConfig instance. Args: s3_output_path (str or PipelineVariable): Optional. The location in Amazon S3 to store the output tensors. The default Debugger output path is created under the default output path of the :class:`~sagemaker.estimator.Estimator` class. For example... | 2 | stack_v2_sparse_classes_30k_train_019237 | Implement the Python class `DebuggerHookConfig` described below.
Class description:
Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `... | Implement the Python class `DebuggerHookConfig` described below.
Class description:
Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DebuggerHookConfig:
"""Create a Debugger hook configuration object to save the tensor for debugging. DebuggerHookConfig provides options to customize how debugging information is emitted and saved. This high-level DebuggerHookConfig class runs based on the `smdebug.SaveConfig <https://github.com/awslabs/sagem... | the_stack_v2_python_sparse | src/sagemaker/debugger/debugger.py | aws/sagemaker-python-sdk | train | 2,050 |
743ec0f5efa603002d9e45b1993bd523adf56d43 | [
"super(CustomResNet152, self).__init__()\nself.dim = dim\nresnet = torchvision.models.resnet152(pretrained=True)\nmodules = list(resnet.children())[:-2]\nself.resnet = nn.Sequential(*modules)\nself.conv = nn.Conv2d(2048, self.dim, kernel_size=(1, 1), stride=(1, 1), bias=False)\nif train_resnet:\n for i, child in... | <|body_start_0|>
super(CustomResNet152, self).__init__()
self.dim = dim
resnet = torchvision.models.resnet152(pretrained=True)
modules = list(resnet.children())[:-2]
self.resnet = nn.Sequential(*modules)
self.conv = nn.Conv2d(2048, self.dim, kernel_size=(1, 1), stride=(1,... | Image encoder that computes both its image embedding and its convolutional feature map | CustomResNet152 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets bac... | stack_v2_sparse_classes_75kplus_train_001554 | 20,277 | no_license | [
{
"docstring": "Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets backbone's weights as trainable if true",
"name": "__init__",
"signature": "def __init__(self, dim=1024, train_resnet=False)"
},
{
"docstring": "Forward pass of t... | 2 | stack_v2_sparse_classes_30k_train_019109 | Implement the Python class `CustomResNet152` described below.
Class description:
Image encoder that computes both its image embedding and its convolutional feature map
Method signatures and docstrings:
- def __init__(self, dim=1024, train_resnet=False): Initializes image encoder based on ResNet :param dim: length of ... | Implement the Python class `CustomResNet152` described below.
Class description:
Image encoder that computes both its image embedding and its convolutional feature map
Method signatures and docstrings:
- def __init__(self, dim=1024, train_resnet=False): Initializes image encoder based on ResNet :param dim: length of ... | bc4fe571775e982975d6ecac82253e94de9dcd2b | <|skeleton|>
class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets bac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets backbone's weigh... | the_stack_v2_python_sparse | models/univse/model.py | strategist922/UniVSE | train | 0 |
b01661eb5ae09695bd75c0cd61a39b1516dc5c48 | [
"super().__init__(coordinator=coordinator)\nself._attr_name = f'{coordinator.data.info.name} Wi-Fi Channel'\nself._attr_unique_id = f'{coordinator.data.info.mac_address}_wifi_channel'",
"if not self.coordinator.data.info.wifi:\n return None\nreturn self.coordinator.data.info.wifi.channel"
] | <|body_start_0|>
super().__init__(coordinator=coordinator)
self._attr_name = f'{coordinator.data.info.name} Wi-Fi Channel'
self._attr_unique_id = f'{coordinator.data.info.mac_address}_wifi_channel'
<|end_body_0|>
<|body_start_1|>
if not self.coordinator.data.info.wifi:
retur... | Defines a WLED Wi-Fi Channel sensor. | WLEDWifiChannelSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WLEDWifiChannelSensor:
"""Defines a WLED Wi-Fi Channel sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi Channel sensor."""
<|body_0|>
def state(self) -> int | None:
"""Return the state of the sensor."""
... | stack_v2_sparse_classes_75kplus_train_001555 | 6,830 | permissive | [
{
"docstring": "Initialize WLED Wi-Fi Channel sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "state",
"signature": "def state(self) -> int | None"
}
] | 2 | null | Implement the Python class `WLEDWifiChannelSensor` described below.
Class description:
Defines a WLED Wi-Fi Channel sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: Initialize WLED Wi-Fi Channel sensor.
- def state(self) -> int | None: Return the state of... | Implement the Python class `WLEDWifiChannelSensor` described below.
Class description:
Defines a WLED Wi-Fi Channel sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: Initialize WLED Wi-Fi Channel sensor.
- def state(self) -> int | None: Return the state of... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class WLEDWifiChannelSensor:
"""Defines a WLED Wi-Fi Channel sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi Channel sensor."""
<|body_0|>
def state(self) -> int | None:
"""Return the state of the sensor."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WLEDWifiChannelSensor:
"""Defines a WLED Wi-Fi Channel sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi Channel sensor."""
super().__init__(coordinator=coordinator)
self._attr_name = f'{coordinator.data.info.name} Wi-Fi Channe... | the_stack_v2_python_sparse | homeassistant/components/wled/sensor.py | BenWoodford/home-assistant | train | 11 |
de8e0ba92c1c3349519a69f6900044727f35e11c | [
"command = command.split(' ')\nprocess = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ntry:\n output, errors = process.communicate(timeout=8)\n output = output.split('\\n')\n process.terminate()\nexcept subprocess.TimeoutExpired:\n process.kill()\n ... | <|body_start_0|>
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
output, errors = process.communicate(timeout=8)
output = output.split('\n')
process.terminate()
... | Commands that evaluate commands.. | Evaluation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_001556 | 2,006 | permissive | [
{
"docstring": "Execute a system command. Bot owner only.",
"name": "sh",
"signature": "async def sh(self, ctx, *, command)"
},
{
"docstring": "Evaluate a Python expression. Bot owner only.",
"name": "_eval",
"signature": "async def _eval(self, ctx, *, expression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031058 | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only. | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only.
<... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | the_stack_v2_python_sparse | cogs/eval.py | sokcheng/Kitsuchan-NG | train | 1 |
96724c43d250e93473a694c17134e1c7a1248d04 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MicrosoftAuthenticatorAuthenticationMethodConfiguration()",
"from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .microsoft_authenticator_authentication_method_target import MicrosoftAuthenticatorAu... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MicrosoftAuthenticatorAuthenticationMethodConfiguration()
<|end_body_0|>
<|body_start_1|>
from .authentication_method_configuration import AuthenticationMethodConfiguration
from .microso... | MicrosoftAuthenticatorAuthenticationMethodConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | stack_v2_sparse_classes_75kplus_train_001557 | 4,083 | 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: MicrosoftAuthenticatorAuthenticationMethodConfiguration",
"name": "create_from_discriminator_value",
"signat... | 3 | stack_v2_sparse_classes_30k_train_020623 | Implement the Python class `MicrosoftAuthenticatorAuthenticationMethodConfiguration` described below.
Class description:
Implement the MicrosoftAuthenticatorAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Microso... | Implement the Python class `MicrosoftAuthenticatorAuthenticationMethodConfiguration` described below.
Class description:
Implement the MicrosoftAuthenticatorAuthenticationMethodConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Microso... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MicrosoftAuthenticatorAuthenticationMethodConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MicrosoftAuthenticatorAuthenticationMethodConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | the_stack_v2_python_sparse | msgraph/generated/models/microsoft_authenticator_authentication_method_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4a3d25c7358022048e0f534ec908b5337c91dbe5 | [
"self.config: Dict[str, str] = {}\nself.config[AcnNodeConfig.KEY] = key\nself.config[AcnNodeConfig.URI] = uri\nself.config[AcnNodeConfig.EXTERNAL_URI] = external_uri if external_uri is not None else ''\nself.config[AcnNodeConfig.DELEGATE_URI] = delegate_uri if delegate_uri is not None else ''\nself.config[AcnNodeCo... | <|body_start_0|>
self.config: Dict[str, str] = {}
self.config[AcnNodeConfig.KEY] = key
self.config[AcnNodeConfig.URI] = uri
self.config[AcnNodeConfig.EXTERNAL_URI] = external_uri if external_uri is not None else ''
self.config[AcnNodeConfig.DELEGATE_URI] = delegate_uri if delegat... | Store the configuration of an acn node as a dictionary. | AcnNodeConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=No... | stack_v2_sparse_classes_75kplus_train_001558 | 12,337 | permissive | [
{
"docstring": "Initialize a new ACN configuration from arguments :param key: node private key to use as identity :param uri: node local uri to bind to :param external_uri: node external uri, needed to be reached by others :param delegate_uri: node local uri for delegate service :param monitoring_uri: node moni... | 6 | stack_v2_sparse_classes_30k_train_043900 | Implement the Python class `AcnNodeConfig` described below.
Class description:
Store the configuration of an acn node as a dictionary.
Method signatures and docstrings:
- def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entr... | Implement the Python class `AcnNodeConfig` described below.
Class description:
Store the configuration of an acn node as a dictionary.
Method signatures and docstrings:
- def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entr... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=None, enable_ch... | the_stack_v2_python_sparse | scripts/acn/run_acn_node_standalone.py | fetchai/agents-aea | train | 192 |
8d55432595119e744136dfda5a3d5ae2904c185f | [
"self._is_string = False\nif isinstance(yaml, str):\n self._is_string = True\n self.name: str = yaml\n self.remote: Optional[str] = None\n self.source: Optional[Union[Source, SourceName]] = None\n return\nif isinstance(yaml, dict):\n self.name: str = yaml['name']\n self.remote: Optional[str] = ... | <|body_start_0|>
self._is_string = False
if isinstance(yaml, str):
self._is_string = True
self.name: str = yaml
self.remote: Optional[str] = None
self.source: Optional[Union[Source, SourceName]] = None
return
if isinstance(yaml, dict):
... | clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name | Upstream | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upstream:
"""clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name"""
def __init__(self, yaml: Union[str, dict]):
"""Upst... | stack_v2_sparse_classes_75kplus_train_001559 | 2,529 | permissive | [
{
"docstring": "Upstream __init__ :param Union[str, dict] yaml: Parsed YAML python object for upstream :raise UnknownTypeError:",
"name": "__init__",
"signature": "def __init__(self, yaml: Union[str, dict])"
},
{
"docstring": "Return python object representation for saving yaml :return: YAML pyt... | 2 | null | Implement the Python class `Upstream` described below.
Class description:
clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name
Method signatures and docst... | Implement the Python class `Upstream` described below.
Class description:
clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name
Method signatures and docst... | 1438fc8b1bb7379de66142ffcb0e20b459b59159 | <|skeleton|>
class Upstream:
"""clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name"""
def __init__(self, yaml: Union[str, dict]):
"""Upst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Upstream:
"""clowder yaml Upstream model class :ivar str name: Upstream name :ivar str path: Project relative path :ivar Optional[Union[Source, SourceName]] source: Upstream source :ivar Optional[str] remote: Upstream remote name"""
def __init__(self, yaml: Union[str, dict]):
"""Upstream __init__... | the_stack_v2_python_sparse | clowder/model/upstream.py | JrGoodle/clowder | train | 17 |
41ad54bb7b8cfa539ea60b1d428ce515f58d3a2b | [
"self.P = P\nself.K = None\nself.R = None\nself.t = None\nself.c = None",
"x = dot(self.P, X)\nfor i in range(3):\n x[i] /= x[2]\nreturn x",
"R = eye(4)\nR[:3, :3] = expm([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])\nreturn R",
"K, R = rq(self.P[:, :3])\nT = diag(sign(diag(K)))\nif det(T) < 0:\n... | <|body_start_0|>
self.P = P
self.K = None
self.R = None
self.t = None
self.c = None
<|end_body_0|>
<|body_start_1|>
x = dot(self.P, X)
for i in range(3):
x[i] /= x[2]
return x
<|end_body_1|>
<|body_start_2|>
R = eye(4)
R[:3, :... | Class for representing pin-hole cameras. | Camera | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
"""Class for representing pin-hole cameras."""
def __init__(self, P):
"""Initialize P = K[R|t] camera model."""
<|body_0|>
def project(self, X):
"""Project points in X (4*n array) and normalize coordinates."""
<|body_1|>
def rotation_matrix(a... | stack_v2_sparse_classes_75kplus_train_001560 | 3,354 | no_license | [
{
"docstring": "Initialize P = K[R|t] camera model.",
"name": "__init__",
"signature": "def __init__(self, P)"
},
{
"docstring": "Project points in X (4*n array) and normalize coordinates.",
"name": "project",
"signature": "def project(self, X)"
},
{
"docstring": "Creates a 3D ro... | 5 | null | Implement the Python class `Camera` described below.
Class description:
Class for representing pin-hole cameras.
Method signatures and docstrings:
- def __init__(self, P): Initialize P = K[R|t] camera model.
- def project(self, X): Project points in X (4*n array) and normalize coordinates.
- def rotation_matrix(a): C... | Implement the Python class `Camera` described below.
Class description:
Class for representing pin-hole cameras.
Method signatures and docstrings:
- def __init__(self, P): Initialize P = K[R|t] camera model.
- def project(self, X): Project points in X (4*n array) and normalize coordinates.
- def rotation_matrix(a): C... | b76292758d7792635cd2ca93b7d7416438a5a72c | <|skeleton|>
class Camera:
"""Class for representing pin-hole cameras."""
def __init__(self, P):
"""Initialize P = K[R|t] camera model."""
<|body_0|>
def project(self, X):
"""Project points in X (4*n array) and normalize coordinates."""
<|body_1|>
def rotation_matrix(a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Camera:
"""Class for representing pin-hole cameras."""
def __init__(self, P):
"""Initialize P = K[R|t] camera model."""
self.P = P
self.K = None
self.R = None
self.t = None
self.c = None
def project(self, X):
"""Project points in X (4*n array) ... | the_stack_v2_python_sparse | research/Python/fun_projecting3DPoints.py | joshuwaifo/gitRepoPracticeCodingMore | train | 0 |
7bfbfcfb04d8f3692d61959560b81b80a97afe4a | [
"if values.get('employee_id', False):\n employee = self.env['hr.employee'].browse(values['employee_id'])\n values.update({'job_id': employee.job_id.id or False})\nreturn super(HRContract, self).create(values)",
"if values.get('employee_id', False):\n employee = self.env['hr.employee'].browse(values['empl... | <|body_start_0|>
if values.get('employee_id', False):
employee = self.env['hr.employee'].browse(values['employee_id'])
values.update({'job_id': employee.job_id.id or False})
return super(HRContract, self).create(values)
<|end_body_0|>
<|body_start_1|>
if values.get('empl... | HRContract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HRContract:
def create(self, values):
"""create a new record"""
<|body_0|>
def write(self, values):
"""update an existing record"""
<|body_1|>
def _get_amount(self):
"""set the values of Basic, HRA, TA if wage is greater than 0."""
<|body... | stack_v2_sparse_classes_75kplus_train_001561 | 6,797 | no_license | [
{
"docstring": "create a new record",
"name": "create",
"signature": "def create(self, values)"
},
{
"docstring": "update an existing record",
"name": "write",
"signature": "def write(self, values)"
},
{
"docstring": "set the values of Basic, HRA, TA if wage is greater than 0.",
... | 6 | stack_v2_sparse_classes_30k_test_002504 | Implement the Python class `HRContract` described below.
Class description:
Implement the HRContract class.
Method signatures and docstrings:
- def create(self, values): create a new record
- def write(self, values): update an existing record
- def _get_amount(self): set the values of Basic, HRA, TA if wage is greate... | Implement the Python class `HRContract` described below.
Class description:
Implement the HRContract class.
Method signatures and docstrings:
- def create(self, values): create a new record
- def write(self, values): update an existing record
- def _get_amount(self): set the values of Basic, HRA, TA if wage is greate... | 59cd55edd536ce9feb85c772e163a2560c224cad | <|skeleton|>
class HRContract:
def create(self, values):
"""create a new record"""
<|body_0|>
def write(self, values):
"""update an existing record"""
<|body_1|>
def _get_amount(self):
"""set the values of Basic, HRA, TA if wage is greater than 0."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HRContract:
def create(self, values):
"""create a new record"""
if values.get('employee_id', False):
employee = self.env['hr.employee'].browse(values['employee_id'])
values.update({'job_id': employee.job_id.id or False})
return super(HRContract, self).create(val... | the_stack_v2_python_sparse | slnee_hr_contract/models/hr_contract.py | zamzamintl/SLNEE-MASTER | train | 0 | |
5e9635c9eac9d56a5bf746a7b2a8a7d2b7dec90c | [
"def backtrack(start, track):\n if sum(track) == target:\n return res.append(track[:])\n if sum(track) > target:\n return\n for i in range(start, len(nums)):\n track.append(nums[i])\n backtrack(0, track)\n track.pop()\nres = []\nbacktrack(0, [])\nreturn len(res)",
"dp =... | <|body_start_0|>
def backtrack(start, track):
if sum(track) == target:
return res.append(track[:])
if sum(track) > target:
return
for i in range(start, len(nums)):
track.append(nums[i])
backtrack(0, track)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""穷举超时:vs 39. 组合总和"""
<|body_0|>
def combinationSum4_1(self, nums: List[int], target: int) -> int:
"""动态规划-状态转移方程:动态规划:自下而上 dp[i] :对于给定的由正整数组成且不存在重复数字的数组,和为 i 的组合的个数。 状态转移方程:dp[i] = sum{dp[i -... | stack_v2_sparse_classes_75kplus_train_001562 | 5,262 | permissive | [
{
"docstring": "穷举超时:vs 39. 组合总和",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums: List[int], target: int) -> int"
},
{
"docstring": "动态规划-状态转移方程:动态规划:自下而上 dp[i] :对于给定的由正整数组成且不存在重复数字的数组,和为 i 的组合的个数。 状态转移方程:dp[i] = sum{dp[i - num] for num in nums and if i >= num}",
"n... | 5 | stack_v2_sparse_classes_30k_train_023802 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums: List[int], target: int) -> int: 穷举超时:vs 39. 组合总和
- def combinationSum4_1(self, nums: List[int], target: int) -> int: 动态规划-状态转移方程:动态规划:自下而上 dp[i] :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums: List[int], target: int) -> int: 穷举超时:vs 39. 组合总和
- def combinationSum4_1(self, nums: List[int], target: int) -> int: 动态规划-状态转移方程:动态规划:自下而上 dp[i] :... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""穷举超时:vs 39. 组合总和"""
<|body_0|>
def combinationSum4_1(self, nums: List[int], target: int) -> int:
"""动态规划-状态转移方程:动态规划:自下而上 dp[i] :对于给定的由正整数组成且不存在重复数字的数组,和为 i 的组合的个数。 状态转移方程:dp[i] = sum{dp[i -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""穷举超时:vs 39. 组合总和"""
def backtrack(start, track):
if sum(track) == target:
return res.append(track[:])
if sum(track) > target:
return
for i in range(s... | the_stack_v2_python_sparse | 377-combination-sum-iv.py | yuenliou/leetcode | train | 0 | |
a977567ffb25d182a782c53a33554d4c720f1903 | [
"if head is None:\n return None\nhead_old = head\nnew_node = head.next\nwhile new_node:\n tmp = new_node.next\n new_node.next = head\n head = new_node\n new_node = tmp\nhead_old.next = None\nreturn head",
"if head is None or head.next is None:\n return head\np = head\nrev = None\nwhile p:\n t... | <|body_start_0|>
if head is None:
return None
head_old = head
new_node = head.next
while new_node:
tmp = new_node.next
new_node.next = head
head = new_node
new_node = tmp
head_old.next = None
return head
<|end_bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Next node: The one gonna become the new head, then back pointing to the next one in original list. ... | stack_v2_sparse_classes_75kplus_train_001563 | 2,049 | no_license | [
{
"docstring": "modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Next node: The one gonna become the new head, then back pointing to the next one in original list. 3). New Head: The new head of reversed list. :type ... | 3 | stack_v2_sparse_classes_30k_train_043451 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Ne... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Ne... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def reverseList1(self, head):
"""modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Next node: The one gonna become the new head, then back pointing to the next one in original list. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList1(self, head):
"""modify list in place, needs three pointers. 1). Old head, which will become the tail at the end. old head.next should be the future head node 2). Next node: The one gonna become the new head, then back pointing to the next one in original list. 3). New Head: ... | the_stack_v2_python_sparse | LeetCodes/LinkedList/ReverseLinkedList.py | chutianwen/LeetCodes | train | 0 | |
13b59db3f2968efaadf006a57e566787a23a11d2 | [
"title = getattr(self, 'page_title', None)\nlanguages = getattr(self, 'page_languages', None)\nif not title:\n languages = languages or [settings.LANGUAGE_CODE]\n title = {language: factory.Faker('catch_phrase').evaluate(None, None, {'locale': language}) for language in languages}\nreturn create_i18n_page(tit... | <|body_start_0|>
title = getattr(self, 'page_title', None)
languages = getattr(self, 'page_languages', None)
if not title:
languages = languages or [settings.LANGUAGE_CODE]
title = {language: factory.Faker('catch_phrase').evaluate(None, None, {'locale': language}) for lan... | Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages. All this is mutualized by inheriting from the present class. | PageExtensionDjangoModelFactory | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageExtensionDjangoModelFactory:
"""Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages. All this is mutualized by inheriting ... | stack_v2_sparse_classes_75kplus_train_001564 | 11,346 | permissive | [
{
"docstring": "Automatically create a related page with the title (or random title if None) in all the requested languages",
"name": "extended_object",
"signature": "def extended_object(self)"
},
{
"docstring": "This hook method is called last when generating an instance from a factory. The sup... | 3 | stack_v2_sparse_classes_30k_train_042793 | Implement the Python class `PageExtensionDjangoModelFactory` described below.
Class description:
Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages... | Implement the Python class `PageExtensionDjangoModelFactory` described below.
Class description:
Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class PageExtensionDjangoModelFactory:
"""Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages. All this is mutualized by inheriting ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PageExtensionDjangoModelFactory:
"""Factories for page extensions have in common that: - they must create a related page with a title, - the related page may have to be placed below a "parent" page, - we may want to test the related page in several languages. All this is mutualized by inheriting from the pres... | the_stack_v2_python_sparse | src/richie/apps/core/factories.py | openfun/richie | train | 238 |
4f95c96f5cfdd09c25091d7b66879f06782999c2 | [
"arr = self.linked_list_to_array(head)\nself.insertion_sort(arr)\nreturn self.array_to_linked_list(arr)",
"arr = []\nwhile head is not None:\n arr.append(head.val)\n head = head.next\nreturn arr",
"for i in range(1, len(arr)):\n j, tmp = (i, arr[i])\n while j and tmp < arr[j - 1]:\n arr[j] = ... | <|body_start_0|>
arr = self.linked_list_to_array(head)
self.insertion_sort(arr)
return self.array_to_linked_list(arr)
<|end_body_0|>
<|body_start_1|>
arr = []
while head is not None:
arr.append(head.val)
head = head.next
return arr
<|end_body_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
<|body_0|>
def linked_list_to_array(self, head: ListNode) -> List[int]:
"""Time/Space: O(n)"""
<|body_1|>
def insertion_sort(self, arr: List[int]) -> Non... | stack_v2_sparse_classes_75kplus_train_001565 | 1,184 | no_license | [
{
"docstring": "Time: O(n ** 2) Space: O(n)",
"name": "insertionSortList",
"signature": "def insertionSortList(self, head: ListNode) -> ListNode"
},
{
"docstring": "Time/Space: O(n)",
"name": "linked_list_to_array",
"signature": "def linked_list_to_array(self, head: ListNode) -> List[int... | 4 | stack_v2_sparse_classes_30k_train_024877 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: Time: O(n ** 2) Space: O(n)
- def linked_list_to_array(self, head: ListNode) -> List[int]: Time/Space: O(n)
- def inserti... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertionSortList(self, head: ListNode) -> ListNode: Time: O(n ** 2) Space: O(n)
- def linked_list_to_array(self, head: ListNode) -> List[int]: Time/Space: O(n)
- def inserti... | 359f3b78da90c41c7e42e5c9e13d49b4fc67fe41 | <|skeleton|>
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
<|body_0|>
def linked_list_to_array(self, head: ListNode) -> List[int]:
"""Time/Space: O(n)"""
<|body_1|>
def insertion_sort(self, arr: List[int]) -> Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
"""Time: O(n ** 2) Space: O(n)"""
arr = self.linked_list_to_array(head)
self.insertion_sort(arr)
return self.array_to_linked_list(arr)
def linked_list_to_array(self, head: ListNode) -> List[int]:
""... | the_stack_v2_python_sparse | problems/147. Insertion Sort List/1 - Back to Array.py | Vasilic-Maxim/LeetCode-Problems | train | 0 | |
cafea02fb5109d6d20a4baa62e7f9f46bf468325 | [
"data = {'usr_name': 'mushan', 'password': '2020', 'error_type': '1'}\nStudent(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()\nresponse = self.client.post('/spider/delete/', content_type='application/json', data=data)\nself.assertEqual(response.status_code, 200)\nself.assertEqual(... | <|body_start_0|>
data = {'usr_name': 'mushan', 'password': '2020', 'error_type': '1'}
Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()
response = self.client.post('/spider/delete/', content_type='application/json', data=data)
self.assertEqual(resp... | DeleteTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTests:
def test_post_200(self):
"""检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1"""
<|body_0|>
def test_post_400(self):
"""检测返回状态码为400的post请求 1.参数数量不正确 2.参数名称不正确"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = {'usr... | stack_v2_sparse_classes_75kplus_train_001566 | 2,898 | no_license | [
{
"docstring": "检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1",
"name": "test_post_200",
"signature": "def test_post_200(self)"
},
{
"docstring": "检测返回状态码为400的post请求 1.参数数量不正确 2.参数名称不正确",
"name": "test_post_400",
"signature": "def test_post_400(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000618 | Implement the Python class `DeleteTests` described below.
Class description:
Implement the DeleteTests class.
Method signatures and docstrings:
- def test_post_200(self): 检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1
- def test_post_400(self): 检测返回状态码为400的post请求 1.参数数量不正确 2.参数名称不正确 | Implement the Python class `DeleteTests` described below.
Class description:
Implement the DeleteTests class.
Method signatures and docstrings:
- def test_post_200(self): 检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1
- def test_post_400(self): 检测返回状态码为400的post请求 1.参数数量不正确 2.参数名称不正确
<|skeleton|>
... | 7dfa07283d4130b931a92c80bf4f499f97a33b62 | <|skeleton|>
class DeleteTests:
def test_post_200(self):
"""检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1"""
<|body_0|>
def test_post_400(self):
"""检测返回状态码为400的post请求 1.参数数量不正确 2.参数名称不正确"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteTests:
def test_post_200(self):
"""检测返回状态码为200的post请求 1.如果数据库中无该学生,返回0 2.如果数据库中密码不相同,返回-1 3.如果成功删除返回1"""
data = {'usr_name': 'mushan', 'password': '2020', 'error_type': '1'}
Student(usr_name='mushan', usr_password='123', id='17373349', name='hbb', grade=3).save()
response... | the_stack_v2_python_sparse | post_web_spider/tests.py | SE2020-TopUnderstanding/BUAA-Campus-Tools-Backend | train | 7 | |
7b054ecd021f6b5501f5717736deb94f1d7a7d49 | [
"cleaned = super().clean(value)\nhtml, closing_tags = complete_html(cleaned)\nreturn self.remove_trailing_stupid_lines(html + closing_tags)",
"lines = text.replace('\\r', '').split('\\n')\ngood_line_found = False\nresult = ''\nfor i in range(len(lines) - 1, -1, -1):\n if not lines[i].strip() in ('', '<p> ... | <|body_start_0|>
cleaned = super().clean(value)
html, closing_tags = complete_html(cleaned)
return self.remove_trailing_stupid_lines(html + closing_tags)
<|end_body_0|>
<|body_start_1|>
lines = text.replace('\r', '').split('\n')
good_line_found = False
result = ''
... | ValidatedRichTextFormField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidatedRichTextFormField:
def clean(self, value):
"""Closes any open tags on the value. Removes any trailing "<p> </p>" lines. :param value: :return:"""
<|body_0|>
def remove_trailing_stupid_lines(text):
""":param text: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_001567 | 4,067 | no_license | [
{
"docstring": "Closes any open tags on the value. Removes any trailing \"<p> </p>\" lines. :param value: :return:",
"name": "clean",
"signature": "def clean(self, value)"
},
{
"docstring": ":param text: :return:",
"name": "remove_trailing_stupid_lines",
"signature": "def remove_tra... | 2 | null | Implement the Python class `ValidatedRichTextFormField` described below.
Class description:
Implement the ValidatedRichTextFormField class.
Method signatures and docstrings:
- def clean(self, value): Closes any open tags on the value. Removes any trailing "<p> </p>" lines. :param value: :return:
- def remove_tra... | Implement the Python class `ValidatedRichTextFormField` described below.
Class description:
Implement the ValidatedRichTextFormField class.
Method signatures and docstrings:
- def clean(self, value): Closes any open tags on the value. Removes any trailing "<p> </p>" lines. :param value: :return:
- def remove_tra... | 1e79166f512f0dd6f142f3c8cd914852645a244a | <|skeleton|>
class ValidatedRichTextFormField:
def clean(self, value):
"""Closes any open tags on the value. Removes any trailing "<p> </p>" lines. :param value: :return:"""
<|body_0|>
def remove_trailing_stupid_lines(text):
""":param text: :return:"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidatedRichTextFormField:
def clean(self, value):
"""Closes any open tags on the value. Removes any trailing "<p> </p>" lines. :param value: :return:"""
cleaned = super().clean(value)
html, closing_tags = complete_html(cleaned)
return self.remove_trailing_stupid_lines(ht... | the_stack_v2_python_sparse | studassweb/base/fields.py | Lundis/SAW | train | 0 | |
b156ecc1a3238da402813d24944b4958a2baef9d | [
"super().__init__()\nself.dice = DiceLoss(include_background=include_background, to_onehot_y=to_onehot_y, sigmoid=sigmoid, softmax=softmax, other_act=other_act, squared_pred=squared_pred, jaccard=jaccard, reduction=reduction, smooth_nr=smooth_nr, smooth_dr=smooth_dr, batch=batch)\nself.cross_entropy = nn.CrossEntro... | <|body_start_0|>
super().__init__()
self.dice = DiceLoss(include_background=include_background, to_onehot_y=to_onehot_y, sigmoid=sigmoid, softmax=softmax, other_act=other_act, squared_pred=squared_pred, jaccard=jaccard, reduction=reduction, smooth_nr=smooth_nr, smooth_dr=smooth_dr, batch=batch)
... | Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In this implementation, two deprecated parameters ``size_average`` and ``reduce``, ... | DiceCELoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceCELoss:
"""Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In this implementation, two deprecated parame... | stack_v2_sparse_classes_75kplus_train_001568 | 9,601 | permissive | [
{
"docstring": "Args: ``ce_weight`` and ``lambda_ce`` are only used for cross entropy loss. ``reduction`` is used for both losses and other parameters are only used for dice loss. include_background: if False channel index 0 (background category) is excluded from the calculation. to_onehot_y: whether to convert... | 2 | stack_v2_sparse_classes_30k_train_048827 | Implement the Python class `DiceCELoss` described below.
Class description:
Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In thi... | Implement the Python class `DiceCELoss` described below.
Class description:
Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In thi... | 2892550cd6ee1578a649414766c3ee88ea67c088 | <|skeleton|>
class DiceCELoss:
"""Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In this implementation, two deprecated parame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiceCELoss:
"""Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in ``monai.losses.DiceLoss``. The details of Cross Entropy Loss is shown in ``torch.nn.CrossEntropyLoss``. In this implementation, two deprecated parameters ``size_a... | the_stack_v2_python_sparse | utils/aneurysm_utils/utils/ignite_utils.py | MarkusMartinMueller/ML_in_MIP | train | 2 |
6f8e4b1ca14a07679bc6b644935d9813b894df27 | [
"content = Question.parse_content(content)\ncomprehension = cls(content=content)\ndb.session.add(comprehension)\ndb.session.commit()\nreturn comprehension",
"content = Question.parse_content(content)\ncomprehension = cls.query.get(id)\ncomprehension.content = content\ndb.session.commit()\nreturn comprehension"
] | <|body_start_0|>
content = Question.parse_content(content)
comprehension = cls(content=content)
db.session.add(comprehension)
db.session.commit()
return comprehension
<|end_body_0|>
<|body_start_1|>
content = Question.parse_content(content)
comprehension = cls.qu... | Comprehension | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comprehension:
def create(cls, content):
"""Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object"""
<|body_0|>
def update(cls, id, content):
"""Update the content of a comprehension :param id: ... | stack_v2_sparse_classes_75kplus_train_001569 | 1,216 | no_license | [
{
"docstring": "Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object",
"name": "create",
"signature": "def create(cls, content)"
},
{
"docstring": "Update the content of a comprehension :param id: the comprehension id :par... | 2 | stack_v2_sparse_classes_30k_train_029941 | Implement the Python class `Comprehension` described below.
Class description:
Implement the Comprehension class.
Method signatures and docstrings:
- def create(cls, content): Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object
- def update(cl... | Implement the Python class `Comprehension` described below.
Class description:
Implement the Comprehension class.
Method signatures and docstrings:
- def create(cls, content): Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object
- def update(cl... | c8af233693cd6a97489a2d73a85646b15220389c | <|skeleton|>
class Comprehension:
def create(cls, content):
"""Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object"""
<|body_0|>
def update(cls, id, content):
"""Update the content of a comprehension :param id: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Comprehension:
def create(cls, content):
"""Create a comprehension and return the comprehension object :param content: text of comprehension :return: comprehension object"""
content = Question.parse_content(content)
comprehension = cls(content=content)
db.session.add(comprehens... | the_stack_v2_python_sparse | exam_app/models/comprehension.py | GraphicalDot/testrocketbackend | train | 0 | |
4ca7dfeecbccba396ec5f4b0f1c33381f0ec868f | [
"self._turn_on_light()\nself._turn_on_dimmer(**kwargs)\nif self.assumed_state:\n self.async_write_ha_state()",
"super()._async_update()\nself._async_update_light()\nself._async_update_dimmer()"
] | <|body_start_0|>
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
if self.assumed_state:
self.async_write_ha_state()
<|end_body_0|>
<|body_start_1|>
super()._async_update()
self._async_update_light()
self._async_update_dimmer()
<|end_body_1|>
| Dimmer child class to MySensorsLight. | MySensorsLightDimmer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_0|>
def _async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
... | stack_v2_sparse_classes_75kplus_train_001570 | 8,168 | permissive | [
{
"docstring": "Turn the device on.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs: Any) -> None"
},
{
"docstring": "Update the controller with the latest value from a sensor.",
"name": "_async_update",
"signature": "def _async_update(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_014364 | Implement the Python class `MySensorsLightDimmer` described below.
Class description:
Dimmer child class to MySensorsLight.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def _async_update(self) -> None: Update the controller with the latest value from ... | Implement the Python class `MySensorsLightDimmer` described below.
Class description:
Dimmer child class to MySensorsLight.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def _async_update(self) -> None: Update the controller with the latest value from ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_0|>
def _async_update(self) -> None:
"""Update the controller with the latest value from a sensor."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySensorsLightDimmer:
"""Dimmer child class to MySensorsLight."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
self._turn_on_light()
self._turn_on_dimmer(**kwargs)
if self.assumed_state:
self.async_write_ha_state()
def _a... | the_stack_v2_python_sparse | homeassistant/components/mysensors/light.py | home-assistant/core | train | 35,501 |
ebf54b7cfbf6e4e047d3ffde56111a592385ccf4 | [
"super(VggNet, self).__init__()\nself.vggname = vggname\nself.num_classes = num_classes\nself.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)\nself.initializer = tf.contrib.layers.xavier_initializer()\nself.variance_initializer = tf.contrib.layers.variance_scaling_initializer(factor=0.1, mode='FAN_IN', uni... | <|body_start_0|>
super(VggNet, self).__init__()
self.vggname = vggname
self.num_classes = num_classes
self.regularizer = tf.contrib.layers.l2_regularizer(scale=wd)
self.initializer = tf.contrib.layers.xavier_initializer()
self.variance_initializer = tf.contrib.layers.vari... | Definition of VGG Networks. | VggNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VggNet:
"""Definition of VGG Networks."""
def __init__(self, vggname, neck, keep_prob, wd, feature_dim, num_classes=10):
"""Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the vgg type, such as 'VGG11'. neck: A bool value that decides... | stack_v2_sparse_classes_75kplus_train_001571 | 5,958 | permissive | [
{
"docstring": "Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the vgg type, such as 'VGG11'. neck: A bool value that decides using the MLP neck or not. keep_prob: The rate of keeping one neuron in Dropout. wd: The co-efficient of weight decay. feature_dim: the... | 5 | stack_v2_sparse_classes_30k_train_005388 | Implement the Python class `VggNet` described below.
Class description:
Definition of VGG Networks.
Method signatures and docstrings:
- def __init__(self, vggname, neck, keep_prob, wd, feature_dim, num_classes=10): Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the v... | Implement the Python class `VggNet` described below.
Class description:
Definition of VGG Networks.
Method signatures and docstrings:
- def __init__(self, vggname, neck, keep_prob, wd, feature_dim, num_classes=10): Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the v... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class VggNet:
"""Definition of VGG Networks."""
def __init__(self, vggname, neck, keep_prob, wd, feature_dim, num_classes=10):
"""Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the vgg type, such as 'VGG11'. neck: A bool value that decides... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VggNet:
"""Definition of VGG Networks."""
def __init__(self, vggname, neck, keep_prob, wd, feature_dim, num_classes=10):
"""Creates a model for classifying an image using VGG networks. Args: vggname: A string representing the vgg type, such as 'VGG11'. neck: A bool value that decides using the ML... | the_stack_v2_python_sparse | dble/vgg.py | Tarkiyah/googleResearch | train | 11 |
49bfe4a6af5e4d3e11405aa04e0d0d654b02fa40 | [
"self.fset = fset\nself.rules = []\nself.output = None",
"self.output = self.rules[0].output\nfor i in range(1, len(self.rules)):\n self.output |= self.rules[i].output"
] | <|body_start_0|>
self.fset = fset
self.rules = []
self.output = None
<|end_body_0|>
<|body_start_1|>
self.output = self.rules[0].output
for i in range(1, len(self.rules)):
self.output |= self.rules[i].output
<|end_body_1|>
| Defines a consequent of a rule. | Consequent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Consequent:
"""Defines a consequent of a rule."""
def __init__(self, fset):
"""Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent."""
<|body_0|>
def Aggregate(self):
"""Aggregates of the truth value... | stack_v2_sparse_classes_75kplus_train_001572 | 1,376 | no_license | [
{
"docstring": "Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent.",
"name": "__init__",
"signature": "def __init__(self, fset)"
},
{
"docstring": "Aggregates of the truth values with max method.",
"name": "Aggregate",
"si... | 2 | stack_v2_sparse_classes_30k_train_004116 | Implement the Python class `Consequent` described below.
Class description:
Defines a consequent of a rule.
Method signatures and docstrings:
- def __init__(self, fset): Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent.
- def Aggregate(self): Aggregat... | Implement the Python class `Consequent` described below.
Class description:
Defines a consequent of a rule.
Method signatures and docstrings:
- def __init__(self, fset): Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent.
- def Aggregate(self): Aggregat... | a165dba28853ca2dad3366193a5306d8a83e6dee | <|skeleton|>
class Consequent:
"""Defines a consequent of a rule."""
def __init__(self, fset):
"""Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent."""
<|body_0|>
def Aggregate(self):
"""Aggregates of the truth value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Consequent:
"""Defines a consequent of a rule."""
def __init__(self, fset):
"""Initialization of consequent. Args: fset: reference to a fuzzy set. rules: list of rules which have this consequent."""
self.fset = fset
self.rules = []
self.output = None
def Aggregate(sel... | the_stack_v2_python_sparse | consequent.py | johmathe/gfuzzy | train | 2 |
20ba13d1bc6f321fdacaf1bedae1ac4d26ce70f9 | [
"self.desired_caps = {'platformName': PLANTFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}\nself.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)\nself.wait = WebDriverWait(self.driver, TIMEOUT)\nself.client = MongoClient(MONGO_URL)\nself.db = self.client[MONGO_DB... | <|body_start_0|>
self.desired_caps = {'platformName': PLANTFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIMEOUT)
self.client = MongoClient(M... | Moments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录"""
<|body_1|>
def enter(self):
"""try: explore = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d7_'))) except: self.driver.refresh() explore = se... | stack_v2_sparse_classes_75kplus_train_001573 | 6,063 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "登录",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "try: explore = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d7_'))) except: self.dri... | 5 | stack_v2_sparse_classes_30k_train_017383 | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录
- def enter(self): try: explore = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d7_'))) except: self.drive... | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录
- def enter(self): try: explore = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d7_'))) except: self.drive... | 87cbae60f7a5b033851b0056dff741a3d5980d06 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录"""
<|body_1|>
def enter(self):
"""try: explore = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d7_'))) except: self.driver.refresh() explore = se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Moments:
def __init__(self):
"""初始化"""
self.desired_caps = {'platformName': PLANTFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIME... | the_stack_v2_python_sparse | 05-Moments/moments.py | Northxw/Python3_WebSpider | train | 545 | |
a0f189e75848f75d055e6b5c1c70327d51c75163 | [
"each_statements = []\nfor i in range(len(self.statements)):\n func_for_statement = self.statements[i]\n current_statement = func_for_statement(g)\n each_statements.append(current_statement)\nreturn each_statements",
"statement = ''\nfor i in range(len(statements)):\n current_statement = statements[i]... | <|body_start_0|>
each_statements = []
for i in range(len(self.statements)):
func_for_statement = self.statements[i]
current_statement = func_for_statement(g)
each_statements.append(current_statement)
return each_statements
<|end_body_0|>
<|body_start_1|>
... | Gen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gen:
def process_chain(self, g):
"""processes the chain of statements and generates the array string with the finished statement."""
<|body_0|>
def join_statements(self, statements):
"""given an array of strings, joins them into one big string."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_001574 | 12,060 | no_license | [
{
"docstring": "processes the chain of statements and generates the array string with the finished statement.",
"name": "process_chain",
"signature": "def process_chain(self, g)"
},
{
"docstring": "given an array of strings, joins them into one big string.",
"name": "join_statements",
"s... | 2 | stack_v2_sparse_classes_30k_train_007288 | Implement the Python class `Gen` described below.
Class description:
Implement the Gen class.
Method signatures and docstrings:
- def process_chain(self, g): processes the chain of statements and generates the array string with the finished statement.
- def join_statements(self, statements): given an array of strings... | Implement the Python class `Gen` described below.
Class description:
Implement the Gen class.
Method signatures and docstrings:
- def process_chain(self, g): processes the chain of statements and generates the array string with the finished statement.
- def join_statements(self, statements): given an array of strings... | 25efe0b85f594bd777a7172ab8c1a888459977f1 | <|skeleton|>
class Gen:
def process_chain(self, g):
"""processes the chain of statements and generates the array string with the finished statement."""
<|body_0|>
def join_statements(self, statements):
"""given an array of strings, joins them into one big string."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gen:
def process_chain(self, g):
"""processes the chain of statements and generates the array string with the finished statement."""
each_statements = []
for i in range(len(self.statements)):
func_for_statement = self.statements[i]
current_statement = func_for_s... | the_stack_v2_python_sparse | main_proj_lib/old_frameworks_examples_tests/framework_numerical.py | brando90/MathNet-large-scale-Mathematics-Dataset-for-Machine-Learning | train | 0 | |
1d22b7ca7c4cf329912d134f09d7204dcb50aec7 | [
"nums.sort()\nres = 0\nfor i in range(len(nums) - 2):\n for j in range(i + 1, len(nums) - 1):\n for k in range(j + 1, len(nums)):\n if nums[i] + nums[j] > nums[k]:\n res += 1\n else:\n break\nreturn res",
"nums.sort(reverse=True)\nres = 0\nfor i in ran... | <|body_start_0|>
nums.sort()
res = 0
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] > nums[k]:
res += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def triangleNumberSol(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
res = 0
... | stack_v2_sparse_classes_75kplus_train_001575 | 1,429 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "triangleNumber",
"signature": "def triangleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "triangleNumberSol",
"signature": "def triangleNumberSol(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def triangleNumber(self, nums): :type nums: List[int] :rtype: int
- def triangleNumberSol(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 triangleNumber(self, nums): :type nums: List[int] :rtype: int
- def triangleNumberSol(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def tr... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def triangleNumberSol(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def triangleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
nums.sort()
res = 0
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] > nu... | the_stack_v2_python_sparse | medium/valid_triangle_number.py | gerrycfchang/leetcode-python | train | 2 | |
ebdc1880c0bda49d0624861e43e7cfa10b05a3ee | [
"if value <= self.value:\n self.left = self.add_to_subtree(self.left, value)\nelif value > self.value:\n self.right = self.add_to_subtree(self.right, value)",
"if parent is None:\n return BinarySearchTree.Node(value)\nparent.add(value)\nreturn parent",
"if value < self.value:\n self.left = self.remo... | <|body_start_0|>
if value <= self.value:
self.left = self.add_to_subtree(self.left, value)
elif value > self.value:
self.right = self.add_to_subtree(self.right, value)
<|end_body_0|>
<|body_start_1|>
if parent is None:
return BinarySearchTree.Node(value)
... | extend node for use in Binary Search Tree implementation | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""extend node for use in Binary Search Tree implementation"""
def add(self, value):
"""add value to correct place in tree O(logn)"""
<|body_0|>
def add_to_subtree(self, parent, value):
"""helper method to add"""
<|body_1|>
def remove(self, val... | stack_v2_sparse_classes_75kplus_train_001576 | 3,709 | no_license | [
{
"docstring": "add value to correct place in tree O(logn)",
"name": "add",
"signature": "def add(self, value)"
},
{
"docstring": "helper method to add",
"name": "add_to_subtree",
"signature": "def add_to_subtree(self, parent, value)"
},
{
"docstring": "remove value from tree and... | 4 | stack_v2_sparse_classes_30k_train_029070 | Implement the Python class `Node` described below.
Class description:
extend node for use in Binary Search Tree implementation
Method signatures and docstrings:
- def add(self, value): add value to correct place in tree O(logn)
- def add_to_subtree(self, parent, value): helper method to add
- def remove(self, value):... | Implement the Python class `Node` described below.
Class description:
extend node for use in Binary Search Tree implementation
Method signatures and docstrings:
- def add(self, value): add value to correct place in tree O(logn)
- def add_to_subtree(self, parent, value): helper method to add
- def remove(self, value):... | ef89e4c89cb014d0acea1669f927cadc6af70225 | <|skeleton|>
class Node:
"""extend node for use in Binary Search Tree implementation"""
def add(self, value):
"""add value to correct place in tree O(logn)"""
<|body_0|>
def add_to_subtree(self, parent, value):
"""helper method to add"""
<|body_1|>
def remove(self, val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
"""extend node for use in Binary Search Tree implementation"""
def add(self, value):
"""add value to correct place in tree O(logn)"""
if value <= self.value:
self.left = self.add_to_subtree(self.left, value)
elif value > self.value:
self.right = self.... | the_stack_v2_python_sparse | Trees/binary_search_tree.py | hayleymathews/data_structures_and_algorithms | train | 0 |
07aa30b259d6d26c3ceddec68d21386c90809c53 | [
"user = info.context.user\nif not user.has_perm('releases.list_all_release'):\n raise GraphQLError('Not allowed')\nreturn Release.objects.all()",
"user = info.context.user\nif not user.has_perm('releases.list_all_releasetask'):\n raise GraphQLError('Not allowed')\nreturn ReleaseTask.objects.all()",
"user ... | <|body_start_0|>
user = info.context.user
if not user.has_perm('releases.list_all_release'):
raise GraphQLError('Not allowed')
return Release.objects.all()
<|end_body_0|>
<|body_start_1|>
user = info.context.user
if not user.has_perm('releases.list_all_releasetask'):... | Query | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
def resolve_all_releases(self, info, **kwargs):
"""Return all releases"""
<|body_0|>
def resolve_all_release_tasks(self, info, **kwargs):
"""Return all release tasks"""
<|body_1|>
def resolve_all_release_services(self, info, **kwargs):
"""... | stack_v2_sparse_classes_75kplus_train_001577 | 3,584 | permissive | [
{
"docstring": "Return all releases",
"name": "resolve_all_releases",
"signature": "def resolve_all_releases(self, info, **kwargs)"
},
{
"docstring": "Return all release tasks",
"name": "resolve_all_release_tasks",
"signature": "def resolve_all_release_tasks(self, info, **kwargs)"
},
... | 4 | stack_v2_sparse_classes_30k_train_021472 | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_all_releases(self, info, **kwargs): Return all releases
- def resolve_all_release_tasks(self, info, **kwargs): Return all release tasks
- def resolve_all_release_services(s... | Implement the Python class `Query` described below.
Class description:
Implement the Query class.
Method signatures and docstrings:
- def resolve_all_releases(self, info, **kwargs): Return all releases
- def resolve_all_release_tasks(self, info, **kwargs): Return all release tasks
- def resolve_all_release_services(s... | ba62b369e6464259ea92dbb9ba49876513f37fba | <|skeleton|>
class Query:
def resolve_all_releases(self, info, **kwargs):
"""Return all releases"""
<|body_0|>
def resolve_all_release_tasks(self, info, **kwargs):
"""Return all release tasks"""
<|body_1|>
def resolve_all_release_services(self, info, **kwargs):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Query:
def resolve_all_releases(self, info, **kwargs):
"""Return all releases"""
user = info.context.user
if not user.has_perm('releases.list_all_release'):
raise GraphQLError('Not allowed')
return Release.objects.all()
def resolve_all_release_tasks(self, info,... | the_stack_v2_python_sparse | creator/releases/queries.py | kids-first/kf-api-study-creator | train | 3 | |
97ba2c8dbb90199871ebead20570ddb79ccca4d5 | [
"args = movies_parser.parse_args()\npage = args['page']\nper_page = args['per_page']\nsort_by = args['sort_by']\nsort_order = args['order']\nstart = per_page * (page - 1)\nstop = start + per_page\ndescending = sort_order == 'desc'\nkwargs = {'start': start, 'stop': stop, 'list_id': list_id, 'order_by': sort_by, 'de... | <|body_start_0|>
args = movies_parser.parse_args()
page = args['page']
per_page = args['per_page']
sort_by = args['sort_by']
sort_order = args['order']
start = per_page * (page - 1)
stop = start + per_page
descending = sort_order == 'desc'
kwargs =... | MovieListMoviesAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieListMoviesAPI:
def get(self, list_id, session=None):
"""Get movies by list ID"""
<|body_0|>
def post(self, list_id, session=None):
"""Add movies to list by ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = movies_parser.parse_args()
... | stack_v2_sparse_classes_75kplus_train_001578 | 12,846 | permissive | [
{
"docstring": "Get movies by list ID",
"name": "get",
"signature": "def get(self, list_id, session=None)"
},
{
"docstring": "Add movies to list by ID",
"name": "post",
"signature": "def post(self, list_id, session=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015958 | Implement the Python class `MovieListMoviesAPI` described below.
Class description:
Implement the MovieListMoviesAPI class.
Method signatures and docstrings:
- def get(self, list_id, session=None): Get movies by list ID
- def post(self, list_id, session=None): Add movies to list by ID | Implement the Python class `MovieListMoviesAPI` described below.
Class description:
Implement the MovieListMoviesAPI class.
Method signatures and docstrings:
- def get(self, list_id, session=None): Get movies by list ID
- def post(self, list_id, session=None): Add movies to list by ID
<|skeleton|>
class MovieListMov... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class MovieListMoviesAPI:
def get(self, list_id, session=None):
"""Get movies by list ID"""
<|body_0|>
def post(self, list_id, session=None):
"""Add movies to list by ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovieListMoviesAPI:
def get(self, list_id, session=None):
"""Get movies by list ID"""
args = movies_parser.parse_args()
page = args['page']
per_page = args['per_page']
sort_by = args['sort_by']
sort_order = args['order']
start = per_page * (page - 1)
... | the_stack_v2_python_sparse | flexget/components/managed_lists/lists/movie_list/api.py | BrutuZ/Flexget | train | 1 | |
31a0c6d48b1a0d9e503cccb66943b41374ab6071 | [
"self.nums = nums\nself.index_to_diff = dict()\nself.prefix_sum = [0] * (len(nums) + 1)\nfor i in range(len(self.nums)):\n self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i]",
"aggregated_diff = val - self.nums[i]\nself.nums[i] = val\nif i in self.index_to_diff:\n aggregated_diff = self.index_to_diff[i] ... | <|body_start_0|>
self.nums = nums
self.index_to_diff = dict()
self.prefix_sum = [0] * (len(nums) + 1)
for i in range(len(self.nums)):
self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i]
<|end_body_0|>
<|body_start_1|>
aggregated_diff = val - self.nums[i]
se... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_001579 | 10,418 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | fa3704af37d9e04ab6fd13b7b17cc83c239946f7 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
self.index_to_diff = dict()
self.prefix_sum = [0] * (len(nums) + 1)
for i in range(len(self.nums)):
self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i]
def update(self, i... | the_stack_v2_python_sparse | lintcode/medium/840_range_sum_query_mutable.py | simonfqy/SimonfqyGitHub | train | 2 | |
d7e08d9fe74455f70df4be5b7c4ca61f6214f580 | [
"super(DCGAN3DEncoder, self).__init__(name=name)\nif initializers_no_bias is None:\n initializers_no_bias = _DEFAULT_CONV_INITIALIZERS_NO_BIAS\nif regularizers_no_bias is None:\n regularizers_no_bias = _DEFAULT_CONV_REGULARIZERS_NO_BIAS\nif filters is None:\n filters = [64, 128, 256, 512, 512]\nself._initi... | <|body_start_0|>
super(DCGAN3DEncoder, self).__init__(name=name)
if initializers_no_bias is None:
initializers_no_bias = _DEFAULT_CONV_INITIALIZERS_NO_BIAS
if regularizers_no_bias is None:
regularizers_no_bias = _DEFAULT_CONV_REGULARIZERS_NO_BIAS
if filters is Non... | A DCGAN model for 128x128 dimensional input. | DCGAN3DEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs... | stack_v2_sparse_classes_75kplus_train_001580 | 31,363 | no_license | [
{
"docstring": "Constructs a spatiotemporal DCGAN Encoder. Args: latent_size: The number of channels in the output layer. Defaults to 128. filters: An optional iterable giving the number of filters at each layer of the network. If None, uses the default configuration of [64, 128, 256, 512, 512]. final_activatio... | 2 | stack_v2_sparse_classes_30k_train_002414 | Implement the Python class `DCGAN3DEncoder` described below.
Class description:
A DCGAN model for 128x128 dimensional input.
Method signatures and docstrings:
- def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, reg... | Implement the Python class `DCGAN3DEncoder` described below.
Class description:
A DCGAN model for 128x128 dimensional input.
Method signatures and docstrings:
- def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, reg... | 358a09d491aab0794df9cc7f3f8064430a78fbc3 | <|skeleton|>
class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs a spatiotemp... | the_stack_v2_python_sparse | architectures/conv_architectures.py | zwbgood6/temporal-hierarchy | train | 0 |
b1d53a1b2a15c85fa0dbb4f6ed7cb233c0e1ed65 | [
"delivery = data.get('delivery')\nif current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):\n raise ValidationError('Delivery is required.', 'delivery')",
"start = arrow.get(data['request_start_date']).date()\nend = arrow.get(data['request_expire_date']).date()\nduration_days = curr... | <|body_start_0|>
delivery = data.get('delivery')
if current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):
raise ValidationError('Delivery is required.', 'delivery')
<|end_body_0|>
<|body_start_1|>
start = arrow.get(data['request_start_date']).date()
... | Loan request schema. | LoanRequestSchemaV1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
<|body_0|>
def postload_checks(self, data, **kwargs):
"""Validate dates values."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_001581 | 3,449 | permissive | [
{
"docstring": "Validate schema delivery field.",
"name": "validates_schema",
"signature": "def validates_schema(self, data, **kwargs)"
},
{
"docstring": "Validate dates values.",
"name": "postload_checks",
"signature": "def postload_checks(self, data, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022679 | Implement the Python class `LoanRequestSchemaV1` described below.
Class description:
Loan request schema.
Method signatures and docstrings:
- def validates_schema(self, data, **kwargs): Validate schema delivery field.
- def postload_checks(self, data, **kwargs): Validate dates values. | Implement the Python class `LoanRequestSchemaV1` described below.
Class description:
Loan request schema.
Method signatures and docstrings:
- def validates_schema(self, data, **kwargs): Validate schema delivery field.
- def postload_checks(self, data, **kwargs): Validate dates values.
<|skeleton|>
class LoanRequestS... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
<|body_0|>
def postload_checks(self, data, **kwargs):
"""Validate dates values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoanRequestSchemaV1:
"""Loan request schema."""
def validates_schema(self, data, **kwargs):
"""Validate schema delivery field."""
delivery = data.get('delivery')
if current_app.config.get('ILS_CIRCULATION_DELIVERY_METHODS', {}) and (not delivery):
raise ValidationError... | the_stack_v2_python_sparse | invenio_app_ils/circulation/loaders/schemas/json/loan_request.py | inveniosoftware/invenio-app-ils | train | 64 |
f3f2496ef169f294042afa87f6f66f1a2af70503 | [
"if not root:\n return ''\nqueue = collections.deque([root])\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('None')\nreturn '[' + ','.join(res) + ']'",
"if not... | <|body_start_0|>
if not root:
return ''
queue = collections.deque([root])
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
... | 序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点 | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点"""
def serialize(self, root):
"""Encodes a tree to a single str... | stack_v2_sparse_classes_75kplus_train_001582 | 1,834 | 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:
序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点
Method signatures and docstrings:
- ... | Implement the Python class `Codec` described below.
Class description:
序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点
Method signatures and docstrings:
- ... | f350b3d6e59fd5771e11ec0b466f9ba5eeb8e927 | <|skeleton|>
class Codec:
"""序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点"""
def serialize(self, root):
"""Encodes a tree to a single str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
"""序列化: - 用BFS遍历树, 与一般遍历不同点是不管node的左右子节点是否存在, 统统加到队列中 - 在节点出队时, 如果节点不存在, 在返回值res中加入一个 null;如果节点存在, 则加入节点值的字符串形式 反序列化: - 同样使用BFS方法, 利用队列新建二叉树 - 首先要将data转换成列表, 然后遍历,只要不为null将节点按顺序加入二叉树中; 同时还要将节点入队 - 队列为空时遍历完毕, 返回根节点"""
def serialize(self, root):
"""Encodes a tree to a single string. :type ro... | the_stack_v2_python_sparse | leetcode/python/297.py | ShawnDong98/Algorithm-Book | train | 0 |
ca0fd627e4169301e33c205f0ead7a512db36aa9 | [
"node = root\nstack = []\noutput = []\nwhile stack or node:\n while node:\n stack.append(node)\n node = node.left\n current = stack.pop()\n output.append(current.val)\n node = current.right\nreturn output",
"output, stack = ([], [(root, False)])\nwhile stack:\n node, is_visited = stac... | <|body_start_0|>
node = root
stack = []
output = []
while stack or node:
while node:
stack.append(node)
node = node.left
current = stack.pop()
output.append(current.val)
node = current.right
return ou... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_stack(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def inorderTraversal_recursive(self, root):
""":ty... | stack_v2_sparse_classes_75kplus_train_001583 | 3,672 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_stack",
"signature": "def inorderTraversal_stack(self, root)"
},
... | 4 | null | 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 inorderTraversal_stack(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_r... | 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 inorderTraversal_stack(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_r... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_stack(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def inorderTraversal_recursive(self, root):
""":ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
node = root
stack = []
output = []
while stack or node:
while node:
stack.append(node)
node = node.left
current = stack.pop()... | the_stack_v2_python_sparse | src/lt_94.py | oxhead/CodingYourWay | train | 0 | |
ff23ce6e378b65dcf0a3864393dc22f86a7da7e0 | [
"if request.user.username == 'Admin':\n return Response(data={'Admin 페이지 접속 가능!'}, status=status.HTTP_200_OK)\nelse:\n return Response(data={'Admin 페이지 접속 불가능!'}, status=status.HTTP_400_BAD_REQUEST)",
"if request.user.username == 'Admin':\n query_set = AdminCategory.objects.filter(parent_category_id=None... | <|body_start_0|>
if request.user.username == 'Admin':
return Response(data={'Admin 페이지 접속 가능!'}, status=status.HTTP_200_OK)
else:
return Response(data={'Admin 페이지 접속 불가능!'}, status=status.HTTP_400_BAD_REQUEST)
<|end_body_0|>
<|body_start_1|>
if request.user.username == '... | AdminViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminViewSet:
def is_admin(self, request):
"""관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인"""
<|body_0|>
def admin_category(self, request):
"""관리자 페이지 카테고리 전송 [admin token required]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if re... | stack_v2_sparse_classes_75kplus_train_001584 | 35,811 | no_license | [
{
"docstring": "관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인",
"name": "is_admin",
"signature": "def is_admin(self, request)"
},
{
"docstring": "관리자 페이지 카테고리 전송 [admin token required]",
"name": "admin_category",
"signature": "def admin_category(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040323 | Implement the Python class `AdminViewSet` described below.
Class description:
Implement the AdminViewSet class.
Method signatures and docstrings:
- def is_admin(self, request): 관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인
- def admin_category(self, request): 관리자 페이지 카테고리 전송 [admin token required] | Implement the Python class `AdminViewSet` described below.
Class description:
Implement the AdminViewSet class.
Method signatures and docstrings:
- def is_admin(self, request): 관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인
- def admin_category(self, request): 관리자 페이지 카테고리 전송 [admin token required]
<|ske... | bcc955bddd9941f2bc54f7577c26c1ddc6b36a48 | <|skeleton|>
class AdminViewSet:
def is_admin(self, request):
"""관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인"""
<|body_0|>
def admin_category(self, request):
"""관리자 페이지 카테고리 전송 [admin token required]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdminViewSet:
def is_admin(self, request):
"""관리자가 맞는지 확인 [admin token required] : 입력받은 토큰으로 관리자가 맞는지 확인"""
if request.user.username == 'Admin':
return Response(data={'Admin 페이지 접속 가능!'}, status=status.HTTP_200_OK)
else:
return Response(data={'Admin 페이지 접속 불가능!'... | the_stack_v2_python_sparse | admin_page/views.py | bgy1060/Daily_Project | train | 1 | |
627d804042051840456f961290b86bebbccdacb2 | [
"if roi_center is not None and roi_size is not None:\n roi_center = np.asarray(roi_center, dtype=np.uint16)\n roi_size = np.asarray(roi_size, dtype=np.uint16)\n self.roi_start = np.subtract(roi_center, np.floor_divide(roi_size, 2))\n self.roi_end = np.add(self.roi_start, roi_size)\nelse:\n assert roi... | <|body_start_0|>
if roi_center is not None and roi_size is not None:
roi_center = np.asarray(roi_center, dtype=np.uint16)
roi_size = np.asarray(roi_size, dtype=np.uint16)
self.roi_start = np.subtract(roi_center, np.floor_divide(roi_size, 2))
self.roi_end = np.add(... | General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start and end coordinates of the ROI must be provided. The sub-volume must sit the ... | SpatialCrop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialCrop:
"""General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start and end coordinates of the ROI must be... | stack_v2_sparse_classes_75kplus_train_001585 | 27,976 | permissive | [
{
"docstring": "Args: roi_center: voxel coordinates for center of the crop ROI. roi_size: size of the crop ROI. roi_start: voxel coordinates for start of the crop ROI. roi_end: voxel coordinates for end of the crop ROI.",
"name": "__init__",
"signature": "def __init__(self, roi_center: Optional[Sequence... | 2 | stack_v2_sparse_classes_30k_train_036890 | Implement the Python class `SpatialCrop` described below.
Class description:
General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start... | Implement the Python class `SpatialCrop` described below.
Class description:
General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start... | d94c4d3a2c465717ba3fae01b7acea7fada9885b | <|skeleton|>
class SpatialCrop:
"""General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start and end coordinates of the ROI must be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpatialCrop:
"""General purpose cropper to produce sub-volume region of interest (ROI). It can support to crop ND spatial (channel-first) data. Either a spatial center and size must be provided, or alternatively if center and size are not provided, the start and end coordinates of the ROI must be provided. Th... | the_stack_v2_python_sparse | monai/transforms/croppad/array.py | precision-medicine-um/MONAI-Deep_Learning | train | 3 |
65792c3c8c6dcf24b2042f655300ba59dd6b7113 | [
"url = request.url\nif forbidden.search(url):\n raise exceptions.IgnoreRequest('{} is blacklisted'.format(url))",
"url = response.url\nif url.endswith('ajax-module-connector.php'):\n data = None\n try:\n data = json.loads(response.text)\n except json.decoder.JSONDecodeError:\n print('Err... | <|body_start_0|>
url = request.url
if forbidden.search(url):
raise exceptions.IgnoreRequest('{} is blacklisted'.format(url))
<|end_body_0|>
<|body_start_1|>
url = response.url
if url.endswith('ajax-module-connector.php'):
data = None
try:
... | SherlockDownloaderMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SherlockDownloaderMiddleware:
def process_request(self, request, spider):
"""Prohibit incompatible URL"""
<|body_0|>
def process_response(self, request, response, spider):
"""Format Wikidot response"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ur... | stack_v2_sparse_classes_75kplus_train_001586 | 1,633 | permissive | [
{
"docstring": "Prohibit incompatible URL",
"name": "process_request",
"signature": "def process_request(self, request, spider)"
},
{
"docstring": "Format Wikidot response",
"name": "process_response",
"signature": "def process_response(self, request, response, spider)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001060 | Implement the Python class `SherlockDownloaderMiddleware` described below.
Class description:
Implement the SherlockDownloaderMiddleware class.
Method signatures and docstrings:
- def process_request(self, request, spider): Prohibit incompatible URL
- def process_response(self, request, response, spider): Format Wiki... | Implement the Python class `SherlockDownloaderMiddleware` described below.
Class description:
Implement the SherlockDownloaderMiddleware class.
Method signatures and docstrings:
- def process_request(self, request, spider): Prohibit incompatible URL
- def process_response(self, request, response, spider): Format Wiki... | e1d44d115cb6263c229b16ccfc66ebe846563e51 | <|skeleton|>
class SherlockDownloaderMiddleware:
def process_request(self, request, spider):
"""Prohibit incompatible URL"""
<|body_0|>
def process_response(self, request, response, spider):
"""Format Wikidot response"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SherlockDownloaderMiddleware:
def process_request(self, request, spider):
"""Prohibit incompatible URL"""
url = request.url
if forbidden.search(url):
raise exceptions.IgnoreRequest('{} is blacklisted'.format(url))
def process_response(self, request, response, spider):
... | the_stack_v2_python_sparse | sherlock/middlewares.py | foundation-int-tech-team/sherlock | train | 24 | |
8e57d07b65e9c83ed6a0c2345877217cc7e8747a | [
"omega_0 = self.frequency * 2.0 * m.pi\nself.cos_omega_t = m.cos(omega_0 / self.sample_rate)\nself.y2 = m.sin(-omega_0 / self.sample_rate)\nself.y1 = 0.0",
"if length is None:\n length = len(arr)\nif length > len(arr):\n raise IndexError('Recursive Oscillator: buffer is too small!')\nif length < 1:\n rai... | <|body_start_0|>
omega_0 = self.frequency * 2.0 * m.pi
self.cos_omega_t = m.cos(omega_0 / self.sample_rate)
self.y2 = m.sin(-omega_0 / self.sample_rate)
self.y1 = 0.0
<|end_body_0|>
<|body_start_1|>
if length is None:
length = len(arr)
if length > len(arr):
... | RecursiveOscillator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecursiveOscillator:
def setup(self):
"""Create the initial values needed to simulate infinite oscillation"""
<|body_0|>
def generate(self, arr, length=None):
"""Generates a sine wave into a given buffer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_001587 | 2,890 | no_license | [
{
"docstring": "Create the initial values needed to simulate infinite oscillation",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Generates a sine wave into a given buffer",
"name": "generate",
"signature": "def generate(self, arr, length=None)"
}
] | 2 | null | Implement the Python class `RecursiveOscillator` described below.
Class description:
Implement the RecursiveOscillator class.
Method signatures and docstrings:
- def setup(self): Create the initial values needed to simulate infinite oscillation
- def generate(self, arr, length=None): Generates a sine wave into a give... | Implement the Python class `RecursiveOscillator` described below.
Class description:
Implement the RecursiveOscillator class.
Method signatures and docstrings:
- def setup(self): Create the initial values needed to simulate infinite oscillation
- def generate(self, arr, length=None): Generates a sine wave into a give... | 9ab8c2e5516893353abe2cb5385247158a5dcb6a | <|skeleton|>
class RecursiveOscillator:
def setup(self):
"""Create the initial values needed to simulate infinite oscillation"""
<|body_0|>
def generate(self, arr, length=None):
"""Generates a sine wave into a given buffer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecursiveOscillator:
def setup(self):
"""Create the initial values needed to simulate infinite oscillation"""
omega_0 = self.frequency * 2.0 * m.pi
self.cos_omega_t = m.cos(omega_0 / self.sample_rate)
self.y2 = m.sin(-omega_0 / self.sample_rate)
self.y1 = 0.0
def g... | the_stack_v2_python_sparse | recursiveOsc.py | chrisssc/pyVis | train | 1 | |
71f0515df79acba71f8512346af2e9986ccb234f | [
"self.__io: BackupPcCloneStyle = io\n'\\n The output style.\\n '\nself.__host: str = ''\n'\\n The host of the backup.\\n '\nself.__backup_no: int = 0\n'\\n The number of the backup.\\n '",
"self.__io.writeln(' Removing files')\nbackup_dir_clone = Config.instance.backup_di... | <|body_start_0|>
self.__io: BackupPcCloneStyle = io
'\n The output style.\n '
self.__host: str = ''
'\n The host of the backup.\n '
self.__backup_no: int = 0
'\n The number of the backup.\n '
<|end_body_0|>
<|body_start_1|>
... | Deletes a backup of a host | BackupDelete | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupDelete:
"""Deletes a backup of a host"""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
<|body_0|>
def __delete_files(self) -> None:
"""Removes the backup from the cone file system."""
... | stack_v2_sparse_classes_75kplus_train_001588 | 2,378 | permissive | [
{
"docstring": "Object constructor. @param BackupPcCloneStyle io: The output style.",
"name": "__init__",
"signature": "def __init__(self, io: BackupPcCloneStyle)"
},
{
"docstring": "Removes the backup from the cone file system.",
"name": "__delete_files",
"signature": "def __delete_file... | 4 | null | Implement the Python class `BackupDelete` described below.
Class description:
Deletes a backup of a host
Method signatures and docstrings:
- def __init__(self, io: BackupPcCloneStyle): Object constructor. @param BackupPcCloneStyle io: The output style.
- def __delete_files(self) -> None: Removes the backup from the c... | Implement the Python class `BackupDelete` described below.
Class description:
Deletes a backup of a host
Method signatures and docstrings:
- def __init__(self, io: BackupPcCloneStyle): Object constructor. @param BackupPcCloneStyle io: The output style.
- def __delete_files(self) -> None: Removes the backup from the c... | a4009868f6cbec42f247f392965077c55f7265c5 | <|skeleton|>
class BackupDelete:
"""Deletes a backup of a host"""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
<|body_0|>
def __delete_files(self) -> None:
"""Removes the backup from the cone file system."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackupDelete:
"""Deletes a backup of a host"""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
self.__io: BackupPcCloneStyle = io
'\n The output style.\n '
self.__host: str = ''
'\n... | the_stack_v2_python_sparse | backuppc_clone/helper/BackupDelete.py | SetBased/BackupPC-Clone | train | 7 |
b313e68fd80438658763cc519ad31869719905e3 | [
"self.filepath = filepath\nself.sheet_name = sheet_name\nself.xls_wb = xlrd.open_workbook(self.filepath)\nself.xls_ws = self.xls_wb.sheet_names()\nself.xls_wl = self.xls_wb.sheet_loaded(self.sheet_name)",
"try:\n xls_ws = self.xls_wb.sheet_by_name(self.sheet_name)\n valid_rows = xls_ws.nrows\n valid_cols... | <|body_start_0|>
self.filepath = filepath
self.sheet_name = sheet_name
self.xls_wb = xlrd.open_workbook(self.filepath)
self.xls_ws = self.xls_wb.sheet_names()
self.xls_wl = self.xls_wb.sheet_loaded(self.sheet_name)
<|end_body_0|>
<|body_start_1|>
try:
xls_ws ... | 工作薄 sheet页 单元格 行 列 | ExcelUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
<|body_0|>
def operate_row(self):
"""行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:"""
... | stack_v2_sparse_classes_75kplus_train_001589 | 3,336 | no_license | [
{
"docstring": "初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称",
"name": "__init__",
"signature": "def __init__(self, filepath, sheet_name='')"
},
{
"docstring": "行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:",
"name": "operate_row",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_033113 | Implement the Python class `ExcelUtil` described below.
Class description:
工作薄 sheet页 单元格 行 列
Method signatures and docstrings:
- def __init__(self, filepath, sheet_name=''): 初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称
- def operate_row(self): 行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用... | Implement the Python class `ExcelUtil` described below.
Class description:
工作薄 sheet页 单元格 行 列
Method signatures and docstrings:
- def __init__(self, filepath, sheet_name=''): 初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称
- def operate_row(self): 行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用... | d885b520757097c1d984d1cdda5d242ee5c6a5d6 | <|skeleton|>
class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
<|body_0|>
def operate_row(self):
"""行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
self.filepath = filepath
self.sheet_name = sheet_name
self.xls_wb = xlrd.open_workbook(self.filepath)
... | the_stack_v2_python_sparse | API_AutoTest/Study/y_xlrd.py | yolotester/learngit | train | 0 |
2382713acf4aaceb8e09d117e2612d6e6b5bc617 | [
"for i in range(rows):\n for j in range(cols):\n if matrix[i * cols + j] == path[0]:\n if self.find(list(matrix), rows, cols, path[1:], i, j):\n return True",
"if not path:\n return True\nmatrix[i * cols + j] = '0'\nif j + 1 < cols and matrix[i * cols + (j + 1)] == path[0]:\... | <|body_start_0|>
for i in range(rows):
for j in range(cols):
if matrix[i * cols + j] == path[0]:
if self.find(list(matrix), rows, cols, path[1:], i, j):
return True
<|end_body_0|>
<|body_start_1|>
if not path:
return Tr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
"""首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵中找到相应的位置。 由于回朔法的递归特性,路径可以被开成一个栈。当在矩阵中定位了路径中前n个字符的位置之后, 在与第n个字符对应的格子的周围都没有找到第n+1个字符,这... | stack_v2_sparse_classes_75kplus_train_001590 | 3,558 | no_license | [
{
"docstring": "首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵中找到相应的位置。 由于回朔法的递归特性,路径可以被开成一个栈。当在矩阵中定位了路径中前n个字符的位置之后, 在与第n个字符对应的格子的周围都没有找到第n+1个字符,这个时候只要在路径上回到第n-1个字符,重新定位第n个字符。 由于路径不能重复进入矩阵的格子,还需要定义和字符矩阵大小一样的布尔值矩阵... | 2 | stack_v2_sparse_classes_30k_train_007473 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): 首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): 首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直... | c756fe54e8e17e9ba0bfdab5fccc24ac89263d90 | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
"""首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵中找到相应的位置。 由于回朔法的递归特性,路径可以被开成一个栈。当在矩阵中定位了路径中前n个字符的位置之后, 在与第n个字符对应的格子的周围都没有找到第n+1个字符,这... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasPath(self, matrix, rows, cols, path):
"""首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的 第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。 除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵中找到相应的位置。 由于回朔法的递归特性,路径可以被开成一个栈。当在矩阵中定位了路径中前n个字符的位置之后, 在与第n个字符对应的格子的周围都没有找到第n+1个字符,这个时候只要在路径上回到第n-... | the_stack_v2_python_sparse | newcoder_offer/has_path.py | EarthChen/LeetCode_Record | train | 0 | |
2037e7c5693e1c0d3a05ed9229553eb3c3cd4a81 | [
"re_string = re.compile('[a-zA-Z0-9]')\nline = ''.join(re_string.findall(s)).lower()\nlenth = len(line)\nfor i in range(lenth // 2):\n if line[i] != line[lenth - i - 1]:\n print(line[i], i)\n return False\nreturn True",
"s = s.lower()\ncharacter = 'abcdefghijklmnopqrstuvwxyz0123456789'\nl = []\nf... | <|body_start_0|>
re_string = re.compile('[a-zA-Z0-9]')
line = ''.join(re_string.findall(s)).lower()
lenth = len(line)
for i in range(lenth // 2):
if line[i] != line[lenth - i - 1]:
print(line[i], i)
return False
return True
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def other_isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re_string = re.compile('[a-zA-Z0-9]')
line = ''.joi... | stack_v2_sparse_classes_75kplus_train_001591 | 1,062 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "other_isPalindrome",
"signature": "def other_isPalindrome(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006876 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def other_isPalindrome(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def other_isPalindrome(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | d156c6a13c89727f80ed6244cae40574395ecf34 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def other_isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
re_string = re.compile('[a-zA-Z0-9]')
line = ''.join(re_string.findall(s)).lower()
lenth = len(line)
for i in range(lenth // 2):
if line[i] != line[lenth - i - 1]:
print(lin... | the_stack_v2_python_sparse | easy/125.py | longhao54/leetcode | train | 0 | |
2687f3033fe05cf24e0ee3c3b53fad5e401b1bd7 | [
"self.cmd = cmd\nself.args = args\nself.kwargs = kwargs",
"if type(self.cmd) is str:\n return eval(self.cmd)\nelse:\n return self.cmd(*self.args, **self.kwargs)"
] | <|body_start_0|>
self.cmd = cmd
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
if type(self.cmd) is str:
return eval(self.cmd)
else:
return self.cmd(*self.args, **self.kwargs)
<|end_body_1|>
| Menu ou la liste des items est calculée dynamiquement | f_menu_dynamic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class f_menu_dynamic:
"""Menu ou la liste des items est calculée dynamiquement"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arguments"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_75kplus_train_001592 | 7,191 | permissive | [
{
"docstring": "Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arguments",
"name": "__init__",
"signature": "def __init__(self, cmd, *args, **kwargs)"
},
{
"docstring": "Execute le code de cmd et renvoie la liste des f_item",
"name": "r... | 2 | null | Implement the Python class `f_menu_dynamic` described below.
Class description:
Menu ou la liste des items est calculée dynamiquement
Method signatures and docstrings:
- def __init__(self, cmd, *args, **kwargs): Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arg... | Implement the Python class `f_menu_dynamic` described below.
Class description:
Menu ou la liste des items est calculée dynamiquement
Method signatures and docstrings:
- def __init__(self, cmd, *args, **kwargs): Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arg... | 46c4f9369964b2f9108f2776bf74f24ccdc71e7f | <|skeleton|>
class f_menu_dynamic:
"""Menu ou la liste des items est calculée dynamiquement"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arguments"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class f_menu_dynamic:
"""Menu ou la liste des items est calculée dynamiquement"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code qui renvoie une liste de f_item Soit du texte, soit une fonction + en option arguments"""
self.cmd = cmd
self.args = args
self... | the_stack_v2_python_sparse | build/lib/FGPIO/f_menu.py | FredThx/FGPIO | train | 0 |
5ba168808aada276dad4aad1a07b340dfb890745 | [
"self.deque = collections.deque([])\nself.dic = {}\nself.capacity = capacity",
"if key not in self.dic:\n return -1\nself.deque.remove(key)\nself.deque.append(key)\nreturn self.dic[key]",
"if key in self.dic:\n self.deque.remove(key)\nelif len(self.dic) == self.capacity:\n v = self.deque.popleft()\n ... | <|body_start_0|>
self.deque = collections.deque([])
self.dic = {}
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.dic:
return -1
self.deque.remove(key)
self.deque.append(key)
return self.dic[key]
<|end_body_1|>
<|body_star... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_001593 | 2,684 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_test_002874 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 9b82e3bd1b404e3cff31469986577ceec3924f73 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.deque = collections.deque([])
self.dic = {}
self.capacity = capacity
def get(self, key):
""":rtype: int"""
if key not in self.dic:
return -1
self.deque.remove(key)
... | the_stack_v2_python_sparse | Python/146. LRU Cache.py | Qiumy/leetcode | train | 0 | |
b0324499c7ea989b7f7f46b3bf63af936c4d4a32 | [
"self.name = name\nself.objective = objective\nself.wrapped_objective = ScoringFunctionWrapper(scoring_function=objective)\nself.contribution_specification = contribution_specification\nself.starting_population = starting_population",
"number_molecules_to_generate = max(self.contribution_specification.top_counts)... | <|body_start_0|>
self.name = name
self.objective = objective
self.wrapped_objective = ScoringFunctionWrapper(scoring_function=objective)
self.contribution_specification = contribution_specification
self.starting_population = starting_population
<|end_body_0|>
<|body_start_1|>
... | This class assesses how well a model is able to generate molecules satisfying a given objective. | GoalDirectedBenchmark | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -... | stack_v2_sparse_classes_75kplus_train_001594 | 5,427 | permissive | [
{
"docstring": "Args: name: Benchmark name objective: Objective for the goal-directed optimization contribution_specification: Specifies how to calculate the global benchmark score",
"name": "__init__",
"signature": "def __init__(self, name: str, objective: ScoringFunction, contribution_specification: S... | 2 | stack_v2_sparse_classes_30k_train_050893 | Implement the Python class `GoalDirectedBenchmark` described below.
Class description:
This class assesses how well a model is able to generate molecules satisfying a given objective.
Method signatures and docstrings:
- def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContrib... | Implement the Python class `GoalDirectedBenchmark` described below.
Class description:
This class assesses how well a model is able to generate molecules satisfying a given objective.
Method signatures and docstrings:
- def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContrib... | 60ebe1f6a396f16e08b834dce448e9343d259feb | <|skeleton|>
class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -> None:
... | the_stack_v2_python_sparse | guacamol/goal_directed_benchmark.py | BenevolentAI/guacamol | train | 328 |
4f7d83c3b987f082420462f0dc96e04463c57693 | [
"def inorder(root, result):\n if root:\n inorder(root.left, result)\n result.append(root.val)\n inorder(root.right, result)\nresult = []\ninorder(root, result)\nreturn result",
"result, stack = ([], [])\nwhile True:\n while root:\n stack.append(root)\n root = root.left\n ... | <|body_start_0|>
def inorder(root, result):
if root:
inorder(root.left, result)
result.append(root.val)
inorder(root.right, result)
result = []
inorder(root, result)
return result
<|end_body_0|>
<|body_start_1|>
result,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def i... | stack_v2_sparse_classes_75kplus_train_001595 | 1,447 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_recursive",
"signature": "def inorderTraversal_recursive(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_iterative",
"signature": "def inorderTraversal_it... | 2 | stack_v2_sparse_classes_30k_train_005290 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iterative(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_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iterative(self, root): :type root: TreeNode :rtype: List[int]
<|skeleto... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
def inorder(root, result):
if root:
inorder(root.left, result)
result.append(root.val)
inorder(root.right, result)
result = []
... | the_stack_v2_python_sparse | code/094_binary-tree-inorder-traversal.py | linhdvu14/leetcode-solutions | train | 2 | |
f6c0c52e91bfe7ad70e12feba311ddf88a5afdac | [
"if metadata:\n msg.update(metadata)\nreturn OrderBookMessage(OrderBookMessageType.SNAPSHOT, {'trading_pair': msg['trading_pair'], 'update_id': msg['lastUpdateId'], 'bids': msg['bids'], 'asks': msg['asks']}, timestamp=timestamp)",
"if metadata:\n msg.update(metadata)\nreturn OrderBookMessage(OrderBookMessag... | <|body_start_0|>
if metadata:
msg.update(metadata)
return OrderBookMessage(OrderBookMessageType.SNAPSHOT, {'trading_pair': msg['trading_pair'], 'update_id': msg['lastUpdateId'], 'bids': msg['bids'], 'asks': msg['asks']}, timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
if metada... | MexcOrderBook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MexcOrderBook:
def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book s... | stack_v2_sparse_classes_75kplus_train_001596 | 3,481 | permissive | [
{
"docstring": "Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book snapshot :param timestamp: the snapshot timestamp :param metadata: a dictionary with extra information to add to the snapshot data :return: a snapshot message... | 3 | stack_v2_sparse_classes_30k_train_029930 | Implement the Python class `MexcOrderBook` described below.
Class description:
Implement the MexcOrderBook class.
Method signatures and docstrings:
- def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage: Creates a snapshot message with the o... | Implement the Python class `MexcOrderBook` described below.
Class description:
Implement the MexcOrderBook class.
Method signatures and docstrings:
- def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage: Creates a snapshot message with the o... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class MexcOrderBook:
def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MexcOrderBook:
def snapshot_message_from_exchange(cls, msg: Dict[str, any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book snapshot :param... | the_stack_v2_python_sparse | hummingbot/connector/exchange/mexc/mexc_order_book.py | CoinAlpha/hummingbot | train | 135 | |
eb0a9606c1d8c12fe4f05db2aa3cc2347705c925 | [
"class X(cls):\n subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(*values)\nX.__name__ = cls.__name__\nreturn X",
"class X(cls):\n subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(minimum, maximum)\nX.__name__ = cls.__name__\nreturn X"
] | <|body_start_0|>
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(*values)
X.__name__ = cls.__name__
return X
<|end_body_0|>
<|body_start_1|>
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(minimum, maxi... | Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the :py:class:`~pysnmp.proto.rfc1902.Integer` type. The :py:class:`~pysnmp.prot... | Integer32 | [
"Apache-2.0",
"PSF-2.0",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"BSD-2-Clause",
"MPL-2.0",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Integer32:
"""Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the :py:class:`~pysnmp.proto.rfc1902.Integ... | stack_v2_sparse_classes_75kplus_train_001597 | 22,493 | permissive | [
{
"docstring": "Creates a subclass with discreet values constraint.",
"name": "withValues",
"signature": "def withValues(cls, *values)"
},
{
"docstring": "Creates a subclass with value range constraint.",
"name": "withRange",
"signature": "def withRange(cls, minimum, maximum)"
}
] | 2 | null | Implement the Python class `Integer32` described below.
Class description:
Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the... | Implement the Python class `Integer32` described below.
Class description:
Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the... | 5099a498edc47ab841965b483c2c32af49eb7dae | <|skeleton|>
class Integer32:
"""Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the :py:class:`~pysnmp.proto.rfc1902.Integ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Integer32:
"""Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the :py:class:`~pysnmp.proto.rfc1902.Integer` type. The... | the_stack_v2_python_sparse | scalyr_agent/third_party/pysnmp/proto/rfc1902.py | scalyr/scalyr-agent-2 | train | 75 |
7832d6c9eda8448515dcca08029e2f8e73b792dc | [
"end = len(numbers) - 1\nstart = 1\nfor index, num in enumerate(numbers):\n find_index = self.find_num(numbers, target - num, index + 1, end)\n if find_index != -1:\n return [index + 1, find_index + 1]",
"if end - start < 2:\n if numbers[start] == target:\n return start\n elif numbers[en... | <|body_start_0|>
end = len(numbers) - 1
start = 1
for index, num in enumerate(numbers):
find_index = self.find_num(numbers, target - num, index + 1, end)
if find_index != -1:
return [index + 1, find_index + 1]
<|end_body_0|>
<|body_start_1|>
if en... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def find_num(self, numbers, target, start, end):
"""return index if target was find, else return -1"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_001598 | 2,289 | no_license | [
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": "return index if target was find, else return -1",
"name": "find_num",
"signature": "def find_num(self, numbers, target, sta... | 2 | stack_v2_sparse_classes_30k_train_029388 | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def find_num(self, numbers, target, start, end): return index if target was ... | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def find_num(self, numbers, target, start, end): return index if target was ... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Solution_1:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def find_num(self, numbers, target, start, end):
"""return index if target was find, else return -1"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution_1:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
end = len(numbers) - 1
start = 1
for index, num in enumerate(numbers):
find_index = self.find_num(numbers, target - num, index + 1, end)
if ... | the_stack_v2_python_sparse | Python/TwoSumIIInputarrayissorted.py | here0009/LeetCode | train | 1 | |
9be0fc98ceb0c3489d117ff5dbb5bd9ed2e967ed | [
"if self.is_removed:\n raise AlreadyRemovedError(self)\nself.is_removed = True\nself.save()",
"if not self.is_removed:\n raise NotRemovedError(self)\nself.is_removed = False\nself.save()"
] | <|body_start_0|>
if self.is_removed:
raise AlreadyRemovedError(self)
self.is_removed = True
self.save()
<|end_body_0|>
<|body_start_1|>
if not self.is_removed:
raise NotRemovedError(self)
self.is_removed = False
self.save()
<|end_body_1|>
| Fake removable mixin | BaseRemovableMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRemovableMixin:
"""Fake removable mixin"""
def remove(self):
"""Remove object"""
<|body_0|>
def restore(self):
"""Restore object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.is_removed:
raise AlreadyRemovedError(self)
... | stack_v2_sparse_classes_75kplus_train_001599 | 2,929 | no_license | [
{
"docstring": "Remove object",
"name": "remove",
"signature": "def remove(self)"
},
{
"docstring": "Restore object",
"name": "restore",
"signature": "def restore(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009886 | Implement the Python class `BaseRemovableMixin` described below.
Class description:
Fake removable mixin
Method signatures and docstrings:
- def remove(self): Remove object
- def restore(self): Restore object | Implement the Python class `BaseRemovableMixin` described below.
Class description:
Fake removable mixin
Method signatures and docstrings:
- def remove(self): Remove object
- def restore(self): Restore object
<|skeleton|>
class BaseRemovableMixin:
"""Fake removable mixin"""
def remove(self):
"""Remo... | 39deb1dc046c80edd6bfdfbef8391842eda35dd2 | <|skeleton|>
class BaseRemovableMixin:
"""Fake removable mixin"""
def remove(self):
"""Remove object"""
<|body_0|>
def restore(self):
"""Restore object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseRemovableMixin:
"""Fake removable mixin"""
def remove(self):
"""Remove object"""
if self.is_removed:
raise AlreadyRemovedError(self)
self.is_removed = True
self.save()
def restore(self):
"""Restore object"""
if not self.is_removed:
... | the_stack_v2_python_sparse | tools/mixins.py | nvbn/djang0byte | train | 26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.