blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
935e87a71f26bbf06e2ff86ac439caf6a26cd48e | [
"if not tf.gfile.Exists(output_dir):\n tf.gfile.MakeDirs(output_dir)\nself.log_file = os.path.join(output_dir, 'debug_{0}.log'.format(time.time()))\nself.log_writer = codecs.getwriter('utf-8')(tf.gfile.GFile(self.log_file, mode='a'))",
"time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())\nlog_line =... | <|body_start_0|>
if not tf.gfile.Exists(output_dir):
tf.gfile.MakeDirs(output_dir)
self.log_file = os.path.join(output_dir, 'debug_{0}.log'.format(time.time()))
self.log_writer = codecs.getwriter('utf-8')(tf.gfile.GFile(self.log_file, mode='a'))
<|end_body_0|>
<|body_start_1|>
... | debug logger | DebugLogger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebugLogger:
"""debug logger"""
def __init__(self, output_dir):
"""initialize debug logger"""
<|body_0|>
def log_print(self, message):
"""log and print debugging message"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not tf.gfile.Exists(outp... | stack_v2_sparse_classes_36k_train_017400 | 860 | permissive | [
{
"docstring": "initialize debug logger",
"name": "__init__",
"signature": "def __init__(self, output_dir)"
},
{
"docstring": "log and print debugging message",
"name": "log_print",
"signature": "def log_print(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013327 | Implement the Python class `DebugLogger` described below.
Class description:
debug logger
Method signatures and docstrings:
- def __init__(self, output_dir): initialize debug logger
- def log_print(self, message): log and print debugging message | Implement the Python class `DebugLogger` described below.
Class description:
debug logger
Method signatures and docstrings:
- def __init__(self, output_dir): initialize debug logger
- def log_print(self, message): log and print debugging message
<|skeleton|>
class DebugLogger:
"""debug logger"""
def __init_... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class DebugLogger:
"""debug logger"""
def __init__(self, output_dir):
"""initialize debug logger"""
<|body_0|>
def log_print(self, message):
"""log and print debugging message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DebugLogger:
"""debug logger"""
def __init__(self, output_dir):
"""initialize debug logger"""
if not tf.gfile.Exists(output_dir):
tf.gfile.MakeDirs(output_dir)
self.log_file = os.path.join(output_dir, 'debug_{0}.log'.format(time.time()))
self.log_writer = codec... | the_stack_v2_python_sparse | sequence_labeling/util/debug_logger.py | stevezheng23/sequence_labeling_tf | train | 18 |
864e4628421c89ff3cbddebaefdd7b201b3f85b5 | [
"parser = ParlaiParser(True, True, 'Index Dense Embs')\nparser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')\nparser.add_argument('--embeddings-name', type=str, default='', help='name of emb part')\nparser.add_argument('--partition-index', type='bool', default=False, help='specify True ... | <|body_start_0|>
parser = ParlaiParser(True, True, 'Index Dense Embs')
parser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')
parser.add_argument('--embeddings-name', type=str, default='', help='name of emb part')
parser.add_argument('--partition-index', type='... | Index Dense Embeddings. | Indexer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
<|body_0|>
def run(self):
"""Load dense embeddings and index with FAISS."""
<|body_1|>
def index_data(self, input_files: List[str], add_only: bool=False):
"""Index ... | stack_v2_sparse_classes_36k_train_017401 | 4,832 | permissive | [
{
"docstring": "Setup args.",
"name": "setup_args",
"signature": "def setup_args(cls)"
},
{
"docstring": "Load dense embeddings and index with FAISS.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Index data. :param input_files: files to load.",
"name": "ind... | 4 | stack_v2_sparse_classes_30k_test_000543 | Implement the Python class `Indexer` described below.
Class description:
Index Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): Setup args.
- def run(self): Load dense embeddings and index with FAISS.
- def index_data(self, input_files: List[str], add_only: bool=False): Index data. :param in... | Implement the Python class `Indexer` described below.
Class description:
Index Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): Setup args.
- def run(self): Load dense embeddings and index with FAISS.
- def index_data(self, input_files: List[str], add_only: bool=False): Index data. :param in... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
<|body_0|>
def run(self):
"""Load dense embeddings and index with FAISS."""
<|body_1|>
def index_data(self, input_files: List[str], add_only: bool=False):
"""Index ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
parser = ParlaiParser(True, True, 'Index Dense Embs')
parser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')
parser.add_argument('--embeddings-name', type=str, default=... | the_stack_v2_python_sparse | parlai/agents/rag/scripts/index_dense_embeddings.py | facebookresearch/ParlAI | train | 10,943 |
9ebb28efcc4ac3c8aeaab8553d75dacd3bed7058 | [
"errors = []\nif not HAS_XMLTODICT:\n errors.append(missing_required_lib('xmltodict'))\nreturn errors",
"errors = self._check_reqs()\nif errors:\n return {'errors': errors}\ncli_output = self._task_args.get('text')\nnetwork_os = self._task_args.get('parser').get('os') or self._task_vars.get('ansible_network... | <|body_start_0|>
errors = []
if not HAS_XMLTODICT:
errors.append(missing_required_lib('xmltodict'))
return errors
<|end_body_0|>
<|body_start_1|>
errors = self._check_reqs()
if errors:
return {'errors': errors}
cli_output = self._task_args.get('te... | The xml parser class Convert an xml string to structured data using xmltodict | CliParser | [
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The xml parser class Convert an xml string to structured data using xmltodict"""
def _check_reqs():
"""Check the prerequisites for the xml parser"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry point for a cli_parse parse execution :r... | stack_v2_sparse_classes_36k_train_017402 | 3,113 | permissive | [
{
"docstring": "Check the prerequisites for the xml parser",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: dict :example: The parse function of a parser should r... | 2 | null | Implement the Python class `CliParser` described below.
Class description:
The xml parser class Convert an xml string to structured data using xmltodict
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the xml parser
- def parse(self, *_args, **_kwargs): Std entry point for a cli_par... | Implement the Python class `CliParser` described below.
Class description:
The xml parser class Convert an xml string to structured data using xmltodict
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the xml parser
- def parse(self, *_args, **_kwargs): Std entry point for a cli_par... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The xml parser class Convert an xml string to structured data using xmltodict"""
def _check_reqs():
"""Check the prerequisites for the xml parser"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry point for a cli_parse parse execution :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CliParser:
"""The xml parser class Convert an xml string to structured data using xmltodict"""
def _check_reqs():
"""Check the prerequisites for the xml parser"""
errors = []
if not HAS_XMLTODICT:
errors.append(missing_required_lib('xmltodict'))
return errors
... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/utils/plugins/sub_plugins/cli_parser/xml_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
91348565fddc4a632122c9631420f5743194c37e | [
"in_file = open('islostarepeat.txt', 'r').read()\ninput1 = in_file[0:100]\ninput2 = BaseCase.w.get_webpage('http://www.islostarepeat.com')\ninput2 = input2[0:100]\nassert input1 == input2",
"s = 'http://www.yr.no/place/Norway/Østfold/Sarpsborg/Hannestad/forecast.xml'\nss = BaseCase.xml_link_dict['Ostfold-Sarpsbor... | <|body_start_0|>
in_file = open('islostarepeat.txt', 'r').read()
input1 = in_file[0:100]
input2 = BaseCase.w.get_webpage('http://www.islostarepeat.com')
input2 = input2[0:100]
assert input1 == input2
<|end_body_0|>
<|body_start_1|>
s = 'http://www.yr.no/place/Norway/Østf... | TestCase1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase1:
def test_one(self):
"""4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document."""
<|body_0|>
def test_two(self):
"""4.2 Check if Hannestad creates the link http://www.yr.no/place/Norway/ stfold/Sa... | stack_v2_sparse_classes_36k_train_017403 | 3,385 | no_license | [
{
"docstring": "4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document.",
"name": "test_one",
"signature": "def test_one(self)"
},
{
"docstring": "4.2 Check if Hannestad creates the link http://www.yr.no/place/Norway/ stfold/Sarpsborg/H... | 6 | stack_v2_sparse_classes_30k_train_019349 | Implement the Python class `TestCase1` described below.
Class description:
Implement the TestCase1 class.
Method signatures and docstrings:
- def test_one(self): 4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document.
- def test_two(self): 4.2 Check if Hanne... | Implement the Python class `TestCase1` described below.
Class description:
Implement the TestCase1 class.
Method signatures and docstrings:
- def test_one(self): 4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document.
- def test_two(self): 4.2 Check if Hanne... | 5ed8867c21d96332bd687ef7de7827af822cf8a4 | <|skeleton|>
class TestCase1:
def test_one(self):
"""4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document."""
<|body_0|>
def test_two(self):
"""4.2 Check if Hannestad creates the link http://www.yr.no/place/Norway/ stfold/Sa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase1:
def test_one(self):
"""4.1 Download the page for reference: http://www.islostarepeat.com/ Check if your program creates the same document."""
in_file = open('islostarepeat.txt', 'r').read()
input1 = in_file[0:100]
input2 = BaseCase.w.get_webpage('http://www.islostare... | the_stack_v2_python_sparse | weather_forecast/test_program.py | inavangen/Python | train | 0 | |
eac34677b256ce5527eb4b12698be65fa4ca9717 | [
"super(GraphAttentionLayer, self).__init__()\nself.output_dim = output_dim\nself.W = nn.Parameter(torch.Tensor(input_dim, output_dim))\nself.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))\nif bias:\n self.bias = nn.Parameter(torch.FloatTensor(output_dim))\nelse:\n self.register_parameter('bias', None)\nsel... | <|body_start_0|>
super(GraphAttentionLayer, self).__init__()
self.output_dim = output_dim
self.W = nn.Parameter(torch.Tensor(input_dim, output_dim))
self.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))
if bias:
self.bias = nn.Parameter(torch.FloatTensor(output_dim))... | Graph Attention层 (dense input) | GraphAttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: bo... | stack_v2_sparse_classes_36k_train_017404 | 6,215 | permissive | [
{
"docstring": "Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean, 是否使用偏置",
"name": "__init__",
"signature": "def __init__(self, input_dim, output_dim, dropout, alpha, bias=True)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_018341 | Implement the Python class `GraphAttentionLayer` described below.
Class description:
Graph Attention层 (dense input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout... | Implement the Python class `GraphAttentionLayer` described below.
Class description:
Graph Attention层 (dense input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphAttentionLayer:
"""Graph Attention层 (dense input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (dense input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean, 是否使用偏置... | the_stack_v2_python_sparse | Node/GAT/script/layers.py | robbinc91/GNN-Pytorch | train | 0 |
e2671ef3ec11f82e4070e8f740b54abe4796c0fb | [
"scripts = ['core_parser_app/js/builtin/autocomplete.js'] + scripts\nAbstractModule.__init__(self, scripts=scripts, styles=styles)\nself.label = label",
"params = {}\nif self.data != '':\n params['value'] = self.data\nif self.label is not None:\n params.update({'label': self.label})\nreturn AbstractModule.r... | <|body_start_0|>
scripts = ['core_parser_app/js/builtin/autocomplete.js'] + scripts
AbstractModule.__init__(self, scripts=scripts, styles=styles)
self.label = label
<|end_body_0|>
<|body_start_1|>
params = {}
if self.data != '':
params['value'] = self.data
if... | AutoCompleteModule class | AbstractAutoCompleteModule | [
"NIST-Software",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractAutoCompleteModule:
"""AutoCompleteModule class"""
def __init__(self, scripts=list(), styles=list(), label=None):
"""Initialize the module Args: scripts: styles: label:"""
<|body_0|>
def _render_module(self, request):
"""Return the module Args: request: R... | stack_v2_sparse_classes_36k_train_017405 | 1,022 | permissive | [
{
"docstring": "Initialize the module Args: scripts: styles: label:",
"name": "__init__",
"signature": "def __init__(self, scripts=list(), styles=list(), label=None)"
},
{
"docstring": "Return the module Args: request: Returns:",
"name": "_render_module",
"signature": "def _render_module... | 2 | stack_v2_sparse_classes_30k_train_012298 | Implement the Python class `AbstractAutoCompleteModule` described below.
Class description:
AutoCompleteModule class
Method signatures and docstrings:
- def __init__(self, scripts=list(), styles=list(), label=None): Initialize the module Args: scripts: styles: label:
- def _render_module(self, request): Return the mo... | Implement the Python class `AbstractAutoCompleteModule` described below.
Class description:
AutoCompleteModule class
Method signatures and docstrings:
- def __init__(self, scripts=list(), styles=list(), label=None): Initialize the module Args: scripts: styles: label:
- def _render_module(self, request): Return the mo... | cef5e0f040c87e5fb224c59f90c314a6944e4d6b | <|skeleton|>
class AbstractAutoCompleteModule:
"""AutoCompleteModule class"""
def __init__(self, scripts=list(), styles=list(), label=None):
"""Initialize the module Args: scripts: styles: label:"""
<|body_0|>
def _render_module(self, request):
"""Return the module Args: request: R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractAutoCompleteModule:
"""AutoCompleteModule class"""
def __init__(self, scripts=list(), styles=list(), label=None):
"""Initialize the module Args: scripts: styles: label:"""
scripts = ['core_parser_app/js/builtin/autocomplete.js'] + scripts
AbstractModule.__init__(self, scri... | the_stack_v2_python_sparse | core_parser_app/tools/modules/views/builtin/autocomplete_module.py | usnistgov/core_parser_app | train | 0 |
c312385f697b9726c7880d92384711f19633f833 | [
"res = []\n\ndef dfs(root, res):\n if root:\n res.append(str(root.val) + ',')\n dfs(root.left, res)\n dfs(root.right, res)\n else:\n res.append('None,')\ndfs(root, res)\nreturn ''.join(res)",
"data = data.split(',')[:-1]\n\ndef buildTree(data):\n if not data:\n return N... | <|body_start_0|>
res = []
def dfs(root, res):
if root:
res.append(str(root.val) + ',')
dfs(root.left, res)
dfs(root.right, res)
else:
res.append('None,')
dfs(root, res)
return ''.join(res)
<|end_body... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017406 | 1,623 | 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_test_000814 | 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:... | 51705d6cf13052dde293dedb75199390ba3b6e53 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def dfs(root, res):
if root:
res.append(str(root.val) + ',')
dfs(root.left, res)
dfs(root.right, res)
... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree.py | simplynaive/LeetCode | train | 0 | |
9985ad5a9da7f1ecff015b98289933f01f11d8e2 | [
"self_keys = {'name': self.name}\nnatural_keys = super(CategoryLevel, self).natural_key(self_keys)\nreturn natural_keys",
"next_name = 'L{n}'.format(n=int(self.name[1:]) + 1)\ntry:\n level = CategoryLevel.objects.get(name=next_name)\nexcept ObjectDoesNotExist as e:\n level = CategoryLevel.objects.create_lev... | <|body_start_0|>
self_keys = {'name': self.name}
natural_keys = super(CategoryLevel, self).natural_key(self_keys)
return natural_keys
<|end_body_0|>
<|body_start_1|>
next_name = 'L{n}'.format(n=int(self.name[1:]) + 1)
try:
level = CategoryLevel.objects.get(name=next_... | Provide Category level table | CategoryLevel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryLevel:
"""Provide Category level table"""
def natural_key(self, *args, **kwargs):
"""Overrides base class method :param args: :param kwargs: :return:"""
<|body_0|>
def next_level(self):
"""Returns next level :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_017407 | 981 | no_license | [
{
"docstring": "Overrides base class method :param args: :param kwargs: :return:",
"name": "natural_key",
"signature": "def natural_key(self, *args, **kwargs)"
},
{
"docstring": "Returns next level :return:",
"name": "next_level",
"signature": "def next_level(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010162 | Implement the Python class `CategoryLevel` described below.
Class description:
Provide Category level table
Method signatures and docstrings:
- def natural_key(self, *args, **kwargs): Overrides base class method :param args: :param kwargs: :return:
- def next_level(self): Returns next level :return: | Implement the Python class `CategoryLevel` described below.
Class description:
Provide Category level table
Method signatures and docstrings:
- def natural_key(self, *args, **kwargs): Overrides base class method :param args: :param kwargs: :return:
- def next_level(self): Returns next level :return:
<|skeleton|>
cla... | a93e0eee39e1f45fa73de84514ca254e235a17bd | <|skeleton|>
class CategoryLevel:
"""Provide Category level table"""
def natural_key(self, *args, **kwargs):
"""Overrides base class method :param args: :param kwargs: :return:"""
<|body_0|>
def next_level(self):
"""Returns next level :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryLevel:
"""Provide Category level table"""
def natural_key(self, *args, **kwargs):
"""Overrides base class method :param args: :param kwargs: :return:"""
self_keys = {'name': self.name}
natural_keys = super(CategoryLevel, self).natural_key(self_keys)
return natural_... | the_stack_v2_python_sparse | cashapp_models/models/CategoryLevelModel.py | dmitryshepelev/cashapp | train | 0 |
9bc1553fb682dc3a39650cb2b9ee1b3c9e213a1a | [
"assert os.path.exists(template_path), 'Expected the path %s to exist' % template_path\nassert isinstance(out_dir_path, str), 'Expected `out_dir_path` to be a string'\nif not os.path.exists(out_dir_path):\n mkpath(out_dir_path)\nwith open(template_path, mode='r') as f:\n variables_and_template = yaml.load_all... | <|body_start_0|>
assert os.path.exists(template_path), 'Expected the path %s to exist' % template_path
assert isinstance(out_dir_path, str), 'Expected `out_dir_path` to be a string'
if not os.path.exists(out_dir_path):
mkpath(out_dir_path)
with open(template_path, mode='r') a... | Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified. | ConfigGenerator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigGenerator:
"""Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified."""
def __init__(self, template_p... | stack_v2_sparse_classes_36k_train_017408 | 5,965 | permissive | [
{
"docstring": "Initialize the generator. The generator loads the template from the specified path and ensures that the path `out_dir_path` exists by creating all missing folders along the path if necessary. Args: template_path (str): Path to the template out_dir_path (str): Path that indicates where generated ... | 4 | stack_v2_sparse_classes_30k_train_011999 | Implement the Python class `ConfigGenerator` described below.
Class description:
Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified... | Implement the Python class `ConfigGenerator` described below.
Class description:
Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified... | b47b5e460e9f4425d06af8a56499bb4f4dbecc3a | <|skeleton|>
class ConfigGenerator:
"""Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified."""
def __init__(self, template_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigGenerator:
"""Objects of this class can be used to generate specific configuration files from templates. A template consists of a configuration file template with variables (strings) to replace. For each variable, a value interval needs to be specified."""
def __init__(self, template_path, out_dir_... | the_stack_v2_python_sparse | mtl-sequence-tagging-framework/src/ConfigGenerator.py | UKPLab/germeval2017-sentiment-detection | train | 13 |
ff3dda7d0cd1d7d16000e7f8d65e71e9e6148d1f | [
"self.filename = filename\nself.app = TK.Tk()\nself.app.title('Photo View Demo')\nmenubar = TK.Menu(self.app)\nfilemenu = TK.Menu(menubar, tearoff=0)\nfilemenu.add_command(label='Open', command=self.open_file)\nfilemenu.add_command(label='Exit', command=self.app.destroy)\nmenubar.add_cascade(label='File', menu=file... | <|body_start_0|>
self.filename = filename
self.app = TK.Tk()
self.app.title('Photo View Demo')
menubar = TK.Menu(self.app)
filemenu = TK.Menu(menubar, tearoff=0)
filemenu.add_command(label='Open', command=self.open_file)
filemenu.add_command(label='Exit', command=... | PhotoGui | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
<|body_0|>
def open_file(self):
"""Request select a photo"""
<|body_1|>
def disp_preview(self):
"""Display preview and details"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_017409 | 3,631 | permissive | [
{
"docstring": "Create a test GUI",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Request select a photo",
"name": "open_file",
"signature": "def open_file(self)"
},
{
"docstring": "Display preview and details",
"name": "disp_preview"... | 3 | stack_v2_sparse_classes_30k_train_001605 | Implement the Python class `PhotoGui` described below.
Class description:
Implement the PhotoGui class.
Method signatures and docstrings:
- def __init__(self, filename=None): Create a test GUI
- def open_file(self): Request select a photo
- def disp_preview(self): Display preview and details | Implement the Python class `PhotoGui` described below.
Class description:
Implement the PhotoGui class.
Method signatures and docstrings:
- def __init__(self, filename=None): Create a test GUI
- def open_file(self): Request select a photo
- def disp_preview(self): Display preview and details
<|skeleton|>
class Photo... | cfba2860145978904d1dd427f2326efeccfc561a | <|skeleton|>
class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
<|body_0|>
def open_file(self):
"""Request select a photo"""
<|body_1|>
def disp_preview(self):
"""Display preview and details"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
self.filename = filename
self.app = TK.Tk()
self.app.title('Photo View Demo')
menubar = TK.Menu(self.app)
filemenu = TK.Menu(menubar, tearoff=0)
filemenu.add_command(label='Open', comma... | the_stack_v2_python_sparse | chapter_03/tkphotohandler.py | packtjaniceg/Raspberry-Pi-4-Cookbook-for-Python-Programmers-Fourth-Edition | train | 0 | |
1d7ee4d6487cb006fa1123eb93463030b1521eab | [
"super(SelfAttentionPooling, self).__init__()\nself.keep_ratio = keep_ratio\nself.act = nn.Tanh()\nself.gcn = GraphConvolution(input_dim, 1)\nreturn",
"node_score = self.gcn(adjacency, X)\nnode_score = self.act(node_score)\nmask = topk(node_score, graph_batch, self.keep_ratio)\nmask_X = X[mask] * node_score.view(... | <|body_start_0|>
super(SelfAttentionPooling, self).__init__()
self.keep_ratio = keep_ratio
self.act = nn.Tanh()
self.gcn = GraphConvolution(input_dim, 1)
return
<|end_body_0|>
<|body_start_1|>
node_score = self.gcn(adjacency, X)
node_score = self.act(node_score)
... | 自注意力机制池化层 | SelfAttentionPooling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttentionPooling:
"""自注意力机制池化层"""
def __init__(self, input_dim, keep_ratio):
"""自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio: float, 每个图中topk的节点占所有节点的比例"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_017410 | 5,537 | permissive | [
{
"docstring": "自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio: float, 每个图中topk的节点占所有节点的比例",
"name": "__init__",
"signature": "def __init__(self, input_dim, keep_ratio)"
},
{
"docstring": "自注意力机制池化层前馈... | 2 | stack_v2_sparse_classes_30k_train_019477 | Implement the Python class `SelfAttentionPooling` described below.
Class description:
自注意力机制池化层
Method signatures and docstrings:
- def __init__(self, input_dim, keep_ratio): 自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio:... | Implement the Python class `SelfAttentionPooling` described below.
Class description:
自注意力机制池化层
Method signatures and docstrings:
- def __init__(self, input_dim, keep_ratio): 自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio:... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class SelfAttentionPooling:
"""自注意力机制池化层"""
def __init__(self, input_dim, keep_ratio):
"""自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio: float, 每个图中topk的节点占所有节点的比例"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttentionPooling:
"""自注意力机制池化层"""
def __init__(self, input_dim, keep_ratio):
"""自注意力机制池化层 使用GCN计算每个图中的每个节点的score作为重要性, 筛选每个图中topk个重要的节点, 获取重要节点的邻接矩阵, 使用重要节点特征和邻接矩阵用于后续操作 Inputs: ------- input_dim: int, 输入的节点特征数量 keep_ratio: float, 每个图中topk的节点占所有节点的比例"""
super(SelfAttentionPooling, sel... | the_stack_v2_python_sparse | Graph/SAGPool/script/layers.py | robbinc91/GNN-Pytorch | train | 0 |
3cc4f180878e97fe9a9e379189e688bdf950b0e6 | [
"self.best_clf = best_clf\nself.min_max_scaler = min_max_scaler\nself.clustering = False\nself.polynomial = False\nif clustering_obj is not None:\n self.clustering_obj = clustering_obj\n self.clustering = True\nif best_features is not None:\n self.best_features = best_features\nif best_features_poly is not... | <|body_start_0|>
self.best_clf = best_clf
self.min_max_scaler = min_max_scaler
self.clustering = False
self.polynomial = False
if clustering_obj is not None:
self.clustering_obj = clustering_obj
self.clustering = True
if best_features is not None:
... | Class to use best model output from AML_MS .Use this class to deploy trainied classifiers. | Predictor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. P... | stack_v2_sparse_classes_36k_train_017411 | 3,923 | permissive | [
{
"docstring": "Use Pickle files from CoreML to deploy the classifier. Parameters: best_clf (object): classifier from CoreML min_max_scaler (object) clustering_obj (object) best_features (list) best_features_poly (list) poly_obj (object)",
"name": "__init__",
"signature": "def __init__(self, best_clf, m... | 3 | stack_v2_sparse_classes_30k_train_019441 | Implement the Python class `Predictor` described below.
Class description:
Class to use best model output from AML_MS .Use this class to deploy trainied classifiers.
Method signatures and docstrings:
- def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):... | Implement the Python class `Predictor` described below.
Class description:
Class to use best model output from AML_MS .Use this class to deploy trainied classifiers.
Method signatures and docstrings:
- def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):... | 22806f3ed2e102363d44e4e78a35c39381c846a9 | <|skeleton|>
class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predictor:
"""Class to use best model output from AML_MS .Use this class to deploy trainied classifiers."""
def __init__(self, best_clf, min_max_scaler, clustering_obj, best_features, best_features_poly, poly_obj, encoders):
"""Use Pickle files from CoreML to deploy the classifier. Parameters: be... | the_stack_v2_python_sparse | Classes/Predictor.py | gariciodaro/MLDiagnosisTool | train | 1 |
05720cf49161e4e7ee89a94e5b97bf749bae35e3 | [
"self.scales = scales\nself.img_scale_mode = img_scale_mode\nself.inclPixelStats = inclPixelStats",
"if isinstance(image, torch.Tensor):\n image = image.numpy()\nimage = np.squeeze(image)\nassert image.ndim == 2\na = Analysis(image, nsc=self.scales, scale_mode=self.img_scale_mode)\na.computeFeatures()\njointSt... | <|body_start_0|>
self.scales = scales
self.img_scale_mode = img_scale_mode
self.inclPixelStats = inclPixelStats
<|end_body_0|>
<|body_start_1|>
if isinstance(image, torch.Tensor):
image = image.numpy()
image = np.squeeze(image)
assert image.ndim == 2
... | Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(gsImage) OR psfeatures = PSTMfeatures() m... | PSTMfeatures | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSTMfeatures:
"""Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(g... | stack_v2_sparse_classes_36k_train_017412 | 2,751 | permissive | [
{
"docstring": "Initialize all parameters needed to analyze a texture image. Args: scales: spatial neighborhood of autocorrelations is Na x Na coefficients (must be odd) img_scale_mode: default None. 'rescale01', 'norm255'",
"name": "__init__",
"signature": "def __init__(self, scales=2, img_scale_mode=N... | 2 | stack_v2_sparse_classes_30k_train_007466 | Implement the Python class `PSTMfeatures` described below.
Class description:
Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ======... | Implement the Python class `PSTMfeatures` described below.
Class description:
Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ======... | 08476d21ce17cc95180525d48202a1690dfc8a08 | <|skeleton|>
class PSTMfeatures:
"""Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSTMfeatures:
"""Extracts Portilla & Simoncelli Texture Model features. [1] Portilla & Simoncelli (2000). A parametric texture model based on joint statistics of complex wavelet coefficients. http://www.cns.nyu.edu/pub/lcv/portilla99-reprint.pdf Usage ====== transform = PSTMfeatures() transform(gsImage) OR ps... | the_stack_v2_python_sparse | ummon/features/psTMfeatures.py | matherm/ummon3 | train | 1 |
fd379d9098a3871381bb7b335acf55cdac964bf5 | [
"if obj:\n return obj.data.get(settings.MSPRAY_USER_LATLNG_FIELD)\nreturn None",
"if obj and obj.geom:\n return '{},{}'.format(obj.geom.coords[1], obj.geom.coords[0])\nreturn None",
"user_latlng = obj.data.get(settings.MSPRAY_USER_LATLNG_FIELD)\nif obj and obj.geom and user_latlng:\n latlong = [float(x... | <|body_start_0|>
if obj:
return obj.data.get(settings.MSPRAY_USER_LATLNG_FIELD)
return None
<|end_body_0|>
<|body_start_1|>
if obj and obj.geom:
return '{},{}'.format(obj.geom.coords[1], obj.geom.coords[0])
return None
<|end_body_1|>
<|body_start_2|>
use... | Serliazer for SpraDay object that calculates field between structure and user | UserDistanceSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDistanceSerializer:
"""Serliazer for SpraDay object that calculates field between structure and user"""
def get_user_latlng(self, obj):
"""Return user latlng value"""
<|body_0|>
def get_structure_latlng(self, obj):
"""Return structure latlng value"""
... | stack_v2_sparse_classes_36k_train_017413 | 8,779 | permissive | [
{
"docstring": "Return user latlng value",
"name": "get_user_latlng",
"signature": "def get_user_latlng(self, obj)"
},
{
"docstring": "Return structure latlng value",
"name": "get_structure_latlng",
"signature": "def get_structure_latlng(self, obj)"
},
{
"docstring": "Return dist... | 3 | null | Implement the Python class `UserDistanceSerializer` described below.
Class description:
Serliazer for SpraDay object that calculates field between structure and user
Method signatures and docstrings:
- def get_user_latlng(self, obj): Return user latlng value
- def get_structure_latlng(self, obj): Return structure lat... | Implement the Python class `UserDistanceSerializer` described below.
Class description:
Serliazer for SpraDay object that calculates field between structure and user
Method signatures and docstrings:
- def get_user_latlng(self, obj): Return user latlng value
- def get_structure_latlng(self, obj): Return structure lat... | b3e0f4b5855abbf0298de6b66f2e9f472f2bf838 | <|skeleton|>
class UserDistanceSerializer:
"""Serliazer for SpraDay object that calculates field between structure and user"""
def get_user_latlng(self, obj):
"""Return user latlng value"""
<|body_0|>
def get_structure_latlng(self, obj):
"""Return structure latlng value"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDistanceSerializer:
"""Serliazer for SpraDay object that calculates field between structure and user"""
def get_user_latlng(self, obj):
"""Return user latlng value"""
if obj:
return obj.data.get(settings.MSPRAY_USER_LATLNG_FIELD)
return None
def get_structure_... | the_stack_v2_python_sparse | mspray/apps/alerts/serializers.py | Frazerbesa/mspray | train | 0 |
adce66832b81a20de12dbf8311df36ab7f742928 | [
"prev = Direction.BOTTOM\nfor dir in Direction:\n if dir is self:\n return prev\n prev = dir",
"prev = Direction.BOTTOM\nfor dir in Direction:\n if prev is self:\n return dir\n prev = dir"
] | <|body_start_0|>
prev = Direction.BOTTOM
for dir in Direction:
if dir is self:
return prev
prev = dir
<|end_body_0|>
<|body_start_1|>
prev = Direction.BOTTOM
for dir in Direction:
if prev is self:
return dir
... | Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction. | Direction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Direction:
"""Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction."""
def previous(self):
"""Get the previous direction to the current one when seen clockwise. :return: Next direction when rotated anti... | stack_v2_sparse_classes_36k_train_017414 | 940 | no_license | [
{
"docstring": "Get the previous direction to the current one when seen clockwise. :return: Next direction when rotated anti-clockwise",
"name": "previous",
"signature": "def previous(self)"
},
{
"docstring": "Get the next direction to the current one when seen clockwise. :return: Next direction... | 2 | stack_v2_sparse_classes_30k_train_008828 | Implement the Python class `Direction` described below.
Class description:
Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction.
Method signatures and docstrings:
- def previous(self): Get the previous direction to the current one when ... | Implement the Python class `Direction` described below.
Class description:
Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction.
Method signatures and docstrings:
- def previous(self): Get the previous direction to the current one when ... | 7cdba26e3e75977beb0ce2f141169284869c2707 | <|skeleton|>
class Direction:
"""Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction."""
def previous(self):
"""Get the previous direction to the current one when seen clockwise. :return: Next direction when rotated anti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Direction:
"""Defines directions available in clock-wise direction. The system just add the value to get the new cell value in the related direction."""
def previous(self):
"""Get the previous direction to the current one when seen clockwise. :return: Next direction when rotated anti-clockwise"""... | the_stack_v2_python_sparse | vacuum-cleaner-agent/vacuum-cleaner-agent/states/direction.py | bhparijat/AI-CS-531 | train | 1 |
a1fe1caa826c744feb3141079b9f4d5050531ecb | [
"if not param:\n param = Credit.credit_param()\nresult = 0.0\nresult_details = {}\nfor factor, p in param.iteritems():\n user_data = profile.get_credit_data(factor)\n if not user_data:\n c_data = p.default_value\n else:\n c_data = p.get_data_level(user_data)\n result += c_data * p.weigh... | <|body_start_0|>
if not param:
param = Credit.credit_param()
result = 0.0
result_details = {}
for factor, p in param.iteritems():
user_data = profile.get_credit_data(factor)
if not user_data:
c_data = p.default_value
else:
... | Credit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
<|body_0|>
def credit_param(source='weibo'):
"""取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not param:
param = Credit.credit_para... | stack_v2_sparse_classes_36k_train_017415 | 2,678 | no_license | [
{
"docstring": "计算用户的信用评分",
"name": "get_profile_credit",
"signature": "def get_profile_credit(profile, param=None)"
},
{
"docstring": "取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]",
"name": "credit_param",
"signature": "def credit_param(source='weibo')"
}
] | 2 | null | Implement the Python class `Credit` described below.
Class description:
Implement the Credit class.
Method signatures and docstrings:
- def get_profile_credit(profile, param=None): 计算用户的信用评分
- def credit_param(source='weibo'): 取得信用评分参数 参数名:[1,2,3,4,5,6,7,10] | Implement the Python class `Credit` described below.
Class description:
Implement the Credit class.
Method signatures and docstrings:
- def get_profile_credit(profile, param=None): 计算用户的信用评分
- def credit_param(source='weibo'): 取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]
<|skeleton|>
class Credit:
def get_profile_credit(pro... | 96ed049eb398c4c188a688e9c1bc2fe8cd2dc80b | <|skeleton|>
class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
<|body_0|>
def credit_param(source='weibo'):
"""取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
if not param:
param = Credit.credit_param()
result = 0.0
result_details = {}
for factor, p in param.iteritems():
user_data = profile.get_credit_data(factor)
if not u... | the_stack_v2_python_sparse | other_projects/python/WeiboAds/src/Weibo/credit/credit_service.py | github188/demodemo | train | 1 | |
8cf82579b9009fbccb5335b99d74f667b681244d | [
"super(TextSubNet, self).__init__()\nif num_layers == 1:\n dropout = 0.0\nself.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)\nself.dropout = nn.Dropout(dropout)\nself.linear_1 = nn.Linear(hidden_size, out_size)",
"_, final_states = se... | <|body_start_0|>
super(TextSubNet, self).__init__()
if num_layers == 1:
dropout = 0.0
self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)
self.dropout = nn.Dropout(dropout)
self.linear_1 = nn.... | The LSTM-based subnetwork that is used in TFN for text | TextSubNet | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers ... | stack_v2_sparse_classes_36k_train_017416 | 3,873 | permissive | [
{
"docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dropout: dropout probability bidirectional: specify usage of bidirectional LSTM Output: (return value in forward) a tensor of shape (batch_size, out_size)",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_013532 | Implement the Python class `TextSubNet` described below.
Class description:
The LSTM-based subnetwork that is used in TFN for text
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden ... | Implement the Python class `TextSubNet` described below.
Class description:
The LSTM-based subnetwork that is used in TFN for text
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False): Args: in_size: input dimension hidden_size: hidden ... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextSubNet:
"""The LSTM-based subnetwork that is used in TFN for text"""
def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):
"""Args: in_size: input dimension hidden_size: hidden layer dimension num_layers: specify the number of layers of LSTMs. dro... | the_stack_v2_python_sparse | PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/subNets/FeatureNets.py | Ascend/ModelZoo-PyTorch | train | 23 |
5d7122dd24dd83aff2cba2f915cb76683e8e0927 | [
"d = {c: [-1, -1] for c in string.ascii_uppercase}\nres = 0\nfor i, c in enumerate(s):\n i0, i1 = d[c]\n res += (i - i1) * (i1 - i0)\n d[c] = [d[c][1], i]\nfor i0, i1 in d.values():\n res += (len(s) - i1) * (i1 - i0)\nreturn res",
"visited = set()\n\ndef dfs(i: int, j: int, d: Dict[str, int], u: int) ... | <|body_start_0|>
d = {c: [-1, -1] for c in string.ascii_uppercase}
res = 0
for i, c in enumerate(s):
i0, i1 = d[c]
res += (i - i1) * (i1 - i0)
d[c] = [d[c][1], i]
for i0, i1 in d.values():
res += (len(s) - i1) * (i1 - i0)
return res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniqueLetterString(self, s: str) -> int:
"""O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)"""
<|body_0|>
def uniqueLetterString(self, s: str) -> int:
"""DFS로 모든 케이스를 다 돌면서 계산하면 되긴함. O(N^2) / O(N^2) (S : s... | stack_v2_sparse_classes_36k_train_017417 | 1,871 | no_license | [
{
"docstring": "O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)",
"name": "uniqueLetterString",
"signature": "def uniqueLetterString(self, s: str) -> int"
},
{
"docstring": "DFS로 모든 케이스를 다 돌면서 계산하면 되긴함. O(N^2) / O(N^2) (S : s 내 문자수) Time Limit Exce... | 2 | stack_v2_sparse_classes_30k_train_007726 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueLetterString(self, s: str) -> int: O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)
- def uniqueLetterString(self, s: str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniqueLetterString(self, s: str) -> int: O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)
- def uniqueLetterString(self, s: str... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def uniqueLetterString(self, s: str) -> int:
"""O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)"""
<|body_0|>
def uniqueLetterString(self, s: str) -> int:
"""DFS로 모든 케이스를 다 돌면서 계산하면 되긴함. O(N^2) / O(N^2) (S : s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniqueLetterString(self, s: str) -> int:
"""O(N) 혹은 O(NlogN) 으로 줄일 수 있는 방법? 각 자리의 문자별로 생각해보자. 양 옆으로 동일한 문자가 또 나오기 전까지 확장할 수 있음. O(N) / O(1)"""
d = {c: [-1, -1] for c in string.ascii_uppercase}
res = 0
for i, c in enumerate(s):
i0, i1 = d[c]
... | the_stack_v2_python_sparse | Leetcode/828.py | hanwgyu/algorithm_problem_solving | train | 5 | |
c207f521c816f76bc624a1d1cd0fdc9eb4258e13 | [
"self.input_layer = input_layer\nself.loss_function = loss_function\nself.target_var = T.matrix('target')\nself.mask_var = T.matrix('mask')\nif aggregation not in self._valid_aggregation:\n raise ValueError(\"aggregation must be 'mean', 'sum', 'normalized_sum' or None, not {0}\".format(aggregation))\nself.aggreg... | <|body_start_0|>
self.input_layer = input_layer
self.loss_function = loss_function
self.target_var = T.matrix('target')
self.mask_var = T.matrix('mask')
if aggregation not in self._valid_aggregation:
raise ValueError("aggregation must be 'mean', 'sum', 'normalized_sum... | MaskedObjective | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskedObjective:
def __init__(self, input_layer, loss_function=mse, aggregation='mean'):
"""Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction given its input - loss_function : a loss function of the form `f(x, t, m)` that returns a scalar loss giv... | stack_v2_sparse_classes_36k_train_017418 | 6,976 | permissive | [
{
"docstring": "Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction given its input - loss_function : a loss function of the form `f(x, t, m)` that returns a scalar loss given tensors that represent the predicted values, true values and mask as arguments. - aggregation : e... | 2 | stack_v2_sparse_classes_30k_train_004028 | Implement the Python class `MaskedObjective` described below.
Class description:
Implement the MaskedObjective class.
Method signatures and docstrings:
- def __init__(self, input_layer, loss_function=mse, aggregation='mean'): Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction g... | Implement the Python class `MaskedObjective` described below.
Class description:
Implement the MaskedObjective class.
Method signatures and docstrings:
- def __init__(self, input_layer, loss_function=mse, aggregation='mean'): Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction g... | 54b4c07fb9cf39a0fc84f5e384a9fc855f9d016f | <|skeleton|>
class MaskedObjective:
def __init__(self, input_layer, loss_function=mse, aggregation='mean'):
"""Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction given its input - loss_function : a loss function of the form `f(x, t, m)` that returns a scalar loss giv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskedObjective:
def __init__(self, input_layer, loss_function=mse, aggregation='mean'):
"""Constructor :parameters: - input_layer : a `Layer` whose output is the networks prediction given its input - loss_function : a loss function of the form `f(x, t, m)` that returns a scalar loss given tensors tha... | the_stack_v2_python_sparse | attrib/lasagne/objectives.py | thjashin/kblearn | train | 3 | |
5b60d3b1374425a1c5159d022c7a93c814a9baf8 | [
"pivot = arr[right]\ni = left\nfor j in range(left, right):\n if array[j] <= pivot:\n array[j], array[i] = (array[i], array[j])\n i += 1\narray[i], array[right] = (array[right], array[i])\nreturn i",
"if left < right:\n pivot = self.partition(array, left, right)\n self.quicksort(array, left... | <|body_start_0|>
pivot = arr[right]
i = left
for j in range(left, right):
if array[j] <= pivot:
array[j], array[i] = (array[i], array[j])
i += 1
array[i], array[right] = (array[right], array[i])
return i
<|end_body_0|>
<|body_start_1|>... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def partition(slef, array, left, right):
"""quick sort partition function"""
<|body_0|>
def quicksort(self, array, left, right):
"""Quick sort algorithm implementation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pivot = arr[right]
... | stack_v2_sparse_classes_36k_train_017419 | 2,601 | no_license | [
{
"docstring": "quick sort partition function",
"name": "partition",
"signature": "def partition(slef, array, left, right)"
},
{
"docstring": "Quick sort algorithm implementation",
"name": "quicksort",
"signature": "def quicksort(self, array, left, right)"
}
] | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def partition(slef, array, left, right): quick sort partition function
- def quicksort(self, array, left, right): Quick sort algorithm implementation | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def partition(slef, array, left, right): quick sort partition function
- def quicksort(self, array, left, right): Quick sort algorithm implementation
<|skeleton|>
class Soluti... | 551cd3b4616c16a6562eb7c577ce671b419f0616 | <|skeleton|>
class Solution1:
def partition(slef, array, left, right):
"""quick sort partition function"""
<|body_0|>
def quicksort(self, array, left, right):
"""Quick sort algorithm implementation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def partition(slef, array, left, right):
"""quick sort partition function"""
pivot = arr[right]
i = left
for j in range(left, right):
if array[j] <= pivot:
array[j], array[i] = (array[i], array[j])
i += 1
array[i], ... | the_stack_v2_python_sparse | others/sorting/quick_sort.py | lizzzcai/leetcode | train | 1 | |
981aec72244de2de1f366869ea44b8c92ecbdb99 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(lambda: nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nquery,... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(lambda: nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_star... | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_017420 | 26,297 | permissive | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | null | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | cfcafa94f10565bc25a72c172a9e58dfa4170fe7 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(lambda: nn.Linear(d_mod... | the_stack_v2_python_sparse | tensor2struct/modules/transformer.py | ashutoshbsathe/tensor2struct-public | train | 0 | |
f3645afcd56066797f12c506c693b6340d35c97d | [
"if context is None:\n context = {}\ncontext.update({'create_company': True})\nreturn super(ResCompany, self).create(cr, uid, vals, context=context)",
"context = dict(context or {})\ncontext.update({'create_company': True})\nreturn super(ResCompany, self).write(cr, uid, ids, values, context=context)"
] | <|body_start_0|>
if context is None:
context = {}
context.update({'create_company': True})
return super(ResCompany, self).create(cr, uid, vals, context=context)
<|end_body_0|>
<|body_start_1|>
context = dict(context or {})
context.update({'create_company': True})
... | ResCompany | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResCompany:
def create(self, cr, uid, vals, context=None):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
<|body_0|>
def write(self, cr, uid, ids, values, context=None):
"""To write a new record, adds a Boolean fiel... | stack_v2_sparse_classes_36k_train_017421 | 2,907 | no_license | [
{
"docstring": "To create a new record, adds a Boolean field to true indicates that the partner is a company",
"name": "create",
"signature": "def create(self, cr, uid, vals, context=None)"
},
{
"docstring": "To write a new record, adds a Boolean field to true indicates that the partner is a com... | 2 | null | Implement the Python class `ResCompany` described below.
Class description:
Implement the ResCompany class.
Method signatures and docstrings:
- def create(self, cr, uid, vals, context=None): To create a new record, adds a Boolean field to true indicates that the partner is a company
- def write(self, cr, uid, ids, va... | Implement the Python class `ResCompany` described below.
Class description:
Implement the ResCompany class.
Method signatures and docstrings:
- def create(self, cr, uid, vals, context=None): To create a new record, adds a Boolean field to true indicates that the partner is a company
- def write(self, cr, uid, ids, va... | 718327d01e5b4408add58682c5ad1901fa35b450 | <|skeleton|>
class ResCompany:
def create(self, cr, uid, vals, context=None):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
<|body_0|>
def write(self, cr, uid, ids, values, context=None):
"""To write a new record, adds a Boolean fiel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResCompany:
def create(self, cr, uid, vals, context=None):
"""To create a new record, adds a Boolean field to true indicates that the partner is a company"""
if context is None:
context = {}
context.update({'create_company': True})
return super(ResCompany, self).cre... | the_stack_v2_python_sparse | l10n_ve_fiscal_requirements/model/res_company.py | Vauxoo/odoo-venezuela | train | 15 | |
8043fe91a635d06a27b58d850606bb4919dc084a | [
"with disable_signal('post_save', schedule_saved, Schedule):\n schedule = Schedule.objects.create(minute=0)\nmessageset = MessageSet.objects.create(default_schedule=schedule)\nfor i in range(10):\n Message.objects.create(messageset=messageset, text_content=str(i), sequence_number=i)\nsubscription_1 = Subscrip... | <|body_start_0|>
with disable_signal('post_save', schedule_saved, Schedule):
schedule = Schedule.objects.create(minute=0)
messageset = MessageSet.objects.create(default_schedule=schedule)
for i in range(10):
Message.objects.create(messageset=messageset, text_content=str(i... | CachedMessageLookupTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedMessageLookupTests:
def test_caching_message_lookup_working(self):
"""Ensure that the second time we make a request, there's no database hit"""
<|body_0|>
def test_cache_message_count_working(self):
"""Ensure that the second time we do a message_count, there's ... | stack_v2_sparse_classes_36k_train_017422 | 6,017 | permissive | [
{
"docstring": "Ensure that the second time we make a request, there's no database hit",
"name": "test_caching_message_lookup_working",
"signature": "def test_caching_message_lookup_working(self)"
},
{
"docstring": "Ensure that the second time we do a message_count, there's no database hit",
... | 2 | null | Implement the Python class `CachedMessageLookupTests` described below.
Class description:
Implement the CachedMessageLookupTests class.
Method signatures and docstrings:
- def test_caching_message_lookup_working(self): Ensure that the second time we make a request, there's no database hit
- def test_cache_message_cou... | Implement the Python class `CachedMessageLookupTests` described below.
Class description:
Implement the CachedMessageLookupTests class.
Method signatures and docstrings:
- def test_caching_message_lookup_working(self): Ensure that the second time we make a request, there's no database hit
- def test_cache_message_cou... | c1d39601c0d16fb32cebe7c2e288076c1dc4225b | <|skeleton|>
class CachedMessageLookupTests:
def test_caching_message_lookup_working(self):
"""Ensure that the second time we make a request, there's no database hit"""
<|body_0|>
def test_cache_message_count_working(self):
"""Ensure that the second time we do a message_count, there's ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedMessageLookupTests:
def test_caching_message_lookup_working(self):
"""Ensure that the second time we make a request, there's no database hit"""
with disable_signal('post_save', schedule_saved, Schedule):
schedule = Schedule.objects.create(minute=0)
messageset = Messag... | the_stack_v2_python_sparse | subscriptions/test_tasks.py | praekeltfoundation/seed-stage-based-messaging | train | 0 | |
6e0b472730836a7f8b167b84509f41c087aabff3 | [
"query = f'{{\\n question: questionById(id: \"{question_id}\") {{\\n id\\n naturalQuestion\\n question_graph: qgraphByQgraphId {{\\n id\\n body\\n }}\\n }}\\n }}'\nrequest_body = {'query': ... | <|body_start_0|>
query = f'{{\n question: questionById(id: "{question_id}") {{\n id\n naturalQuestion\n question_graph: qgraphByQgraphId {{\n id\n body\n }}\n }}\n }}'
request_b... | QuestionAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionAPI:
def get(self, question_id):
"""Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: "question id" schema: type: string required: true responses: 200: description: "Question" content: application/json: schema: type: object 401:... | stack_v2_sparse_classes_36k_train_017423 | 16,438 | permissive | [
{
"docstring": "Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: \"question id\" schema: type: string required: true responses: 200: description: \"Question\" content: application/json: schema: type: object 401: description: \"unauthorized\" content: text/pla... | 3 | stack_v2_sparse_classes_30k_train_018006 | Implement the Python class `QuestionAPI` described below.
Class description:
Implement the QuestionAPI class.
Method signatures and docstrings:
- def get(self, question_id): Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: "question id" schema: type: string require... | Implement the Python class `QuestionAPI` described below.
Class description:
Implement the QuestionAPI class.
Method signatures and docstrings:
- def get(self, question_id): Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: "question id" schema: type: string require... | 5d0b29a6d7871673f3e4fa110bbd3e6a77cabd61 | <|skeleton|>
class QuestionAPI:
def get(self, question_id):
"""Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: "question id" schema: type: string required: true responses: 200: description: "Question" content: application/json: schema: type: object 401:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionAPI:
def get(self, question_id):
"""Get message for question. --- tags: [questions] parameters: - in: path name: question_id description: "question id" schema: type: string required: true responses: 200: description: "Question" content: application/json: schema: type: object 401: description: ... | the_stack_v2_python_sparse | manager/api/q_api.py | NCATS-Gamma/robokop | train | 13 | |
c514223e77d7bfe677ab34ae85c684ae37f397a3 | [
"self.translate = translate\nself.scale = scale\nself.rotate = rotate\nself.shear = shear",
"sl, _ = data.shape\ntx = random.uniform(0, self.translate)\nty = random.uniform(0, self.translate)\ntranslate_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])\nsx = random.uniform(1 - self.scale, 1 + self.scale)\nsy... | <|body_start_0|>
self.translate = translate
self.scale = scale
self.rotate = rotate
self.shear = shear
<|end_body_0|>
<|body_start_1|>
sl, _ = data.shape
tx = random.uniform(0, self.translate)
ty = random.uniform(0, self.translate)
translate_matrix = np.a... | RandomAffineSignal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomAffineSignal:
def __init__(self, translate=3, scale=0.2, rotate=0.314, shear=0.1):
"""Args: translate (float): random translate distance (in signal's input units) scale (float): random scale ratio rotate (float): random rotate degrees (in radians; e.g. 3.14, ) shear (float): random... | stack_v2_sparse_classes_36k_train_017424 | 3,283 | permissive | [
{
"docstring": "Args: translate (float): random translate distance (in signal's input units) scale (float): random scale ratio rotate (float): random rotate degrees (in radians; e.g. 3.14, ) shear (float): random ratio for shear (w.r.t. x, y)",
"name": "__init__",
"signature": "def __init__(self, transl... | 2 | stack_v2_sparse_classes_30k_train_016904 | Implement the Python class `RandomAffineSignal` described below.
Class description:
Implement the RandomAffineSignal class.
Method signatures and docstrings:
- def __init__(self, translate=3, scale=0.2, rotate=0.314, shear=0.1): Args: translate (float): random translate distance (in signal's input units) scale (float... | Implement the Python class `RandomAffineSignal` described below.
Class description:
Implement the RandomAffineSignal class.
Method signatures and docstrings:
- def __init__(self, translate=3, scale=0.2, rotate=0.314, shear=0.1): Args: translate (float): random translate distance (in signal's input units) scale (float... | deb30d742edef5dcb82e8ff3377948b53f956da9 | <|skeleton|>
class RandomAffineSignal:
def __init__(self, translate=3, scale=0.2, rotate=0.314, shear=0.1):
"""Args: translate (float): random translate distance (in signal's input units) scale (float): random scale ratio rotate (float): random rotate degrees (in radians; e.g. 3.14, ) shear (float): random... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomAffineSignal:
def __init__(self, translate=3, scale=0.2, rotate=0.314, shear=0.1):
"""Args: translate (float): random translate distance (in signal's input units) scale (float): random scale ratio rotate (float): random rotate degrees (in radians; e.g. 3.14, ) shear (float): random ratio for she... | the_stack_v2_python_sparse | obf/dataloader/augmenter.py | BeibinLi/OBF | train | 3 | |
e5cf8c444ea5bd69686137fc4d7a0822d5af726b | [
"if not isinstance(variables, list):\n self.variables = [variables]\nelse:\n self.variables = variables",
"self.median_dict = {}\nfor col in self.variables:\n self.median_dict[col] = X[col].median()\nreturn self",
"X = X.copy()\nfor col in self.variables:\n X[col][X[col] == -99] = self.median_dict[c... | <|body_start_0|>
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
<|end_body_0|>
<|body_start_1|>
self.median_dict = {}
for col in self.variables:
self.median_dict[col] = X[col].median()
return ... | Converts Rupee to Integer | CategoricalMedianImputation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoricalMedianImputation:
"""Converts Rupee to Integer"""
def __init__(self, variables=None) -> None:
"""Initialize and Convert if not a list"""
<|body_0|>
def fit(self, X: pd.DataFrame, y: pd.Series=None):
"""Fit statement to accomodate the sklearn pipeline""... | stack_v2_sparse_classes_36k_train_017425 | 3,391 | no_license | [
{
"docstring": "Initialize and Convert if not a list",
"name": "__init__",
"signature": "def __init__(self, variables=None) -> None"
},
{
"docstring": "Fit statement to accomodate the sklearn pipeline",
"name": "fit",
"signature": "def fit(self, X: pd.DataFrame, y: pd.Series=None)"
},
... | 3 | stack_v2_sparse_classes_30k_train_019573 | Implement the Python class `CategoricalMedianImputation` described below.
Class description:
Converts Rupee to Integer
Method signatures and docstrings:
- def __init__(self, variables=None) -> None: Initialize and Convert if not a list
- def fit(self, X: pd.DataFrame, y: pd.Series=None): Fit statement to accomodate t... | Implement the Python class `CategoricalMedianImputation` described below.
Class description:
Converts Rupee to Integer
Method signatures and docstrings:
- def __init__(self, variables=None) -> None: Initialize and Convert if not a list
- def fit(self, X: pd.DataFrame, y: pd.Series=None): Fit statement to accomodate t... | 6ebbdac1266069c2de0ec655239d4501f5c419c3 | <|skeleton|>
class CategoricalMedianImputation:
"""Converts Rupee to Integer"""
def __init__(self, variables=None) -> None:
"""Initialize and Convert if not a list"""
<|body_0|>
def fit(self, X: pd.DataFrame, y: pd.Series=None):
"""Fit statement to accomodate the sklearn pipeline""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoricalMedianImputation:
"""Converts Rupee to Integer"""
def __init__(self, variables=None) -> None:
"""Initialize and Convert if not a list"""
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fi... | the_stack_v2_python_sparse | packages/fooddelivery/fooddelivery/datamanagement/preprocessing.py | mohankumar1905/Deployment | train | 0 |
c96b040eb2334c8b0acfd63708be915bdbd75589 | [
"super(InvertedResidual, self).__init__()\nself.user_res_connect = stride == 1 and inp == oup\nself.conv = InvertedConv(inp, oup, stride, kernel, expand_ratio)",
"if self.user_res_connect:\n return inputs + self.conv(inputs)\nelse:\n return self.conv(inputs)"
] | <|body_start_0|>
super(InvertedResidual, self).__init__()
self.user_res_connect = stride == 1 and inp == oup
self.conv = InvertedConv(inp, oup, stride, kernel, expand_ratio)
<|end_body_0|>
<|body_start_1|>
if self.user_res_connect:
return inputs + self.conv(inputs)
e... | Create InvertedResidual SearchSpace. | InvertedResidual | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvertedResidual:
"""Create InvertedResidual SearchSpace."""
def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1):
"""Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param stride: stride :param kernel: kernel :param expand_ratio: chan... | stack_v2_sparse_classes_36k_train_017426 | 8,338 | permissive | [
{
"docstring": "Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param stride: stride :param kernel: kernel :param expand_ratio: channel increase multiplier",
"name": "__init__",
"signature": "def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1)"
},
{... | 2 | null | Implement the Python class `InvertedResidual` described below.
Class description:
Create InvertedResidual SearchSpace.
Method signatures and docstrings:
- def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1): Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param strid... | Implement the Python class `InvertedResidual` described below.
Class description:
Create InvertedResidual SearchSpace.
Method signatures and docstrings:
- def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1): Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param strid... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class InvertedResidual:
"""Create InvertedResidual SearchSpace."""
def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1):
"""Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param stride: stride :param kernel: kernel :param expand_ratio: chan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvertedResidual:
"""Create InvertedResidual SearchSpace."""
def __init__(self, inp, oup, stride, kernel=3, expand_ratio=1):
"""Construct InvertedResidual class. :param inp: input channel :param oup: output channel :param stride: stride :param kernel: kernel :param expand_ratio: channel increase ... | the_stack_v2_python_sparse | zeus/modules/blocks/micro_decoder.py | huawei-noah/xingtian | train | 308 |
1ca2396c72164a52ed1b2f795deee85c27c5dbc6 | [
"users = CRITsUser.objects(is_active=True, prefs__notify__email=True)\nnotifications = Notification.objects(status='new')\nfor user in users:\n includes = [x for x in notifications if user.username in x.users and user.username != x.analyst and (x.obj_id != None)]\n if len(includes):\n email = EmailNoti... | <|body_start_0|>
users = CRITsUser.objects(is_active=True, prefs__notify__email=True)
notifications = Notification.objects(status='new')
for user in users:
includes = [x for x in notifications if user.username in x.users and user.username != x.analyst and (x.obj_id != None)]
... | generate_notifications Django command | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""generate_notifications Django command"""
def handle(self, *args, **options):
"""Script Execution."""
<|body_0|>
def process_notifications(self, notifications, users):
"""Set notifications to processed. Remove users from the list if they received an em... | stack_v2_sparse_classes_36k_train_017427 | 5,156 | permissive | [
{
"docstring": "Script Execution.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Set notifications to processed. Remove users from the list if they received an email. If any notification has 0 users left, remove it. Also remove any processed notification... | 2 | stack_v2_sparse_classes_30k_train_018786 | Implement the Python class `Command` described below.
Class description:
generate_notifications Django command
Method signatures and docstrings:
- def handle(self, *args, **options): Script Execution.
- def process_notifications(self, notifications, users): Set notifications to processed. Remove users from the list i... | Implement the Python class `Command` described below.
Class description:
generate_notifications Django command
Method signatures and docstrings:
- def handle(self, *args, **options): Script Execution.
- def process_notifications(self, notifications, users): Set notifications to processed. Remove users from the list i... | 81fc042efe61a252ee3433432f7bd7f0f11b217d | <|skeleton|>
class Command:
"""generate_notifications Django command"""
def handle(self, *args, **options):
"""Script Execution."""
<|body_0|>
def process_notifications(self, notifications, users):
"""Set notifications to processed. Remove users from the list if they received an em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""generate_notifications Django command"""
def handle(self, *args, **options):
"""Script Execution."""
users = CRITsUser.objects(is_active=True, prefs__notify__email=True)
notifications = Notification.objects(status='new')
for user in users:
includes ... | the_stack_v2_python_sparse | crits/core/management/commands/generate_notifications.py | MITRECND/crits | train | 22 |
258fa2d7c5873801c63264e09d57e339eeaa4b37 | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)])\nch = chans\nfor i in range(num_pool_layers - 1):\n self.down_sample_... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob)])
ch... | PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015. | UnetModelTakeLatentDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnetModelTakeLatentDecoder:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention,... | stack_v2_sparse_classes_36k_train_017428 | 30,521 | no_license | [
{
"docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ... | 2 | stack_v2_sparse_classes_30k_train_011316 | Implement the Python class `UnetModelTakeLatentDecoder` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image comput... | Implement the Python class `UnetModelTakeLatentDecoder` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image comput... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class UnetModelTakeLatentDecoder:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnetModelTakeLatentDecoder:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–24... | the_stack_v2_python_sparse | lemawarersn_t1assist/models.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
ae0b12ca5a30d06d3dde154d582283965b497a69 | [
"if len(matrix) == 0:\n return\nm, n = (len(matrix), len(matrix[0]))\nfor i in xrange(m):\n for j in xrange(1, n):\n matrix[i][j] += matrix[i][j - 1]\nfor j in xrange(n):\n for i in xrange(1, m):\n matrix[i][j] += matrix[i - 1][j]\nself.matrix = matrix",
"if row1 == 0 and col1 == 0:\n re... | <|body_start_0|>
if len(matrix) == 0:
return
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m):
for j in xrange(1, n):
matrix[i][j] += matrix[i][j - 1]
for j in xrange(n):
for i in xrange(1, m):
matrix[i][j] += mat... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_017429 | 2,398 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if len(matrix) == 0:
return
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m):
for j in xrange(1, n):
matrix[i][j] += ma... | the_stack_v2_python_sparse | Algorithm/Python/304. Range Sum Query 2D - Immutable.py | WuLC/LeetCode | train | 29 | |
a0630817ed9b516e896730f1efb6b407226e8978 | [
"l, r = (0, len(numbers) - 1)\nwhile l < r:\n s = numbers[l] + numbers[r]\n if s == target:\n return [l + 1, r + 1]\n elif s < target:\n l += 1\n else:\n r -= 1",
"dic = {}\nfor i, num in enumerate(numbers):\n if target - num in dic:\n return [dic[target - num] + 1, i + ... | <|body_start_0|>
l, r = (0, len(numbers) - 1)
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l + 1, r + 1]
elif s < target:
l += 1
else:
r -= 1
<|end_body_0|>
<|body_start_1|>
dic =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
"""two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_dictionary(self, numbers, target):
"""Dictionary O(n) time and O(n) space :type numbers: List[in... | stack_v2_sparse_classes_36k_train_017430 | 1,727 | no_license | [
{
"docstring": "two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": "Dictionary O(n) time and O(n) space :type numbers: List[int] :type target: int :rtype: List[in... | 3 | stack_v2_sparse_classes_30k_train_018727 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum_dictionary(self, numbers, target... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum_dictionary(self, numbers, target... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
"""two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_dictionary(self, numbers, target):
"""Dictionary O(n) time and O(n) space :type numbers: List[in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers, target):
"""two Pointer O(n) time and O(1) space :type numbers: List[int] :type target: int :rtype: List[int]"""
l, r = (0, len(numbers) - 1)
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l +... | the_stack_v2_python_sparse | LeetCode/BinarySearch/167_two_sum_ii_input_array_is_sorted.py | XyK0907/for_work | train | 0 | |
f07c7b00c45bdc6297e6c884b0f7dc599a89ff53 | [
"actions.speech.enable()\nengine = speech_system.engine.name\nif 'dragon' in engine:\n if app.platform == 'mac':\n actions.user.engine_sleep()\n elif app.platform == 'windows':\n actions.user.engine_wake()\n actions.user.engine_mimic('switch to command mode')",
"engine = speech_system.e... | <|body_start_0|>
actions.speech.enable()
engine = speech_system.engine.name
if 'dragon' in engine:
if app.platform == 'mac':
actions.user.engine_sleep()
elif app.platform == 'windows':
actions.user.engine_wake()
actions.user... | Actions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actions:
def talon_mode():
"""For windows and Mac with Dragon, enables Talon commands and Dragon's command mode."""
<|body_0|>
def dragon_mode():
"""For windows and Mac with Dragon, disables Talon commands and exits Dragon's command mode"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_017431 | 1,797 | permissive | [
{
"docstring": "For windows and Mac with Dragon, enables Talon commands and Dragon's command mode.",
"name": "talon_mode",
"signature": "def talon_mode()"
},
{
"docstring": "For windows and Mac with Dragon, disables Talon commands and exits Dragon's command mode",
"name": "dragon_mode",
... | 2 | stack_v2_sparse_classes_30k_train_008561 | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def talon_mode(): For windows and Mac with Dragon, enables Talon commands and Dragon's command mode.
- def dragon_mode(): For windows and Mac with Dragon, disables Talon commands a... | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def talon_mode(): For windows and Mac with Dragon, enables Talon commands and Dragon's command mode.
- def dragon_mode(): For windows and Mac with Dragon, disables Talon commands a... | b8df33d9ae81850b9fdc05f481984a17bdda9758 | <|skeleton|>
class Actions:
def talon_mode():
"""For windows and Mac with Dragon, enables Talon commands and Dragon's command mode."""
<|body_0|>
def dragon_mode():
"""For windows and Mac with Dragon, disables Talon commands and exits Dragon's command mode"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actions:
def talon_mode():
"""For windows and Mac with Dragon, enables Talon commands and Dragon's command mode."""
actions.speech.enable()
engine = speech_system.engine.name
if 'dragon' in engine:
if app.platform == 'mac':
actions.user.engine_sleep(... | the_stack_v2_python_sparse | core/modes/modes.py | 2shea/knausj_talon | train | 3 | |
80041828d3c7bfb550bf00a21e60ecb67fcb0eb7 | [
"Author = AuthorModel.find_by_id(id)\nif Author:\n return Author.json()\nreturn ({'message': 'Author not found'}, 404)",
"if AuthorModel.find_by_id(id):\n return ({'message': \"An Author with id '{}' already exists.\".format(id)}, 400)\ndata = Author.parser.parse_args()\nauthor = AuthorModel(id, **data)\ntr... | <|body_start_0|>
Author = AuthorModel.find_by_id(id)
if Author:
return Author.json()
return ({'message': 'Author not found'}, 404)
<|end_body_0|>
<|body_start_1|>
if AuthorModel.find_by_id(id):
return ({'message': "An Author with id '{}' already exists.".format(i... | Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id> | Author | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Author:
"""Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id>"""
def get(self, id):
"""GET request that deals ... | stack_v2_sparse_classes_36k_train_017432 | 9,451 | permissive | [
{
"docstring": "GET request that deals with requests that look for a author by id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "POST request that deals with the creation of an a new author",
"name": "post",
"signature": "def post(self, id)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_000091 | Implement the Python class `Author` described below.
Class description:
Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id>
Method signatures and... | Implement the Python class `Author` described below.
Class description:
Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id>
Method signatures and... | 42456ced804a2c9570227b393de662847283c76f | <|skeleton|>
class Author:
"""Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id>"""
def get(self, id):
"""GET request that deals ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Author:
"""Author. Resource that helps with dealing with Http request for a book by providing its id. HTTP GET call : /authors/<int:id> HTTP POST call : /books/<int:id> HTTP DELETE call : /books/<int:id> HTTP PUT call : /books/<int:id>"""
def get(self, id):
"""GET request that deals with requests... | the_stack_v2_python_sparse | resources/author.py | basgir/bibliotek | train | 0 |
b7b86ca920f141aeae4b54b8575f741169fd084d | [
"if root == None:\n return []\nqueue = deque()\nqueue.append(root)\nresult = []\nwhile queue:\n item = queue.popleft()\n if item:\n result.append(item.val)\n queue.append(item.left)\n queue.append(item.right)\n else:\n result.append('null')\nprint(result)\nreturn result",
"... | <|body_start_0|>
if root == None:
return []
queue = deque()
queue.append(root)
result = []
while queue:
item = queue.popleft()
if item:
result.append(item.val)
queue.append(item.left)
queue.append... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017433 | 2,144 | 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_021597 | 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:... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return []
queue = deque()
queue.append(root)
result = []
while queue:
item = queue.popleft()
if item:... | the_stack_v2_python_sparse | 297-serialize-and-deserialize.py | stevestar888/leetcode-problems | train | 2 | |
c7ef827ce147272a79b8be95db96945f6f67e493 | [
"import collections\nif len(s) != len(t):\n return False\nfreq_map1, freq_map2 = (collections.defaultdict(int), collections.defaultdict(int))\nfor i in xrange(len(s)):\n freq_map1[s[i]] += 1\n freq_map2[t[i]] += 1\nreturn freq_map1 == freq_map2",
"a = ''.join(sorted(list(s)))\nb = ''.join(sorted(list(t))... | <|body_start_0|>
import collections
if len(s) != len(t):
return False
freq_map1, freq_map2 = (collections.defaultdict(int), collections.defaultdict(int))
for i in xrange(len(s)):
freq_map1[s[i]] += 1
freq_map2[t[i]] += 1
return freq_map1 == fre... | https://leetcode.com/problems/valid-anagram/solution/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/valid-anagram/solution/"""
def isAnagram(self, s, t):
"""Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)"""
<|body_0|>
def isAnagram_sorting(self, s, t):
"""Tech2: If you don't want t... | stack_v2_sparse_classes_36k_train_017434 | 858 | no_license | [
{
"docstring": "Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)",
"name": "isAnagram",
"signature": "def isAnagram(self, s, t)"
},
{
"docstring": "Tech2: If you don't want to use extra space, sort both strings and compare. Time: O(nlogn) Space: O(1)",
"na... | 2 | stack_v2_sparse_classes_30k_train_001446 | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/valid-anagram/solution/
Method signatures and docstrings:
- def isAnagram(self, s, t): Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)
- def isAnagram_sorting(self, s, t): Tech2... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/valid-anagram/solution/
Method signatures and docstrings:
- def isAnagram(self, s, t): Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)
- def isAnagram_sorting(self, s, t): Tech2... | 57212d700dfba0db4925d9d4896f7f0b9635a5b5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/valid-anagram/solution/"""
def isAnagram(self, s, t):
"""Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)"""
<|body_0|>
def isAnagram_sorting(self, s, t):
"""Tech2: If you don't want t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode.com/problems/valid-anagram/solution/"""
def isAnagram(self, s, t):
"""Tech1: create frequency maps for both and compare these maps. Time: O(n) Space: O(n)"""
import collections
if len(s) != len(t):
return False
freq_map1, freq_map2... | the_stack_v2_python_sparse | valid_anagrams.py | baloooo/coding_practice | train | 0 |
5566ceab8ed9c28661fe5ca28243ae4f8b95adcd | [
"self.__rep = rental_repo\nself.__cl_rep = client_rep\nself.__car_rep = car_rep",
"try:\n new_rental = Rental(id_car, id_client)\n self.__rep.store_rental(new_rental)\nexcept ValidatorException as ex:\n print(ex.args)\nexcept RepositoryException as ex:\n print(ex)",
"del_rental = self.__rep.delete_r... | <|body_start_0|>
self.__rep = rental_repo
self.__cl_rep = client_rep
self.__car_rep = car_rep
<|end_body_0|>
<|body_start_1|>
try:
new_rental = Rental(id_car, id_client)
self.__rep.store_rental(new_rental)
except ValidatorException as ex:
prin... | Class to controls the action performed with rentals | RentalService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RentalService:
"""Class to controls the action performed with rentals"""
def __init__(self, rental_repo, client_rep, car_rep):
""":param rental_repo: RentalRepository"""
<|body_0|>
def add_rent_srv(self, id_car, id_client):
"""Function that adds a new rental to t... | stack_v2_sparse_classes_36k_train_017435 | 2,648 | no_license | [
{
"docstring": ":param rental_repo: RentalRepository",
"name": "__init__",
"signature": "def __init__(self, rental_repo, client_rep, car_rep)"
},
{
"docstring": "Function that adds a new rental to the repository :param id_car: :param id_client: :return:",
"name": "add_rent_srv",
"signatu... | 6 | null | Implement the Python class `RentalService` described below.
Class description:
Class to controls the action performed with rentals
Method signatures and docstrings:
- def __init__(self, rental_repo, client_rep, car_rep): :param rental_repo: RentalRepository
- def add_rent_srv(self, id_car, id_client): Function that a... | Implement the Python class `RentalService` described below.
Class description:
Class to controls the action performed with rentals
Method signatures and docstrings:
- def __init__(self, rental_repo, client_rep, car_rep): :param rental_repo: RentalRepository
- def add_rent_srv(self, id_car, id_client): Function that a... | e0324bf24bfc801cc68404f86c720926e144e5aa | <|skeleton|>
class RentalService:
"""Class to controls the action performed with rentals"""
def __init__(self, rental_repo, client_rep, car_rep):
""":param rental_repo: RentalRepository"""
<|body_0|>
def add_rent_srv(self, id_car, id_client):
"""Function that adds a new rental to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RentalService:
"""Class to controls the action performed with rentals"""
def __init__(self, rental_repo, client_rep, car_rep):
""":param rental_repo: RentalRepository"""
self.__rep = rental_repo
self.__cl_rep = client_rep
self.__car_rep = car_rep
def add_rent_srv(self... | the_stack_v2_python_sparse | testPractice/services/rental_service.py | GeorgianBadita/Python-Problems | train | 6 |
bf6e73075a59d349fada574767be26c20fe08869 | [
"len_nodetypes = float(Nodetype.published.count())\nself.cache_metatypes = {}\nfor cat in metatypes:\n if len_nodetypes:\n self.cache_metatypes[cat.pk] = cat.nodetypes_published().count() / len_nodetypes\n else:\n self.cache_metatypes[cat.pk] = 0.0",
"metatypes = Metatype.objects.all()\nself.c... | <|body_start_0|>
len_nodetypes = float(Nodetype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_nodetypes:
self.cache_metatypes[cat.pk] = cat.nodetypes_published().count() / len_nodetypes
else:
self.cache_metatypes... | Sitemap for metatypes | MetatypeSitemap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""Retu... | stack_v2_sparse_classes_36k_train_017436 | 3,463 | permissive | [
{
"docstring": "Cache categorie's nodetypes percent on total nodetypes",
"name": "cache",
"signature": "def cache(self, metatypes)"
},
{
"docstring": "Return all metatypes with coeff",
"name": "items",
"signature": "def items(self)"
},
{
"docstring": "Return last modification of ... | 4 | null | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's nodetypes percent on total nodetypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last modific... | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's nodetypes percent on total nodetypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last modific... | d515883fc4ffe01dd8b4b876d5a3dd023f862d30 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""Retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's nodetypes percent on total nodetypes"""
len_nodetypes = float(Nodetype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_nodetypes:
... | the_stack_v2_python_sparse | gstudio/sitemaps.py | gnowgi/django-gstudio | train | 1 |
ef3fa825bcdb403fee9d89da55f612ecf144ebf8 | [
"self.node_1 = BST(15)\nself.node_2 = BST(5)\nself.node_3 = BST(20)\nself.node_4 = BST(2)\nself.node_5 = BST(5)\nself.node_6 = BST(17)\nself.node_7 = BST(22)\nself.node_8 = BST(1)\nself.node_I = BST(3)\nself.k = 3\nself.node_1.left = self.node_2\nself.node_1.right = self.node_3\nself.node_2.left = self.node_4\nself... | <|body_start_0|>
self.node_1 = BST(15)
self.node_2 = BST(5)
self.node_3 = BST(20)
self.node_4 = BST(2)
self.node_5 = BST(5)
self.node_6 = BST(17)
self.node_7 = BST(22)
self.node_8 = BST(1)
self.node_I = BST(3)
self.k = 3
self.node_1... | Class with unittests for FindKthLargestValueInBST.py | test_FindKthLargestValueInBST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_FindKthLargestValueInBST:
"""Class with unittests for FindKthLargestValueInBST.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017437 | 1,511 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_FindKthLargestValueInBST` described below.
Class description:
Class with unittests for FindKthLargestValueInBST.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_FindKthLargestValueInBST` described below.
Class description:
Class with unittests for FindKthLargestValueInBST.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_Fi... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_FindKthLargestValueInBST:
"""Class with unittests for FindKthLargestValueInBST.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_FindKthLargestValueInBST:
"""Class with unittests for FindKthLargestValueInBST.py"""
def setUp(self):
"""Sets up input."""
self.node_1 = BST(15)
self.node_2 = BST(5)
self.node_3 = BST(20)
self.node_4 = BST(2)
self.node_5 = BST(5)
self.node_6 = ... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/FindKthLargestValueInBST/test_FindKthLargestValueInBST.py | JakubKazimierski/PythonPortfolio | train | 9 |
90b380c2f84d1b9d56d68224aaae9d58e31ae7ba | [
"if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):\n if self.grid[x][y] == '1':\n queue.append((x, y))",
"queue = deque()\nqueue.append((row, col))\nwhile queue:\n x, y = queue.pop()\n self.grid[x][y] = '2'\n self.append_if(queue, x - 1, y)\n self.append_if(queue, x, y - 1)\n sel... | <|body_start_0|>
if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):
if self.grid[x][y] == '1':
queue.append((x, y))
<|end_body_0|>
<|body_start_1|>
queue = deque()
queue.append((row, col))
while queue:
x, y = queue.pop()
self.g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def append_if(self, queue, x, y):
"""Append to the queue only if in bounds of the grid and the cell value is 1."""
<|body_0|>
def mark_neighbors(self, row, col):
"""Mark all the cells in the current island with value = 2. Breadth-first search."""
<|... | stack_v2_sparse_classes_36k_train_017438 | 1,558 | no_license | [
{
"docstring": "Append to the queue only if in bounds of the grid and the cell value is 1.",
"name": "append_if",
"signature": "def append_if(self, queue, x, y)"
},
{
"docstring": "Mark all the cells in the current island with value = 2. Breadth-first search.",
"name": "mark_neighbors",
... | 3 | stack_v2_sparse_classes_30k_train_016618 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def append_if(self, queue, x, y): Append to the queue only if in bounds of the grid and the cell value is 1.
- def mark_neighbors(self, row, col): Mark all the cells in the curre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def append_if(self, queue, x, y): Append to the queue only if in bounds of the grid and the cell value is 1.
- def mark_neighbors(self, row, col): Mark all the cells in the curre... | 0864b4f8a52d9463d09def8d54a9b852e4073dcc | <|skeleton|>
class Solution:
def append_if(self, queue, x, y):
"""Append to the queue only if in bounds of the grid and the cell value is 1."""
<|body_0|>
def mark_neighbors(self, row, col):
"""Mark all the cells in the current island with value = 2. Breadth-first search."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def append_if(self, queue, x, y):
"""Append to the queue only if in bounds of the grid and the cell value is 1."""
if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):
if self.grid[x][y] == '1':
queue.append((x, y))
def mark_neighbors(self, row,... | the_stack_v2_python_sparse | islands2.py | Sammyuel/LeetcodeSolutions | train | 0 | |
5400ddc092a52e80994a6291074d541ed9db4d6d | [
"super(BiLSTMMultiLayeredWithShortcutConnections, self).__init__(num_layers, input_dim, hidden_dim, model, rnn_builder_factory)\nassert num_layers > 0\nassert hidden_dim % 2 == 0\nself.shortcut_connections = shortcut_connections\nself.builder_layers = []\nf = rnn_builder_factory(1, input_dim, hidden_dim / 2, model)... | <|body_start_0|>
super(BiLSTMMultiLayeredWithShortcutConnections, self).__init__(num_layers, input_dim, hidden_dim, model, rnn_builder_factory)
assert num_layers > 0
assert hidden_dim % 2 == 0
self.shortcut_connections = shortcut_connections
self.builder_layers = []
f = r... | BiLSTMMultiLayeredWithShortcutConnections | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTMMultiLayeredWithShortcutConnections:
def __init__(self, num_layers, input_dim, hidden_dim, model, rnn_builder_factory, shortcut_connections):
"""This class implements a multilayered BiRNN with shortcut connections @param num_layers: depth of the BiRNN @param input_dim: size of the ... | stack_v2_sparse_classes_36k_train_017439 | 3,893 | permissive | [
{
"docstring": "This class implements a multilayered BiRNN with shortcut connections @param num_layers: depth of the BiRNN @param input_dim: size of the inputs @param hidden_dim: size of the outputs (and intermediate layer representations) @param model @param rnn_builder_factory: RNNBuilder subclass, e.g. LSTMB... | 2 | stack_v2_sparse_classes_30k_train_001323 | Implement the Python class `BiLSTMMultiLayeredWithShortcutConnections` described below.
Class description:
Implement the BiLSTMMultiLayeredWithShortcutConnections class.
Method signatures and docstrings:
- def __init__(self, num_layers, input_dim, hidden_dim, model, rnn_builder_factory, shortcut_connections): This cl... | Implement the Python class `BiLSTMMultiLayeredWithShortcutConnections` described below.
Class description:
Implement the BiLSTMMultiLayeredWithShortcutConnections class.
Method signatures and docstrings:
- def __init__(self, num_layers, input_dim, hidden_dim, model, rnn_builder_factory, shortcut_connections): This cl... | d0b1aac0ad3d288ad433816949dcbfa97da4d067 | <|skeleton|>
class BiLSTMMultiLayeredWithShortcutConnections:
def __init__(self, num_layers, input_dim, hidden_dim, model, rnn_builder_factory, shortcut_connections):
"""This class implements a multilayered BiRNN with shortcut connections @param num_layers: depth of the BiRNN @param input_dim: size of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLSTMMultiLayeredWithShortcutConnections:
def __init__(self, num_layers, input_dim, hidden_dim, model, rnn_builder_factory, shortcut_connections):
"""This class implements a multilayered BiRNN with shortcut connections @param num_layers: depth of the BiRNN @param input_dim: size of the inputs @param ... | the_stack_v2_python_sparse | toolkit/rnn.py | onurgu/joint-ner-and-md-tagger | train | 25 | |
b6ebecea0a69aaf66c0677ce1353029d8c1e210c | [
"import jsonrpc_requests\nself._url = url\nself._server = jsonrpc_requests.Server('{}/jsonrpc'.format(self._url), auth=auth, timeout=5)",
"import jsonrpc_requests\ntry:\n data = kwargs.get(ATTR_DATA) or {}\n displaytime = data.get(ATTR_DISPLAYTIME, 10000)\n icon = data.get(ATTR_ICON, 'info')\n title =... | <|body_start_0|>
import jsonrpc_requests
self._url = url
self._server = jsonrpc_requests.Server('{}/jsonrpc'.format(self._url), auth=auth, timeout=5)
<|end_body_0|>
<|body_start_1|>
import jsonrpc_requests
try:
data = kwargs.get(ATTR_DATA) or {}
displayti... | Implement the notification service for Kodi. | KODINotificationService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KODINotificationService:
"""Implement the notification service for Kodi."""
def __init__(self, url, auth=None):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to Kodi."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_017440 | 2,288 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, url, auth=None)"
},
{
"docstring": "Send a message to Kodi.",
"name": "send_message",
"signature": "def send_message(self, message='', **kwargs)"
}
] | 2 | null | Implement the Python class `KODINotificationService` described below.
Class description:
Implement the notification service for Kodi.
Method signatures and docstrings:
- def __init__(self, url, auth=None): Initialize the service.
- def send_message(self, message='', **kwargs): Send a message to Kodi. | Implement the Python class `KODINotificationService` described below.
Class description:
Implement the notification service for Kodi.
Method signatures and docstrings:
- def __init__(self, url, auth=None): Initialize the service.
- def send_message(self, message='', **kwargs): Send a message to Kodi.
<|skeleton|>
cl... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class KODINotificationService:
"""Implement the notification service for Kodi."""
def __init__(self, url, auth=None):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to Kodi."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KODINotificationService:
"""Implement the notification service for Kodi."""
def __init__(self, url, auth=None):
"""Initialize the service."""
import jsonrpc_requests
self._url = url
self._server = jsonrpc_requests.Server('{}/jsonrpc'.format(self._url), auth=auth, timeout=5... | the_stack_v2_python_sparse | homeassistant/components/notify/kodi.py | Smart-Torvy/torvy-home-assistant | train | 2 |
3b130d3645e2754adc0dc0b335e6e032bade5b0a | [
"inputs = [x for x in sys_stdin]\nif inputs[0] == '':\n a = list()\nelse:\n a = [self.cast(x.strip()) for x in inputs[0].strip('[]\\n').split(',')]\no = TreeNode().convert(a)\nreturn o",
"if x.lower() == 'null':\n return None\nelse:\n return int(x)"
] | <|body_start_0|>
inputs = [x for x in sys_stdin]
if inputs[0] == '':
a = list()
else:
a = [self.cast(x.strip()) for x in inputs[0].strip('[]\n').split(',')]
o = TreeNode().convert(a)
return o
<|end_body_0|>
<|body_start_1|>
if x.lower() == 'null':... | Input | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :p... | stack_v2_sparse_classes_36k_train_017441 | 2,324 | permissive | [
{
"docstring": "Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]",
"name": "stdin",
"signature": "def stdin(self, sys_stdin)"
},
{
"docstring": "Converts string values to integer or None values. :param st... | 2 | null | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]
- def cast(self... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]
- def cast(self... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None values. :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head node of binary tree :rtype: tup[TreeNode, TreeNode]"""
inputs = [x for x in sys_stdin]
if inputs[0] == '':
a = list()
else:
a =... | the_stack_v2_python_sparse | 0958_check_completeness_of_binary_tree/python_source.py | arthurdysart/LeetCode | train | 0 | |
ff9e3cab333955b7cf4e38f4f99665d7351245ea | [
"super(TTSCloudClientDelegate, self).set_configuration(dict_config)\nfor str_name_tts, dict_config_tts in self._config_tts.items():\n if str_name_tts == 'google_cloud_tts':\n dict_config_tts_copy = dict_config_tts.copy()\n dict_config_tts_copy['audio_file_format'] = self._config_tts['audio_file_for... | <|body_start_0|>
super(TTSCloudClientDelegate, self).set_configuration(dict_config)
for str_name_tts, dict_config_tts in self._config_tts.items():
if str_name_tts == 'google_cloud_tts':
dict_config_tts_copy = dict_config_tts.copy()
dict_config_tts_copy['audio_... | TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves like InterfaceTTSCloudClient. | TTSCloudClientDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TTSCloudClientDelegate:
"""TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves like InterfaceTTSCloudClient."""
d... | stack_v2_sparse_classes_36k_train_017442 | 4,942 | no_license | [
{
"docstring": "Overrides corresponding method of abstract parent class. Extends: - Creates instance of specific TTS cloud client based on configuration and sets it as _client_tts.",
"name": "set_configuration",
"signature": "def set_configuration(self, dict_config)"
},
{
"docstring": "Implement... | 5 | stack_v2_sparse_classes_30k_train_019383 | Implement the Python class `TTSCloudClientDelegate` described below.
Class description:
TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves ... | Implement the Python class `TTSCloudClientDelegate` described below.
Class description:
TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves ... | 16fd30af8deeb911f504857a636fbfded12fad8f | <|skeleton|>
class TTSCloudClientDelegate:
"""TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves like InterfaceTTSCloudClient."""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TTSCloudClientDelegate:
"""TTS cloud client delegate class. - Initializes specific TTS cloud client based on passed configuration. - Redirects calls of interface methods to specific TTS cloud client. - Has structure like AbstractTTSClientDelegate. - Behaves like InterfaceTTSCloudClient."""
def set_config... | the_stack_v2_python_sparse | robotis_op2_tts/tts_engines/cloud/tts_delegate.py | valeryvpetrov-dev/Robotis-OP2-TTS | train | 0 |
ca99f6a5e32ce4dcab7c7c8cda4b5ad922d3cbca | [
"b = GraphBuilder('GZTest', {'fontname': '\"sans bold\"', 'shape': 'doublecircle', 'style': 'filled'})\nb.node('A', attrs={'label': '\"STOP!\"', 'color': 'red'})\nb.node('C', attrs={'fillcolor': 'green', 'color': 'black', 'fontcolor': 'white', 'label': '\"go\"'})\nb.edge('A', 'B', 'C')\nb.nodeCluster('A', 'B', 'C',... | <|body_start_0|>
b = GraphBuilder('GZTest', {'fontname': '"sans bold"', 'shape': 'doublecircle', 'style': 'filled'})
b.node('A', attrs={'label': '"STOP!"', 'color': 'red'})
b.node('C', attrs={'fillcolor': 'green', 'color': 'black', 'fontcolor': 'white', 'label': '"go"'})
b.edge('A', 'B',... | python3 -m unittest graphviz.GZTest | TestGZ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGZ:
"""python3 -m unittest graphviz.GZTest"""
def test_graph_builder(self):
"""python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder"""
<|body_0|>
def test_digraph_builder(self):
"""python3 -m unittest graphviz.GZTest.TestGZ.test_digraph_builder"""
... | stack_v2_sparse_classes_36k_train_017443 | 1,395 | no_license | [
{
"docstring": "python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder",
"name": "test_graph_builder",
"signature": "def test_graph_builder(self)"
},
{
"docstring": "python3 -m unittest graphviz.GZTest.TestGZ.test_digraph_builder",
"name": "test_digraph_builder",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_001391 | Implement the Python class `TestGZ` described below.
Class description:
python3 -m unittest graphviz.GZTest
Method signatures and docstrings:
- def test_graph_builder(self): python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder
- def test_digraph_builder(self): python3 -m unittest graphviz.GZTest.TestGZ.test_... | Implement the Python class `TestGZ` described below.
Class description:
python3 -m unittest graphviz.GZTest
Method signatures and docstrings:
- def test_graph_builder(self): python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder
- def test_digraph_builder(self): python3 -m unittest graphviz.GZTest.TestGZ.test_... | 0d12fbb8e5a4418c8c43b20452672e288bcca031 | <|skeleton|>
class TestGZ:
"""python3 -m unittest graphviz.GZTest"""
def test_graph_builder(self):
"""python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder"""
<|body_0|>
def test_digraph_builder(self):
"""python3 -m unittest graphviz.GZTest.TestGZ.test_digraph_builder"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGZ:
"""python3 -m unittest graphviz.GZTest"""
def test_graph_builder(self):
"""python3 -m unittest graphviz.GZTest.TestGZ.test_graph_builder"""
b = GraphBuilder('GZTest', {'fontname': '"sans bold"', 'shape': 'doublecircle', 'style': 'filled'})
b.node('A', attrs={'label': '"STO... | the_stack_v2_python_sparse | graphviz/GZTest.py | rcrowther/wild | train | 0 |
bb1b1932492c568a3117bdff4f149386c95123f5 | [
"super().__init__()\nself.conv1 = nn.Conv2d(in_channels, 6, kernel_size=5, bias=False)\nself.pool = nn.MaxPool2d(kernel_size=2, stride=2)\nself.conv2 = nn.Conv2d(6, 16, kernel_size=5, bias=False)\nself.fc1 = nn.Linear(16 * 13 * 13, 120)\nself.fc2 = nn.Linear(120, 84)\nself.fc3 = nn.Linear(84, out_channels)\nself.si... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2d(in_channels, 6, kernel_size=5, bias=False)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5, bias=False)
self.fc1 = nn.Linear(16 * 13 * 13, 120)
self.fc2 = nn.Linear(12... | Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (2): Conv2d(6, 16, kernel_size=(5, 5), s... | CNNNetBasic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNNetBasic:
"""Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (... | stack_v2_sparse_classes_36k_train_017444 | 5,888 | no_license | [
{
"docstring": ":param in_channels : int, image channel size - default : in_channels = 1 :param out_channels : int, number of output classes - default : out_channels = 2",
"name": "__init__",
"signature": "def __init__(self, in_channels: int=1, out_channels: int=2) -> None"
},
{
"docstring": ":p... | 2 | stack_v2_sparse_classes_30k_train_016430 | Implement the Python class `CNNNetBasic` described below.
Class description:
Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, pa... | Implement the Python class `CNNNetBasic` described below.
Class description:
Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, pa... | 9189d2eeb748b1e539a1062a09a06b38a09780de | <|skeleton|>
class CNNNetBasic:
"""Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNNetBasic:
"""Basic neural network class for residual maps. The output returns a sigmoid of size out_channels. Neural network structure : (conv_base): (0): Conv2d(in_channels, 6, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (2): Conv2d(6,... | the_stack_v2_python_sparse | Simulations/helpers/model/baseline.py | emmahoggett/Error_class_lenstronomy | train | 1 |
081dc29a1fc95b725e09bf79c65e6400305fbc09 | [
"heapq.heapify(nums)\nself.nums = nums\nself.k = k",
"heapq.heappush(self.nums, val)\ntry:\n return heapq.nlargest(self.k, self.nums)[self.k - 1]\nexcept:\n print('No such Kth element in the queue')"
] | <|body_start_0|>
heapq.heapify(nums)
self.nums = nums
self.k = k
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.nums, val)
try:
return heapq.nlargest(self.k, self.nums)[self.k - 1]
except:
print('No such Kth element in the queue')
<|end_body_... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
heapq.heapify(nums)
self.nums = nums
self.... | stack_v2_sparse_classes_36k_train_017445 | 3,962 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009469 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
heapq.heapify(nums)
self.nums = nums
self.k = k
def add(self, val):
""":type val: int :rtype: int"""
heapq.heappush(self.nums, val)
try:
return heapq.nlarg... | the_stack_v2_python_sparse | Heap/703. Kth Largest Element in a Stream.py | beninghton/notGivenUpToG | train | 0 | |
45afb7c4121def57063cffebc1ef6b708a0d803f | [
"n = len(s)\ndp = self.palindrome_state(s)\ncut_dp = [None] * n\nfor i in xrange(n):\n if dp[0][i]:\n cut_dp[i] = 0\n else:\n cut_dp[i] = i\n for j in xrange(1, i + 1):\n if dp[j][i]:\n cut_dp[i] = min(cut_dp[i], cut_dp[j - 1] + 1)\nreturn cut_dp[-1]",
"n = len... | <|body_start_0|>
n = len(s)
dp = self.palindrome_state(s)
cut_dp = [None] * n
for i in xrange(n):
if dp[0][i]:
cut_dp[i] = 0
else:
cut_dp[i] = i
for j in xrange(1, i + 1):
if dp[j][i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def palindrome_state(self, s):
"""This is the crux of palindrome related questions. Find the palindrome state of given string with O(n^2). dp[i][j] indicates that whether substring s[i:j+1] is p... | stack_v2_sparse_classes_36k_train_017446 | 1,923 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "minCut",
"signature": "def minCut(self, s)"
},
{
"docstring": "This is the crux of palindrome related questions. Find the palindrome state of given string with O(n^2). dp[i][j] indicates that whether substring s[i:j+1] is palindrome. Three case... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int
- def palindrome_state(self, s): This is the crux of palindrome related questions. Find the palindrome state of given string with O(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCut(self, s): :type s: str :rtype: int
- def palindrome_state(self, s): This is the crux of palindrome related questions. Find the palindrome state of given string with O(... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def palindrome_state(self, s):
"""This is the crux of palindrome related questions. Find the palindrome state of given string with O(n^2). dp[i][j] indicates that whether substring s[i:j+1] is p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCut(self, s):
""":type s: str :rtype: int"""
n = len(s)
dp = self.palindrome_state(s)
cut_dp = [None] * n
for i in xrange(n):
if dp[0][i]:
cut_dp[i] = 0
else:
cut_dp[i] = i
for j in... | the_stack_v2_python_sparse | dynamic_programming/leetcode_Palindrome_Partitioning_II.py | monkeylyf/interviewjam | train | 59 | |
af9675e501c88288332d9de915d27b0af11eab7e | [
"mongo = MongoDBConnection()\nwith mongo:\n db = mongo.connection.hp_norton\n db['customers'].drop()\n db['products'].drop()\n db['rentals'].drop()",
"mongo = MongoDBConnection()\nwith mongo:\n db = mongo.connection.hp_norton\n db['customers'].drop()\n db['products'].drop()\n db['rentals']... | <|body_start_0|>
mongo = MongoDBConnection()
with mongo:
db = mongo.connection.hp_norton
db['customers'].drop()
db['products'].drop()
db['rentals'].drop()
<|end_body_0|>
<|body_start_1|>
mongo = MongoDBConnection()
with mongo:
... | Test all Database functions | TestBasicOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBasicOperations:
"""Test all Database functions"""
def setUp(self):
"""Remove collections and start with no data"""
<|body_0|>
def tearDown(self):
"""Remove collections"""
<|body_1|>
def test_import_data(self):
"""Test importing data from... | stack_v2_sparse_classes_36k_train_017447 | 3,112 | no_license | [
{
"docstring": "Remove collections and start with no data",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Remove collections",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Test importing data from csv into mongodb",
"name": "te... | 6 | null | Implement the Python class `TestBasicOperations` described below.
Class description:
Test all Database functions
Method signatures and docstrings:
- def setUp(self): Remove collections and start with no data
- def tearDown(self): Remove collections
- def test_import_data(self): Test importing data from csv into mongo... | Implement the Python class `TestBasicOperations` described below.
Class description:
Test all Database functions
Method signatures and docstrings:
- def setUp(self): Remove collections and start with no data
- def tearDown(self): Remove collections
- def test_import_data(self): Test importing data from csv into mongo... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestBasicOperations:
"""Test all Database functions"""
def setUp(self):
"""Remove collections and start with no data"""
<|body_0|>
def tearDown(self):
"""Remove collections"""
<|body_1|>
def test_import_data(self):
"""Test importing data from... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBasicOperations:
"""Test all Database functions"""
def setUp(self):
"""Remove collections and start with no data"""
mongo = MongoDBConnection()
with mongo:
db = mongo.connection.hp_norton
db['customers'].drop()
db['products'].drop()
... | the_stack_v2_python_sparse | students/eric_grandeo/lesson05/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
c2a8e865ff664932e9edbe4ac97bc7decfd0af14 | [
"self._currency_or_init_punct = Regex(' ([\\\\p{Sc}\\\\(\\\\[\\\\{\\\\¿\\\\¡]+) ', flags=UNICODE)\nself._noprespace_punct = Regex(' ([\\\\,\\\\.\\\\?\\\\!\\\\:\\\\;\\\\\\\\\\\\%\\\\}\\\\]\\\\)]+) ', flags=UNICODE)\nself._contract = Regex(\" (\\\\p{Alpha}+) ' (ll|ve|re|[dsmt])(?= )\", flags=UNICODE | IGNORECASE)\nse... | <|body_start_0|>
self._currency_or_init_punct = Regex(' ([\\p{Sc}\\(\\[\\{\\¿\\¡]+) ', flags=UNICODE)
self._noprespace_punct = Regex(' ([\\,\\.\\?\\!\\:\\;\\\\\\%\\}\\]\\)]+) ', flags=UNICODE)
self._contract = Regex(" (\\p{Alpha}+) ' (ll|ve|re|[dsmt])(?= )", flags=UNICODE | IGNORECASE)
s... | A simple de-tokenizer class. | Detokenizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Detokenizer:
"""A simple de-tokenizer class."""
def __init__(self):
"""Constructor (pre-compile all needed regexes)."""
<|body_0|>
def detokenize(self, text):
"""Detokenize the given text."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._cu... | stack_v2_sparse_classes_36k_train_017448 | 2,470 | no_license | [
{
"docstring": "Constructor (pre-compile all needed regexes).",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Detokenize the given text.",
"name": "detokenize",
"signature": "def detokenize(self, text)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000172 | Implement the Python class `Detokenizer` described below.
Class description:
A simple de-tokenizer class.
Method signatures and docstrings:
- def __init__(self): Constructor (pre-compile all needed regexes).
- def detokenize(self, text): Detokenize the given text. | Implement the Python class `Detokenizer` described below.
Class description:
A simple de-tokenizer class.
Method signatures and docstrings:
- def __init__(self): Constructor (pre-compile all needed regexes).
- def detokenize(self, text): Detokenize the given text.
<|skeleton|>
class Detokenizer:
"""A simple de-t... | fb738681da71edabe18b2b673de02b72af9791a1 | <|skeleton|>
class Detokenizer:
"""A simple de-tokenizer class."""
def __init__(self):
"""Constructor (pre-compile all needed regexes)."""
<|body_0|>
def detokenize(self, text):
"""Detokenize the given text."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Detokenizer:
"""A simple de-tokenizer class."""
def __init__(self):
"""Constructor (pre-compile all needed regexes)."""
self._currency_or_init_punct = Regex(' ([\\p{Sc}\\(\\[\\{\\¿\\¡]+) ', flags=UNICODE)
self._noprespace_punct = Regex(' ([\\,\\.\\?\\!\\:\\;\\\\\\%\\}\\]\\)]+) ', ... | the_stack_v2_python_sparse | e2e-challenge/postprocess/postprocess.py | ProjectsUCSC/E2E-NLG-Personage | train | 4 |
83c0b70fcf56401f49bfb8cc4801d338245a861e | [
"collaboration = db.Collaboration.get(id)\nif not collaboration:\n return ({'msg': 'collaboration having collaboration_id={} can not be found'.format(id)}, HTTPStatus.NOT_FOUND)\norg_schema = OrganizationSchema()\nreturn (org_schema.dump(collaboration.organizations, many=True).data, HTTPStatus.OK)",
"collabora... | <|body_start_0|>
collaboration = db.Collaboration.get(id)
if not collaboration:
return ({'msg': 'collaboration having collaboration_id={} can not be found'.format(id)}, HTTPStatus.NOT_FOUND)
org_schema = OrganizationSchema()
return (org_schema.dump(collaboration.organizations... | Resource for /api/collaboration/<int:id>/organization. | CollaborationOrganization | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollaborationOrganization:
"""Resource for /api/collaboration/<int:id>/organization."""
def get(self, id):
"""Return organizations for a specific collaboration."""
<|body_0|>
def post(self, id):
"""Add an organizations to a specific collaboration."""
<|bo... | stack_v2_sparse_classes_36k_train_017449 | 14,133 | permissive | [
{
"docstring": "Return organizations for a specific collaboration.",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Add an organizations to a specific collaboration.",
"name": "post",
"signature": "def post(self, id)"
},
{
"docstring": "Removes an organization... | 3 | stack_v2_sparse_classes_30k_train_017112 | Implement the Python class `CollaborationOrganization` described below.
Class description:
Resource for /api/collaboration/<int:id>/organization.
Method signatures and docstrings:
- def get(self, id): Return organizations for a specific collaboration.
- def post(self, id): Add an organizations to a specific collabora... | Implement the Python class `CollaborationOrganization` described below.
Class description:
Resource for /api/collaboration/<int:id>/organization.
Method signatures and docstrings:
- def get(self, id): Return organizations for a specific collaboration.
- def post(self, id): Add an organizations to a specific collabora... | a64827981db26b34dd1dcea1cb2282d03dd4545d | <|skeleton|>
class CollaborationOrganization:
"""Resource for /api/collaboration/<int:id>/organization."""
def get(self, id):
"""Return organizations for a specific collaboration."""
<|body_0|>
def post(self, id):
"""Add an organizations to a specific collaboration."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollaborationOrganization:
"""Resource for /api/collaboration/<int:id>/organization."""
def get(self, id):
"""Return organizations for a specific collaboration."""
collaboration = db.Collaboration.get(id)
if not collaboration:
return ({'msg': 'collaboration having coll... | the_stack_v2_python_sparse | vantage6/server/resource/collaboration.py | mindrenee/vantage6-server | train | 0 |
1e9ebb1104b3dcf9ff4f3bd5067e1a4f0c58abd6 | [
"List = self.indexChar(S, C)\nresult = []\nfor i in range(len(S)):\n result.append(min((abs(i - k) for k in List)))\nreturn result",
"res = []\nif len(S) == 0 or C not in S:\n return -1\nfor i in range(len(S)):\n if S[i] == C:\n res.append(i)\nreturn res"
] | <|body_start_0|>
List = self.indexChar(S, C)
result = []
for i in range(len(S)):
result.append(min((abs(i - k) for k in List)))
return result
<|end_body_0|>
<|body_start_1|>
res = []
if len(S) == 0 or C not in S:
return -1
for i in range(l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def indexChar(self, S, C):
"""找出S中C的所有下标索引"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
List = self.indexChar(S, C)
result = []
... | stack_v2_sparse_classes_36k_train_017450 | 653 | no_license | [
{
"docstring": ":type S: str :type C: str :rtype: List[int]",
"name": "shortestToChar",
"signature": "def shortestToChar(self, S, C)"
},
{
"docstring": "找出S中C的所有下标索引",
"name": "indexChar",
"signature": "def indexChar(self, S, C)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016093 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def indexChar(self, S, C): 找出S中C的所有下标索引 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestToChar(self, S, C): :type S: str :type C: str :rtype: List[int]
- def indexChar(self, S, C): 找出S中C的所有下标索引
<|skeleton|>
class Solution:
def shortestToChar(self, ... | 2df5d3b361bc7d25cd3d2afd5ac1c64fbc303920 | <|skeleton|>
class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
<|body_0|>
def indexChar(self, S, C):
"""找出S中C的所有下标索引"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestToChar(self, S, C):
""":type S: str :type C: str :rtype: List[int]"""
List = self.indexChar(S, C)
result = []
for i in range(len(S)):
result.append(min((abs(i - k) for k in List)))
return result
def indexChar(self, S, C):
"... | the_stack_v2_python_sparse | leetcode_821.py | SongJialiJiali/test | train | 0 | |
cf19259f3570c5b3ae0df5767a57cf271949b98a | [
"rec_unit = rec_unit.lower()\nassert rec_unit in RNN.__rec_units, 'Specified recurrent unit is not available'\nsuper(RNN, self).__init__()\nself.embeddings = nn.Embedding(vocab_size, emb_size)\nself.unit = RNN.__rec_units[rec_unit](emb_size, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(hidden... | <|body_start_0|>
rec_unit = rec_unit.lower()
assert rec_unit in RNN.__rec_units, 'Specified recurrent unit is not available'
super(RNN, self).__init__()
self.embeddings = nn.Embedding(vocab_size, emb_size)
self.unit = RNN.__rec_units[rec_unit](emb_size, hidden_size, num_layers, b... | Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning. | RNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNN:
"""Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning."""
def __init__(self, emb_size, hidden_size, vocab_size, num_layers=1, rec_unit='gru'):
"""Initializer :param embed_size: size of word embeddings :param hidden... | stack_v2_sparse_classes_36k_train_017451 | 4,029 | permissive | [
{
"docstring": "Initializer :param embed_size: size of word embeddings :param hidden_size: size of hidden state of the recurrent unit :param vocab_size: size of the vocabulary (output of the network) :param num_layers: number of recurrent layers (default=1) :param rec_unit: type of recurrent unit (default=gru)"... | 3 | stack_v2_sparse_classes_30k_train_020744 | Implement the Python class `RNN` described below.
Class description:
Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning.
Method signatures and docstrings:
- def __init__(self, emb_size, hidden_size, vocab_size, num_layers=1, rec_unit='gru'): Initializer... | Implement the Python class `RNN` described below.
Class description:
Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning.
Method signatures and docstrings:
- def __init__(self, emb_size, hidden_size, vocab_size, num_layers=1, rec_unit='gru'): Initializer... | 56571e96030162d844cf9e769b7a5a41d3e0a7bc | <|skeleton|>
class RNN:
"""Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning."""
def __init__(self, emb_size, hidden_size, vocab_size, num_layers=1, rec_unit='gru'):
"""Initializer :param embed_size: size of word embeddings :param hidden... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNN:
"""Recurrent Neural Network for Text Generation. To be used as part of an Encoder-Decoder network for Image Captioning."""
def __init__(self, emb_size, hidden_size, vocab_size, num_layers=1, rec_unit='gru'):
"""Initializer :param embed_size: size of word embeddings :param hidden_size: size o... | the_stack_v2_python_sparse | Week_4/7.22-7.30_Show&Tell/temp/model.py | EricZhu-42/NJU_NLP_SummerCamp_2019 | train | 1 |
20c96b2a15f9417079d418617824268e151a5b0a | [
"if not root:\n return ''\nres = str(root.val)\nif len(root.children) != 0:\n children_res = []\n for child in root.children:\n children_res.append(self.serialize(child))\n res = res + '[' + ' '.join(children_res) + ']'\nreturn res",
"if len(data) == 0:\n return None\nstart = data.find('[')\... | <|body_start_0|>
if not root:
return ''
res = str(root.val)
if len(root.children) != 0:
children_res = []
for child in root.children:
children_res.append(self.serialize(child))
res = res + '[' + ' '.join(children_res) + ']'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_017452 | 1,698 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | stack_v2_sparse_classes_30k_val_000633 | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | d87acd5481a2dbfad7288b73750e6e086650a17d | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
res = str(root.val)
if len(root.children) != 0:
children_res = []
for child in root.children:
child... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree/428. Serialize and Deserialize N-ary Tree(AC).py | BohaoLiGithub/Leetcode | train | 0 | |
63a23d8ff4152990f79278eb7ba063800e1287cf | [
"blocks = Encryption.splitBase64IntoBlocks(data, blocksize)\nprevious = iv\ncipherText = []\nfor block in blocks:\n xor = XOR.b64_Xor(previous, block)\n ct = Encryption.AES.ECB.Encrypt(key, xor)\n cipherText.append(base64.b64decode(ct))\n previous = ct\ncipherText = b''.join(cipherText)\nreturn base64.b... | <|body_start_0|>
blocks = Encryption.splitBase64IntoBlocks(data, blocksize)
previous = iv
cipherText = []
for block in blocks:
xor = XOR.b64_Xor(previous, block)
ct = Encryption.AES.ECB.Encrypt(key, xor)
cipherText.append(base64.b64decode(ct))
... | CBC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBC:
def Encrypt(iv, key, data, blocksize=16):
""">>> All data must be Base64 <<< Encrypts data in AES CBC mode"""
<|body_0|>
def Decrypt(iv, key, data, blocksize=16):
""">>> All data must be Base64 <<< Decrypts data encrypted using AES CBC mode"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_017453 | 26,157 | no_license | [
{
"docstring": ">>> All data must be Base64 <<< Encrypts data in AES CBC mode",
"name": "Encrypt",
"signature": "def Encrypt(iv, key, data, blocksize=16)"
},
{
"docstring": ">>> All data must be Base64 <<< Decrypts data encrypted using AES CBC mode",
"name": "Decrypt",
"signature": "def ... | 2 | null | Implement the Python class `CBC` described below.
Class description:
Implement the CBC class.
Method signatures and docstrings:
- def Encrypt(iv, key, data, blocksize=16): >>> All data must be Base64 <<< Encrypts data in AES CBC mode
- def Decrypt(iv, key, data, blocksize=16): >>> All data must be Base64 <<< Decrypts... | Implement the Python class `CBC` described below.
Class description:
Implement the CBC class.
Method signatures and docstrings:
- def Encrypt(iv, key, data, blocksize=16): >>> All data must be Base64 <<< Encrypts data in AES CBC mode
- def Decrypt(iv, key, data, blocksize=16): >>> All data must be Base64 <<< Decrypts... | 91610f384ccdb6065104d8ce5b3ac0f6d785d20a | <|skeleton|>
class CBC:
def Encrypt(iv, key, data, blocksize=16):
""">>> All data must be Base64 <<< Encrypts data in AES CBC mode"""
<|body_0|>
def Decrypt(iv, key, data, blocksize=16):
""">>> All data must be Base64 <<< Decrypts data encrypted using AES CBC mode"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CBC:
def Encrypt(iv, key, data, blocksize=16):
""">>> All data must be Base64 <<< Encrypts data in AES CBC mode"""
blocks = Encryption.splitBase64IntoBlocks(data, blocksize)
previous = iv
cipherText = []
for block in blocks:
xor = XOR.b64_Xor(previous, block... | the_stack_v2_python_sparse | SharedCode/Function.py | AidanFray/Cryptopals_Crypto_Challenges | train | 3 | |
704d245a3732d243f460aeb8651d0d296a77fb7f | [
"context = {}\nc = context.copy()\nc['uom'] = move.product_uom.id\nc['location'] = move.location_id.id\nproduct = self.pool.get('product.product').browse(cr, uid, move.product_id.id, context=c)\npartial_move = super(stock_partial_move, self)._partial_move_for(cr, uid, move, context=context)\npartial_move.update({'r... | <|body_start_0|>
context = {}
c = context.copy()
c['uom'] = move.product_uom.id
c['location'] = move.location_id.id
product = self.pool.get('product.product').browse(cr, uid, move.product_id.id, context=c)
partial_move = super(stock_partial_move, self)._partial_move_for(c... | stock_partial_move | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_partial_move:
def _partial_move_for(self, cr, uid, move, context=None):
"""Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : id"""
<|body_0|>
def do_partial(self, cr, uid, ids, context=None):
"""Inherit fuction t... | stack_v2_sparse_classes_36k_train_017454 | 3,214 | no_license | [
{
"docstring": "Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : id",
"name": "_partial_move_for",
"signature": "def _partial_move_for(self, cr, uid, move, context=None)"
},
{
"docstring": "Inherit fuction to add constrains in picking @return : s... | 2 | null | Implement the Python class `stock_partial_move` described below.
Class description:
Implement the stock_partial_move class.
Method signatures and docstrings:
- def _partial_move_for(self, cr, uid, move, context=None): Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : i... | Implement the Python class `stock_partial_move` described below.
Class description:
Implement the stock_partial_move class.
Method signatures and docstrings:
- def _partial_move_for(self, cr, uid, move, context=None): Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : i... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_partial_move:
def _partial_move_for(self, cr, uid, move, context=None):
"""Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : id"""
<|body_0|>
def do_partial(self, cr, uid, ids, context=None):
"""Inherit fuction t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_partial_move:
def _partial_move_for(self, cr, uid, move, context=None):
"""Inherit to add real stock quantity in partial move dict @param move : id of picking move @return : id"""
context = {}
c = context.copy()
c['uom'] = move.product_uom.id
c['location'] = move.... | the_stack_v2_python_sparse | v_7/NISS/common_shamil_v3/stock_negative/wizard/stock_partial_move.py | musabahmed/baba | train | 0 | |
3b786df6b51e839673cd16770e2710942cc4da40 | [
"n = str(n)[::-1]\nst = ''\nroman_lst = ['', 'I', 'V', 'X', 'L', 'C', 'D', 'M']\nindex = 0\nfor ch in n if len(n) < 4 else n[:3]:\n index += 2\n if int(ch):\n roman_dict = {0: '*', 1: f'{roman_lst[index - 1]}', 2: f'{roman_lst[index - 1] * 2}', 3: f'{roman_lst[index - 1] * 3}', 4: f'{roman_lst[index - ... | <|body_start_0|>
n = str(n)[::-1]
st = ''
roman_lst = ['', 'I', 'V', 'X', 'L', 'C', 'D', 'M']
index = 0
for ch in n if len(n) < 4 else n[:3]:
index += 2
if int(ch):
roman_dict = {0: '*', 1: f'{roman_lst[index - 1]}', 2: f'{roman_lst[index -... | RomanNumerals | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RomanNumerals:
def to_roman(n):
"""Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от индекса в строке создаем соответсвенный словарь из римских цифр. Первая цифра в строке это единицы, потом... | stack_v2_sparse_classes_36k_train_017455 | 4,897 | no_license | [
{
"docstring": "Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от индекса в строке создаем соответсвенный словарь из римских цифр. Первая цифра в строке это единицы, потом десятки, сотни и тысяча. Для каждого измер... | 2 | stack_v2_sparse_classes_30k_train_005219 | Implement the Python class `RomanNumerals` described below.
Class description:
Implement the RomanNumerals class.
Method signatures and docstrings:
- def to_roman(n): Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от инд... | Implement the Python class `RomanNumerals` described below.
Class description:
Implement the RomanNumerals class.
Method signatures and docstrings:
- def to_roman(n): Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от инд... | 8f676985ca7ee9dc592778f5958352f183ce8029 | <|skeleton|>
class RomanNumerals:
def to_roman(n):
"""Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от индекса в строке создаем соответсвенный словарь из римских цифр. Первая цифра в строке это единицы, потом... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RomanNumerals:
def to_roman(n):
"""Функция переводит число в римское Принцип работы: Получаем число, его преобразуем в строку и переворачиваем, далее идем по строке и отталкиваясь от индекса в строке создаем соответсвенный словарь из римских цифр. Первая цифра в строке это единицы, потом десятки, сотн... | the_stack_v2_python_sparse | 4/Roman Numerals Helper 4kyu.py | VIVERA83/Codewars | train | 0 | |
2cecdee2ee3b86790ccbfed39cfbd3e01c1448b1 | [
"search = self\nif document_pid:\n search = search.filter('term', document_pid=document_pid)\nelse:\n raise MissingRequiredParameterError(description='document_pid is required')\nreturn search",
"search = self\nif patron_pid:\n search = search.filter('term', patron_pid=patron_pid)\nelse:\n raise Missi... | <|body_start_0|>
search = self
if document_pid:
search = search.filter('term', document_pid=document_pid)
else:
raise MissingRequiredParameterError(description='document_pid is required')
return search
<|end_body_0|>
<|body_start_1|>
search = self
... | Search for ILL borrowing requests. | BorrowingRequestsSearch | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BorrowingRequestsSearch:
"""Search for ILL borrowing requests."""
def search_by_document_pid(self, document_pid=None):
"""Search by document pid."""
<|body_0|>
def search_by_patron_pid(self, patron_pid=None):
"""Search by patron pid."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_017456 | 1,606 | permissive | [
{
"docstring": "Search by document pid.",
"name": "search_by_document_pid",
"signature": "def search_by_document_pid(self, document_pid=None)"
},
{
"docstring": "Search by patron pid.",
"name": "search_by_patron_pid",
"signature": "def search_by_patron_pid(self, patron_pid=None)"
},
... | 3 | null | Implement the Python class `BorrowingRequestsSearch` described below.
Class description:
Search for ILL borrowing requests.
Method signatures and docstrings:
- def search_by_document_pid(self, document_pid=None): Search by document pid.
- def search_by_patron_pid(self, patron_pid=None): Search by patron pid.
- def se... | Implement the Python class `BorrowingRequestsSearch` described below.
Class description:
Search for ILL borrowing requests.
Method signatures and docstrings:
- def search_by_document_pid(self, document_pid=None): Search by document pid.
- def search_by_patron_pid(self, patron_pid=None): Search by patron pid.
- def se... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class BorrowingRequestsSearch:
"""Search for ILL borrowing requests."""
def search_by_document_pid(self, document_pid=None):
"""Search by document pid."""
<|body_0|>
def search_by_patron_pid(self, patron_pid=None):
"""Search by patron pid."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BorrowingRequestsSearch:
"""Search for ILL borrowing requests."""
def search_by_document_pid(self, document_pid=None):
"""Search by document pid."""
search = self
if document_pid:
search = search.filter('term', document_pid=document_pid)
else:
raise... | the_stack_v2_python_sparse | invenio_app_ils/ill/search.py | inveniosoftware/invenio-app-ils | train | 64 |
58dad088a62149f810dfc1ccb95e6f92adf51455 | [
"self.config = config\nself.s3_util = CORTXS3Util(self.config, connectionType)\nif connection is None:\n super(CORTXS3KVApi, self).__init__(self.config, connectionType)\nelse:\n super(CORTXS3KVApi, self).__init__(self.config, connectionType, connection=connection)",
"if index_id is None:\n Log.error('Ind... | <|body_start_0|>
self.config = config
self.s3_util = CORTXS3Util(self.config, connectionType)
if connection is None:
super(CORTXS3KVApi, self).__init__(self.config, connectionType)
else:
super(CORTXS3KVApi, self).__init__(self.config, connectionType, connection=co... | CORTXS3KVApi provides key-value REST-API's Put, Get & Delete. | CORTXS3KVApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
<|body_0|>
def put(self, index_id=None, object_key_name=None, value=''):
"""Perform PUT request... | stack_v2_sparse_classes_36k_train_017457 | 8,568 | permissive | [
{
"docstring": "Initialise config.",
"name": "__init__",
"signature": "def __init__(self, config, connectionType, connection=None)"
},
{
"docstring": "Perform PUT request and generate response.",
"name": "put",
"signature": "def put(self, index_id=None, object_key_name=None, value='')"
... | 4 | null | Implement the Python class `CORTXS3KVApi` described below.
Class description:
CORTXS3KVApi provides key-value REST-API's Put, Get & Delete.
Method signatures and docstrings:
- def __init__(self, config, connectionType, connection=None): Initialise config.
- def put(self, index_id=None, object_key_name=None, value='')... | Implement the Python class `CORTXS3KVApi` described below.
Class description:
CORTXS3KVApi provides key-value REST-API's Put, Get & Delete.
Method signatures and docstrings:
- def __init__(self, config, connectionType, connection=None): Initialise config.
- def put(self, index_id=None, object_key_name=None, value='')... | b1987967aec7e24530c9703db6f100d2c8289624 | <|skeleton|>
class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
<|body_0|>
def put(self, index_id=None, object_key_name=None, value=''):
"""Perform PUT request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CORTXS3KVApi:
"""CORTXS3KVApi provides key-value REST-API's Put, Get & Delete."""
def __init__(self, config, connectionType, connection=None):
"""Initialise config."""
self.config = config
self.s3_util = CORTXS3Util(self.config, connectionType)
if connection is None:
... | the_stack_v2_python_sparse | s3backgrounddelete/s3backgrounddelete/cortx_s3_kv_api.py | Seagate/cortx-s3server | train | 38 |
dc23c666751810a04c60f005135e3070854fb3d8 | [
"x, y = (len(grid), len(grid[0]))\nfor i in range(x):\n for j in range(y):\n if i == 0 and j != 0:\n grid[i][j] = grid[i][j - 1] + grid[i][j]\n elif i != 0 and j == 0:\n grid[i][j] = grid[i - 1][j] + grid[i][j]\n elif i != 0 and j != 0:\n grid[i][j] = min(gri... | <|body_start_0|>
x, y = (len(grid), len(grid[0]))
for i in range(x):
for j in range(y):
if i == 0 and j != 0:
grid[i][j] = grid[i][j - 1] + grid[i][j]
elif i != 0 and j == 0:
grid[i][j] = grid[i - 1][j] + grid[i][j]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
x, y = (len(grid), len(grid[0]))
... | stack_v2_sparse_classes_36k_train_017458 | 1,117 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum1",
"signature": "def minPathSum1(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
x, y = (len(grid), len(grid[0]))
for i in range(x):
for j in range(y):
if i == 0 and j != 0:
grid[i][j] = grid[i][j - 1] + grid[i][j]
elif... | the_stack_v2_python_sparse | leetcode/064最小路径和.py | ShawDa/Coding | train | 0 | |
324482d1d9260e622e8bc9277d95f1f508700fcd | [
"self.driver.find_element(*self._location_username).send_keys('赫敏2')\nself.driver.find_element(*self._location_acctid).send_keys('020')\nself.driver.find_element(*self._location_Add_phone).send_keys('13177778882')\nself.driver.find_element(By.CSS_SELECTOR, '.js_btn_save').click()\nreturn ContactPage(self.driver)",
... | <|body_start_0|>
self.driver.find_element(*self._location_username).send_keys('赫敏2')
self.driver.find_element(*self._location_acctid).send_keys('020')
self.driver.find_element(*self._location_Add_phone).send_keys('13177778882')
self.driver.find_element(By.CSS_SELECTOR, '.js_btn_save').cl... | AddMember | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMember:
def add_member(self):
"""添加成员操作 :return:"""
<|body_0|>
def add_member_fail(self, acctid, phone):
"""添加成员失败操作 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver.find_element(*self._location_username).send_keys('赫敏2')
... | stack_v2_sparse_classes_36k_train_017459 | 1,753 | no_license | [
{
"docstring": "添加成员操作 :return:",
"name": "add_member",
"signature": "def add_member(self)"
},
{
"docstring": "添加成员失败操作 :return:",
"name": "add_member_fail",
"signature": "def add_member_fail(self, acctid, phone)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016515 | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 添加成员操作 :return:
- def add_member_fail(self, acctid, phone): 添加成员失败操作 :return: | Implement the Python class `AddMember` described below.
Class description:
Implement the AddMember class.
Method signatures and docstrings:
- def add_member(self): 添加成员操作 :return:
- def add_member_fail(self, acctid, phone): 添加成员失败操作 :return:
<|skeleton|>
class AddMember:
def add_member(self):
"""添加成员操作 ... | 5ff767243f7d7f698997633f39ecd4c4ebcc998a | <|skeleton|>
class AddMember:
def add_member(self):
"""添加成员操作 :return:"""
<|body_0|>
def add_member_fail(self, acctid, phone):
"""添加成员失败操作 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMember:
def add_member(self):
"""添加成员操作 :return:"""
self.driver.find_element(*self._location_username).send_keys('赫敏2')
self.driver.find_element(*self._location_acctid).send_keys('020')
self.driver.find_element(*self._location_Add_phone).send_keys('13177778882')
self... | the_stack_v2_python_sparse | test_selenium/test_web_weixin/page/add_member_page.py | ceshiren/HogwartsSDET16 | train | 16 | |
58aba3f885d33b180e3c05ae2fa280d3b3553d2f | [
"self._logger = logging.getLogger(__name__)\nself._dev_ratio = dev_ratio\nself._test_ratio = test_ratio if not n_splits else 1.0 / n_splits\nself._n_splits = n_splits\nself._random_state = random_state\nself._logger.info('Using random state: {}'.format(self._random_state))\nself._logger.info('Splits: {:.2f}/{:.2f}/... | <|body_start_0|>
self._logger = logging.getLogger(__name__)
self._dev_ratio = dev_ratio
self._test_ratio = test_ratio if not n_splits else 1.0 / n_splits
self._n_splits = n_splits
self._random_state = random_state
self._logger.info('Using random state: {}'.format(self._ra... | DataSplitter | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSplitter:
def __init__(self, dev_ratio: float=0.15, test_ratio: float=0.2, n_splits: int=None, random_state: int=None):
"""Initialize class. If n_splits is set, it will override test_ratio. :param dev_ratio: proportion of data to be withheld for model development, defaults to 0.15 :t... | stack_v2_sparse_classes_36k_train_017460 | 6,808 | permissive | [
{
"docstring": "Initialize class. If n_splits is set, it will override test_ratio. :param dev_ratio: proportion of data to be withheld for model development, defaults to 0.15 :type dev_ratio: float, optional :param test_ratio: proportion of data to be withheld for testing, defaults to 0.2 :type test_ratio: floa... | 5 | stack_v2_sparse_classes_30k_train_003773 | Implement the Python class `DataSplitter` described below.
Class description:
Implement the DataSplitter class.
Method signatures and docstrings:
- def __init__(self, dev_ratio: float=0.15, test_ratio: float=0.2, n_splits: int=None, random_state: int=None): Initialize class. If n_splits is set, it will override test_... | Implement the Python class `DataSplitter` described below.
Class description:
Implement the DataSplitter class.
Method signatures and docstrings:
- def __init__(self, dev_ratio: float=0.15, test_ratio: float=0.2, n_splits: int=None, random_state: int=None): Initialize class. If n_splits is set, it will override test_... | bd8599228d95ef42b5879370cdcbc03333b4e461 | <|skeleton|>
class DataSplitter:
def __init__(self, dev_ratio: float=0.15, test_ratio: float=0.2, n_splits: int=None, random_state: int=None):
"""Initialize class. If n_splits is set, it will override test_ratio. :param dev_ratio: proportion of data to be withheld for model development, defaults to 0.15 :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSplitter:
def __init__(self, dev_ratio: float=0.15, test_ratio: float=0.2, n_splits: int=None, random_state: int=None):
"""Initialize class. If n_splits is set, it will override test_ratio. :param dev_ratio: proportion of data to be withheld for model development, defaults to 0.15 :type dev_ratio:... | the_stack_v2_python_sparse | WP3/Task3.3/src/data/data_splitter.py | on-merrit/ON-MERRIT | train | 2 | |
930f36e66d8992398d67959098c8256e92cbbe12 | [
"config = self.xmpp['xep_0004'].Form()\nconfig['type'] = 'submit'\nfor field, value in self.profile.items():\n config.add_field(var=field, value=value)\nreturn self.xmpp['xep_0060'].set_node_config(jid=None, node=node, config=config, **iqkwargs)",
"options = pubsubkwargs.pop('options', None)\nif not options:\n... | <|body_start_0|>
config = self.xmpp['xep_0004'].Form()
config['type'] = 'submit'
for field, value in self.profile.items():
config.add_field(var=field, value=value)
return self.xmpp['xep_0060'].set_node_config(jid=None, node=node, config=config, **iqkwargs)
<|end_body_0|>
<|b... | XEP-0223: Persistent Storage of Private Data via PubSub | XEP_0223 | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XEP_0223:
"""XEP-0223: Persistent Storage of Private Data via PubSub"""
def configure(self, node: str, **iqkwargs) -> Future:
"""Update a node's configuration to match the private storage profile. :param node: Node to set the configuration at."""
<|body_0|>
def store(sel... | stack_v2_sparse_classes_36k_train_017461 | 3,643 | permissive | [
{
"docstring": "Update a node's configuration to match the private storage profile. :param node: Node to set the configuration at.",
"name": "configure",
"signature": "def configure(self, node: str, **iqkwargs) -> Future"
},
{
"docstring": "Store private data via PEP. This is just a (very) thin ... | 3 | null | Implement the Python class `XEP_0223` described below.
Class description:
XEP-0223: Persistent Storage of Private Data via PubSub
Method signatures and docstrings:
- def configure(self, node: str, **iqkwargs) -> Future: Update a node's configuration to match the private storage profile. :param node: Node to set the c... | Implement the Python class `XEP_0223` described below.
Class description:
XEP-0223: Persistent Storage of Private Data via PubSub
Method signatures and docstrings:
- def configure(self, node: str, **iqkwargs) -> Future: Update a node's configuration to match the private storage profile. :param node: Node to set the c... | 7a0fb970833c778ed50dcb49c5b7b4043d57b1e5 | <|skeleton|>
class XEP_0223:
"""XEP-0223: Persistent Storage of Private Data via PubSub"""
def configure(self, node: str, **iqkwargs) -> Future:
"""Update a node's configuration to match the private storage profile. :param node: Node to set the configuration at."""
<|body_0|>
def store(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XEP_0223:
"""XEP-0223: Persistent Storage of Private Data via PubSub"""
def configure(self, node: str, **iqkwargs) -> Future:
"""Update a node's configuration to match the private storage profile. :param node: Node to set the configuration at."""
config = self.xmpp['xep_0004'].Form()
... | the_stack_v2_python_sparse | slixmpp/plugins/xep_0223.py | poezio/slixmpp | train | 97 |
bc10e9eacb2d563140cf7f234e651f8f373a9352 | [
"email = self.cleaned_data['email']\nself.users_cache = User.objects.filter(email__iexact=email, is_active=True)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif any((user.password == UNUSABLE_PASSWORD for user in self.users_cache)):\n raise forms.ValidationErro... | <|body_start_0|>
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise forms.ValidationError(self.error_messages['unknown'])
if any((user.password == UNUSABLE_PASSWORD for user in sel... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g... | stack_v2_sparse_classes_36k_train_017462 | 11,762 | no_license | [
{
"docstring": "Validates that an active user exists with the given email address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, p... | 2 | stack_v2_sparse_classes_30k_train_010251 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, project, subject_template_name='password_reset_subjec... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, project, subject_template_name='password_reset_subjec... | 5633b8c777ffa04e3372c7c5af4a86f672724d71 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise form... | the_stack_v2_python_sparse | invites/forms.py | fabiosussetto/holiday | train | 1 | |
799dd7999dd12775909826786a0967da3a03f5bd | [
"with self.assertRaises(NotImplementedError):\n loss = StrongConvexMixin()\n getattr(loss, fn, None)(*args)",
"loss = StrongConvexMixin()\nret = getattr(loss, fn, None)(*args)\nself.assertNone(ret)"
] | <|body_start_0|>
with self.assertRaises(NotImplementedError):
loss = StrongConvexMixin()
getattr(loss, fn, None)(*args)
<|end_body_0|>
<|body_start_1|>
loss = StrongConvexMixin()
ret = getattr(loss, fn, None)(*args)
self.assertNone(ret)
<|end_body_1|>
| Tests for the StrongConvexMixin. | StrongConvexMixinTests | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
<|body_0|>
def test_return_none(self, fn... | stack_v2_sparse_classes_36k_train_017463 | 14,409 | permissive | [
{
"docstring": "Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin",
"name": "test_not_implemented",
"signature": "def test_not_implemented(self, fn, args)"
},
{
"docstring": "Test that fn of Mixin returns None. Args: fn: fn of... | 2 | stack_v2_sparse_classes_30k_val_001169 | Implement the Python class `StrongConvexMixinTests` described below.
Class description:
Tests for the StrongConvexMixin.
Method signatures and docstrings:
- def test_not_implemented(self, fn, args): Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin... | Implement the Python class `StrongConvexMixinTests` described below.
Class description:
Tests for the StrongConvexMixin.
Method signatures and docstrings:
- def test_not_implemented(self, fn, args): Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
<|body_0|>
def test_return_none(self, fn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
with self.assertRaises(NotImplementedError):
l... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/bolt_on/losses_test.py | tensorflow/privacy | train | 1,881 |
e66c8f45a34c77e8c6473086cf955d51b621db6a | [
"super(PickingResult, self).__init__(item, indices)\nself._objectPositions = numpy.array(positions, copy=False, dtype=numpy.float64)\nprimitive = item._getScenePrimitive()\nself._objectToSceneTransform = primitive.objectToSceneTransform\nself._objectToNDCTransform = primitive.objectToNDCTransform\nself._scenePositi... | <|body_start_0|>
super(PickingResult, self).__init__(item, indices)
self._objectPositions = numpy.array(positions, copy=False, dtype=numpy.float64)
primitive = item._getScenePrimitive()
self._objectToSceneTransform = primitive.objectToSceneTransform
self._objectToNDCTransform = p... | Class to access picking information in a 3D scene. | PickingResult | [
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) i... | stack_v2_sparse_classes_36k_train_017464 | 9,112 | permissive | [
{
"docstring": "Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) in item coordinates. :param numpy.ndarray indices: Array-like of indices of picked data. Either 1D or 2D with dim0: data dimension and dim1: indices. No co... | 3 | stack_v2_sparse_classes_30k_train_004907 | Implement the Python class `PickingResult` described below.
Class description:
Class to access picking information in a 3D scene.
Method signatures and docstrings:
- def __init__(self, item, positions, indices=None, fetchdata=None): Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray ... | Implement the Python class `PickingResult` described below.
Class description:
Class to access picking information in a 3D scene.
Method signatures and docstrings:
- def __init__(self, item, positions, indices=None, fetchdata=None): Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray ... | 5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f | <|skeleton|>
class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) in item coordi... | the_stack_v2_python_sparse | src/silx/gui/plot3d/items/_pick.py | silx-kit/silx | train | 120 |
ae98b8e7b24d255031301d1a6191926e6db7d4f7 | [
"os.chdir(path)\ndbx = dropbox.Dropbox(self.authenticate())\nself.path = path\nself.dbx = dbx",
"with open(f'/home/johan/scriptlang_homeworks/homework-assignment-3-jp1995/dbx_token.ini', 'r') as file:\n access_token = file.readline()\nreturn access_token",
"for i in os.listdir():\n modified = time.ctime(o... | <|body_start_0|>
os.chdir(path)
dbx = dropbox.Dropbox(self.authenticate())
self.path = path
self.dbx = dbx
<|end_body_0|>
<|body_start_1|>
with open(f'/home/johan/scriptlang_homeworks/homework-assignment-3-jp1995/dbx_token.ini', 'r') as file:
access_token = file.read... | MoveOldFiles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoveOldFiles:
def __init__(self, path: str):
"""Class constructor."""
<|body_0|>
def authenticate(self):
"""Get token from file."""
<|body_1|>
def check(self):
"""Check if file is older than 7 days, read and upload to dropbox if so."""
<|... | stack_v2_sparse_classes_36k_train_017465 | 1,206 | no_license | [
{
"docstring": "Class constructor.",
"name": "__init__",
"signature": "def __init__(self, path: str)"
},
{
"docstring": "Get token from file.",
"name": "authenticate",
"signature": "def authenticate(self)"
},
{
"docstring": "Check if file is older than 7 days, read and upload to ... | 3 | stack_v2_sparse_classes_30k_train_020782 | Implement the Python class `MoveOldFiles` described below.
Class description:
Implement the MoveOldFiles class.
Method signatures and docstrings:
- def __init__(self, path: str): Class constructor.
- def authenticate(self): Get token from file.
- def check(self): Check if file is older than 7 days, read and upload to... | Implement the Python class `MoveOldFiles` described below.
Class description:
Implement the MoveOldFiles class.
Method signatures and docstrings:
- def __init__(self, path: str): Class constructor.
- def authenticate(self): Get token from file.
- def check(self): Check if file is older than 7 days, read and upload to... | 8bbc9bfb515fed075dd37fa5303de6cc0f6c7e4e | <|skeleton|>
class MoveOldFiles:
def __init__(self, path: str):
"""Class constructor."""
<|body_0|>
def authenticate(self):
"""Get token from file."""
<|body_1|>
def check(self):
"""Check if file is older than 7 days, read and upload to dropbox if so."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MoveOldFiles:
def __init__(self, path: str):
"""Class constructor."""
os.chdir(path)
dbx = dropbox.Dropbox(self.authenticate())
self.path = path
self.dbx = dbx
def authenticate(self):
"""Get token from file."""
with open(f'/home/johan/scriptlang_hom... | the_stack_v2_python_sparse | homework_3/task2.py | jp1995/scriptlang_hw | train | 0 | |
8332d1aa840d72ab3608afbaf471b4042ee1646f | [
"if len(self) == 0:\n raise GeometryException('no point')\nr = copy.copy(self[0])\nfor i in range(1, len(self)):\n r += self[i]\nreturn r * (1.0 / float(len(self)))",
"bary = self.barycentre()\nprod = [((p - bary).angle(), p) for p in self]\nprod.sort()\nreturn GeometryPolygone([p[1] for p in prod])",
"ci... | <|body_start_0|>
if len(self) == 0:
raise GeometryException('no point')
r = copy.copy(self[0])
for i in range(1, len(self)):
r += self[i]
return r * (1.0 / float(len(self)))
<|end_body_0|>
<|body_start_1|>
bary = self.barycentre()
prod = [((p - ba... | A sequence of point, the last one is connected to the first one. | GeometryPolygone | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometryPolygone:
"""A sequence of point, the last one is connected to the first one."""
def barycentre(self):
"""@return the barycentre"""
<|body_0|>
def circle(self):
"""@return a list of points ordered by angle taken to the barycenter (works only dimension 2)"... | stack_v2_sparse_classes_36k_train_017466 | 2,469 | permissive | [
{
"docstring": "@return the barycentre",
"name": "barycentre",
"signature": "def barycentre(self)"
},
{
"docstring": "@return a list of points ordered by angle taken to the barycenter (works only dimension 2)",
"name": "circle",
"signature": "def circle(self)"
},
{
"docstring": "... | 4 | null | Implement the Python class `GeometryPolygone` described below.
Class description:
A sequence of point, the last one is connected to the first one.
Method signatures and docstrings:
- def barycentre(self): @return the barycentre
- def circle(self): @return a list of points ordered by angle taken to the barycenter (wor... | Implement the Python class `GeometryPolygone` described below.
Class description:
A sequence of point, the last one is connected to the first one.
Method signatures and docstrings:
- def barycentre(self): @return the barycentre
- def circle(self): @return a list of points ordered by angle taken to the barycenter (wor... | 2abbc7a20c7437f9ab91d1ec83a6aecdefceb028 | <|skeleton|>
class GeometryPolygone:
"""A sequence of point, the last one is connected to the first one."""
def barycentre(self):
"""@return the barycentre"""
<|body_0|>
def circle(self):
"""@return a list of points ordered by angle taken to the barycenter (works only dimension 2)"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeometryPolygone:
"""A sequence of point, the last one is connected to the first one."""
def barycentre(self):
"""@return the barycentre"""
if len(self) == 0:
raise GeometryException('no point')
r = copy.copy(self[0])
for i in range(1, len(self)):
r... | the_stack_v2_python_sparse | src/ensae_teaching_cs/special/geometry_polygone.py | Pandinosaurus/ensae_teaching_cs | train | 1 |
da77fa18c51cda3197089ce3509f71356543b19b | [
"self.head = head\nnode = head\ncount = 0\nwhile node is not None:\n count += 1\n node = node.next\nself.length = count",
"randomIndex = randint(0, self.length - 1)\nnode = self.head\ncount = 0\nwhile node is not None:\n if count == randomIndex:\n return node.val\n node = node.next\n count +... | <|body_start_0|>
self.head = head
node = head
count = 0
while node is not None:
count += 1
node = node.next
self.length = count
<|end_body_0|>
<|body_start_1|>
randomIndex = randint(0, self.length - 1)
node = self.head
count = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017467 | 1,068 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_012174 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | c383f848662ce5ea48dd7fc92a4552a0106b4c6e | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
self.head = head
node = head
count = 0
while node is not None:
count += 1
n... | the_stack_v2_python_sparse | leetcode/problems/medium/382-linked-list-random-node.py | MrMagicPickle/competitive-programming | train | 0 | |
810ae83d1693da87a7997b878679ca6f5c7e19b5 | [
"self.total = 0\nself.additional = 0\nself.LaplaceBigramCount = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))\nself.LaplaceUnigramCount = collections.defaultdict(lambda: 0)\nself.train(corpus)",
"lasttoken = '<s>'\nfor sentence in corpus.corpus:\n for datum in sentence.data:\n toke... | <|body_start_0|>
self.total = 0
self.additional = 0
self.LaplaceBigramCount = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
self.LaplaceUnigramCount = collections.defaultdict(lambda: 0)
self.train(corpus)
<|end_body_0|>
<|body_start_1|>
lasttoken = ... | LaplaceBigramLM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaplaceBigramLM:
def __init__(self, corpus):
"""Bigram Languange Model with add-one smoothing is implemented."""
<|body_0|>
def train(self, corpus):
"""Takes a corpus and trains your language model Compute any counts or other corpus statistics in this function"""
... | stack_v2_sparse_classes_36k_train_017468 | 2,115 | no_license | [
{
"docstring": "Bigram Languange Model with add-one smoothing is implemented.",
"name": "__init__",
"signature": "def __init__(self, corpus)"
},
{
"docstring": "Takes a corpus and trains your language model Compute any counts or other corpus statistics in this function",
"name": "train",
... | 3 | stack_v2_sparse_classes_30k_train_014384 | Implement the Python class `LaplaceBigramLM` described below.
Class description:
Implement the LaplaceBigramLM class.
Method signatures and docstrings:
- def __init__(self, corpus): Bigram Languange Model with add-one smoothing is implemented.
- def train(self, corpus): Takes a corpus and trains your language model C... | Implement the Python class `LaplaceBigramLM` described below.
Class description:
Implement the LaplaceBigramLM class.
Method signatures and docstrings:
- def __init__(self, corpus): Bigram Languange Model with add-one smoothing is implemented.
- def train(self, corpus): Takes a corpus and trains your language model C... | 769655d7a95f5d38329f20aa9517bb6c41818db0 | <|skeleton|>
class LaplaceBigramLM:
def __init__(self, corpus):
"""Bigram Languange Model with add-one smoothing is implemented."""
<|body_0|>
def train(self, corpus):
"""Takes a corpus and trains your language model Compute any counts or other corpus statistics in this function"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaplaceBigramLM:
def __init__(self, corpus):
"""Bigram Languange Model with add-one smoothing is implemented."""
self.total = 0
self.additional = 0
self.LaplaceBigramCount = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
self.LaplaceUnigramCount = c... | the_stack_v2_python_sparse | final_project/LaplaceBigramLM.py | jpanda111/UCSC_python | train | 0 | |
7439333ec8e426a8b049722f099e1e21260bcbce | [
"assert peer.id is not None\nif peer.id in self:\n raise ValueError('Peer has already been added')\nself[peer.id] = peer",
"assert peer.id is not None\nif peer.id not in self:\n self.add(peer)\n return peer\nelse:\n current = self[peer.id]\n current.merge(peer)\n return current",
"assert peer.... | <|body_start_0|>
assert peer.id is not None
if peer.id in self:
raise ValueError('Peer has already been added')
self[peer.id] = peer
<|end_body_0|>
<|body_start_1|>
assert peer.id is not None
if peer.id not in self:
self.add(peer)
return peer
... | PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`. | PeerStorage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
... | stack_v2_sparse_classes_36k_train_017469 | 1,737 | permissive | [
{
"docstring": "Add a new peer to the storage. Raises a `ValueError` if the peer has already been added.",
"name": "add",
"signature": "def add(self, peer: PeerId) -> None"
},
{
"docstring": "Add a peer to the storage if it has not been added yet. Otherwise, merge the current peer with the given... | 3 | null | Implement the Python class `PeerStorage` described below.
Class description:
PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`.
Method signatures and docstrings:
- def add(self, peer: PeerId) -> None: Add a new peer to the storage. Rais... | Implement the Python class `PeerStorage` described below.
Class description:
PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`.
Method signatures and docstrings:
- def add(self, peer: PeerId) -> None: Add a new peer to the storage. Rais... | 78229b7c99365229a7a806a4660d17234c0b2a9a | <|skeleton|>
class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeerStorage:
"""PeerStorage is used to store all known peers in memory. It is a dict of peer objects, and peers can be retrieved by their `peer.id`."""
def add(self, peer: PeerId) -> None:
"""Add a new peer to the storage. Raises a `ValueError` if the peer has already been added."""
asser... | the_stack_v2_python_sparse | hathor/p2p/peer_storage.py | HathorNetwork/hathor-core | train | 75 |
37e07e2b98c4d807b9c329fd0afdad6e179fe946 | [
"self.entity_description = description\nself._attr_unique_id = f'{DOMAIN}-{description.key}-{inverter.serial_number}'\nself._attr_device_info = device_info\nself._attr_options = supported_options\nself._attr_current_option = current_mode\nself._inverter: Inverter = inverter",
"await self._inverter.set_operation_m... | <|body_start_0|>
self.entity_description = description
self._attr_unique_id = f'{DOMAIN}-{description.key}-{inverter.serial_number}'
self._attr_device_info = device_info
self._attr_options = supported_options
self._attr_current_option = current_mode
self._inverter: Invert... | Entity representing the inverter operation mode. | InverterOperationModeEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InverterOperationModeEntity:
"""Entity representing the inverter operation mode."""
def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_mode: str) -> None:
"""Initialize the inverter operation mod... | stack_v2_sparse_classes_36k_train_017470 | 3,315 | permissive | [
{
"docstring": "Initialize the inverter operation mode setting entity.",
"name": "__init__",
"signature": "def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_mode: str) -> None"
},
{
"docstring": "Change the... | 2 | null | Implement the Python class `InverterOperationModeEntity` described below.
Class description:
Entity representing the inverter operation mode.
Method signatures and docstrings:
- def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_... | Implement the Python class `InverterOperationModeEntity` described below.
Class description:
Entity representing the inverter operation mode.
Method signatures and docstrings:
- def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class InverterOperationModeEntity:
"""Entity representing the inverter operation mode."""
def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_mode: str) -> None:
"""Initialize the inverter operation mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InverterOperationModeEntity:
"""Entity representing the inverter operation mode."""
def __init__(self, device_info: DeviceInfo, description: SelectEntityDescription, inverter: Inverter, supported_options: list[str], current_mode: str) -> None:
"""Initialize the inverter operation mode setting ent... | the_stack_v2_python_sparse | homeassistant/components/goodwe/select.py | home-assistant/core | train | 35,501 |
aab8f7787cd53135202d7158683af3e58d28e57a | [
"self.wx_menu = wx.Menu()\nparent = self.parent\nwhile parent and parent.widget_name != 'window':\n parent = parent.parent\nparent.wx_menus.append(self)",
"parent = self.parent\nif parent.widget_name in ('context', 'menu'):\n parent.wx_menu.AppendSubMenu(self.wx_menu, self.generic.name)\nelse:\n parent.w... | <|body_start_0|>
self.wx_menu = wx.Menu()
parent = self.parent
while parent and parent.widget_name != 'window':
parent = parent.parent
parent.wx_menus.append(self)
<|end_body_0|>
<|body_start_1|>
parent = self.parent
if parent.widget_name in ('context', 'menu... | WX4Menu | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WX4Menu:
def _init(self):
"""Initialize the menu."""
<|body_0|>
def _complete(self, window):
"""Complete the menu."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wx_menu = wx.Menu()
parent = self.parent
while parent and parent.... | stack_v2_sparse_classes_36k_train_017471 | 789 | permissive | [
{
"docstring": "Initialize the menu.",
"name": "_init",
"signature": "def _init(self)"
},
{
"docstring": "Complete the menu.",
"name": "_complete",
"signature": "def _complete(self, window)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006239 | Implement the Python class `WX4Menu` described below.
Class description:
Implement the WX4Menu class.
Method signatures and docstrings:
- def _init(self): Initialize the menu.
- def _complete(self, window): Complete the menu. | Implement the Python class `WX4Menu` described below.
Class description:
Implement the WX4Menu class.
Method signatures and docstrings:
- def _init(self): Initialize the menu.
- def _complete(self, window): Complete the menu.
<|skeleton|>
class WX4Menu:
def _init(self):
"""Initialize the menu."""
... | 2ff2a0f38119f22ac292aa533dbee3fb4fa04a41 | <|skeleton|>
class WX4Menu:
def _init(self):
"""Initialize the menu."""
<|body_0|>
def _complete(self, window):
"""Complete the menu."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WX4Menu:
def _init(self):
"""Initialize the menu."""
self.wx_menu = wx.Menu()
parent = self.parent
while parent and parent.widget_name != 'window':
parent = parent.parent
parent.wx_menus.append(self)
def _complete(self, window):
"""Complete the ... | the_stack_v2_python_sparse | bui/specific/wx4/menu.py | vincent-lg/bui | train | 4 | |
5b2ae067c1386d1e7ca22d6b3c699ba0314b4017 | [
"adminUserObj = User.objects.filter(is_admin=True)\nserializer = UserSerializer(adminUserObj, many=True)\nreturn Response(serializer.data)",
"print(request.data)\nusername = request.data['username']\nprint(username)\nserializer = UserSerializer(data=request.data)\nif serializer.is_valid(raise_exception=ValueError... | <|body_start_0|>
adminUserObj = User.objects.filter(is_admin=True)
serializer = UserSerializer(adminUserObj, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
print(request.data)
username = request.data['username']
print(username)
serial... | A class based view for signing up admins | adminSignupView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class adminSignupView:
"""A class based view for signing up admins"""
def get(self, format=None):
"""Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records"""
<|body_0|>
def post(self, request, format... | stack_v2_sparse_classes_36k_train_017472 | 1,933 | no_license | [
{
"docstring": "Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records",
"name": "get",
"signature": "def get(self, format=None)"
},
{
"docstring": "Create a student record :param format: Format of the student records t... | 2 | null | Implement the Python class `adminSignupView` described below.
Class description:
A class based view for signing up admins
Method signatures and docstrings:
- def get(self, format=None): Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records
... | Implement the Python class `adminSignupView` described below.
Class description:
A class based view for signing up admins
Method signatures and docstrings:
- def get(self, format=None): Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records
... | 88e4e994a029527d9e6b9431155a81cd5774b63c | <|skeleton|>
class adminSignupView:
"""A class based view for signing up admins"""
def get(self, format=None):
"""Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records"""
<|body_0|>
def post(self, request, format... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class adminSignupView:
"""A class based view for signing up admins"""
def get(self, format=None):
"""Get all the student records :param format: Format of the student records to return to 00 :return: Returns a list of student records"""
adminUserObj = User.objects.filter(is_admin=True)
s... | the_stack_v2_python_sparse | myuser/views/adminSignupView.py | anku580/Upfront---Backend | train | 0 |
bf749e141ebf205ae4187ec7889da3c2868a7586 | [
"fields = collections.OrderedDict()\nfor base in bases:\n if hasattr(base, '__fields__'):\n fields.update(base.__fields__)\nreturn collections.OrderedDict(__fields__=fields)",
"if '__additional__' not in attrs:\n attrs['__additional__'] = []\nif '__excluded__' not in attrs:\n attrs['__excluded__']... | <|body_start_0|>
fields = collections.OrderedDict()
for base in bases:
if hasattr(base, '__fields__'):
fields.update(base.__fields__)
return collections.OrderedDict(__fields__=fields)
<|end_body_0|>
<|body_start_1|>
if '__additional__' not in attrs:
... | Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. * :attr:`Schema.__fields__` is a dictionary of field names and their correspon... | SchemaMeta | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaMeta:
"""Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. * :attr:`Schema.__fields__` is a diction... | stack_v2_sparse_classes_36k_train_017473 | 29,320 | permissive | [
{
"docstring": "Prepare the namespace for the schema class. Args: name: Name of the schema class. bases: Base classes of the schema class. **kwds: Additional keyword arguments at class definition. This method is used to create the initial field dictionary :attr:`~Schema.__fields__` for the schema class.",
"... | 2 | null | Implement the Python class `SchemaMeta` described below.
Class description:
Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. *... | Implement the Python class `SchemaMeta` described below.
Class description:
Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. *... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class SchemaMeta:
"""Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. * :attr:`Schema.__fields__` is a diction... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaMeta:
"""Meta class to add dynamic support to :class:`Schema`. This meta class is used to generate necessary attributes for the :class:`Schema` class. It can be useful to reduce runtime generation cost as well as caching already generated attributes. * :attr:`Schema.__fields__` is a dictionary of field ... | the_stack_v2_python_sparse | pcapkit/protocols/schema/schema.py | JarryShaw/PyPCAPKit | train | 204 |
4f7e9addfb39074feb1d322c0bd07b308cf68142 | [
"r1 = requests.get(url=self.asset_api)\nhostname_list = r1.json()\npool = ThreadPoolExecutor(20)\nfor hostname in hostname_list:\n pool.submit(self.task, hostname)",
"try:\n info = get_server_info(self, hostname)\n r1 = requests.post(url=self.asset_api, data=json.dumps(info).encode('utf-8'), headers={'Co... | <|body_start_0|>
r1 = requests.get(url=self.asset_api)
hostname_list = r1.json()
pool = ThreadPoolExecutor(20)
for hostname in hostname_list:
pool.submit(self.task, hostname)
<|end_body_0|>
<|body_start_1|>
try:
info = get_server_info(self, hostname)
... | SshAndSalt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SshAndSalt:
def handler(self):
"""处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:"""
<|body_0|>
def task(self, hostname):
"""执行采集器,拿到采集结果汇报给API 1. 执行所有的采集器拿到info 2. 汇报info给api :param hostname: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_017474 | 2,083 | no_license | [
{
"docstring": "处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:",
"name": "handler",
"signature": "def handler(self)"
},
{
"docstring": "执行采集器,拿到采集结果汇报给API 1. 执行所有的采集器拿到info 2. 汇报info给api :param hostname: :return:",
"name": "task",
"signature": "def ta... | 2 | stack_v2_sparse_classes_30k_train_005404 | Implement the Python class `SshAndSalt` described below.
Class description:
Implement the SshAndSalt class.
Method signatures and docstrings:
- def handler(self): 处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:
- def task(self, hostname): 执行采集器,拿到采集结果汇报给API 1. 执行所有的采集器拿到info 2. 汇报i... | Implement the Python class `SshAndSalt` described below.
Class description:
Implement the SshAndSalt class.
Method signatures and docstrings:
- def handler(self): 处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:
- def task(self, hostname): 执行采集器,拿到采集结果汇报给API 1. 执行所有的采集器拿到info 2. 汇报i... | d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7 | <|skeleton|>
class SshAndSalt:
def handler(self):
"""处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:"""
<|body_0|>
def task(self, hostname):
"""执行采集器,拿到采集结果汇报给API 1. 执行所有的采集器拿到info 2. 汇报info给api :param hostname: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SshAndSalt:
def handler(self):
"""处理SSH/SALT模式下的资产采集 1. 通过api获取需要采集的主机列表 2. 使用线程池实现并发处理 3. 把所有的主机交给task方法去采集 :return:"""
r1 = requests.get(url=self.asset_api)
hostname_list = r1.json()
pool = ThreadPoolExecutor(20)
for hostname in hostname_list:
pool.submit(... | the_stack_v2_python_sparse | CMDB_V2/auto_client/src/engine/base.py | 214031230/Python21 | train | 0 | |
947a0a97259aabeda52ab8c6a063dc50170d1c02 | [
"gym.Wrapper.__init__(self, env)\nself.noop_max = noop_max\nself.override_num_noops = None\nif isinstance(env.action_space, gym.spaces.MultiBinary):\n self.noop_action = np.zeros(self.env.action_space.n, dtype=np.int64)\nelse:\n self.noop_action = 0\n assert env.unwrapped.get_action_meanings()[0] == 'NOOP'... | <|body_start_0|>
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
if isinstance(env.action_space, gym.spaces.MultiBinary):
self.noop_action = np.zeros(self.env.action_space.n, dtype=np.int64)
else:
self.noop_action = ... | NoopResetEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self, **kwargs):
"""Do no-op action for a number of steps in [1, noop_max]."""
<... | stack_v2_sparse_classes_36k_train_017475 | 5,252 | no_license | [
{
"docstring": "Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.",
"name": "__init__",
"signature": "def __init__(self, env, noop_max=30)"
},
{
"docstring": "Do no-op action for a number of steps in [1, noop_max].",
"name": "_reset",
"sig... | 2 | null | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self, **kwargs): Do ... | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self, **kwargs): Do ... | 7b394fa87523803b3f4536b316df76cc44f8846e | <|skeleton|>
class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self, **kwargs):
"""Do no-op action for a number of steps in [1, noop_max]."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
if isinstance(env.action_... | the_stack_v2_python_sparse | RL4/rl_mar2018_8_transfer_and_implicit/utils/envs.py | chriscremer/Other_Code | train | 7 | |
22fcc0cd69accb362d71f418cc4e41c05f9ee297 | [
"app_label = obj.category._meta.app_label\nmodel_name = obj.category._meta.model_name\nlink = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})\nreturn format_html(u'<a href=\"%s\">%s</a>' % (link, obj.category))",
"form = super().get_form(request, obj=None, change=Fal... | <|body_start_0|>
app_label = obj.category._meta.app_label
model_name = obj.category._meta.model_name
link = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})
return format_html(u'<a href="%s">%s</a>' % (link, obj.category))
<|end_body_0|>
<|b... | ArticleAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
<|body_0|>
def get_form(self, request, obj=None, change=False, **kwargs):
"""文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view."""
<|body_1|>
def get_q... | stack_v2_sparse_classes_36k_train_017476 | 10,733 | permissive | [
{
"docstring": "链接到文章所属分类, obj是一个文章对象",
"name": "category_link",
"signature": "def category_link(self, obj)"
},
{
"docstring": "文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view.",
"name": "get_form",
"signature": "def get_form(self, request, obj=None, chan... | 5 | stack_v2_sparse_classes_30k_val_000625 | Implement the Python class `ArticleAdmin` described below.
Class description:
Implement the ArticleAdmin class.
Method signatures and docstrings:
- def category_link(self, obj): 链接到文章所属分类, obj是一个文章对象
- def get_form(self, request, obj=None, change=False, **kwargs): 文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class fo... | Implement the Python class `ArticleAdmin` described below.
Class description:
Implement the ArticleAdmin class.
Method signatures and docstrings:
- def category_link(self, obj): 链接到文章所属分类, obj是一个文章对象
- def get_form(self, request, obj=None, change=False, **kwargs): 文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class fo... | 0fcf3709fabeee49874343b3a4ab80582698c466 | <|skeleton|>
class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
<|body_0|>
def get_form(self, request, obj=None, change=False, **kwargs):
"""文章详情页内选择作者, 只有超级管理员才会被filter出来 Return a Form class for use in the admin add view."""
<|body_1|>
def get_q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleAdmin:
def category_link(self, obj):
"""链接到文章所属分类, obj是一个文章对象"""
app_label = obj.category._meta.app_label
model_name = obj.category._meta.model_name
link = reverse('admin:%s_%s_change' % (app_label, model_name), kwargs={'object_id': obj.category_id})
return forma... | the_stack_v2_python_sparse | blog/admin.py | enjoy-binbin/Django-blog | train | 113 | |
5f6ccbb3eade070963786b511a82294022aa7900 | [
"for name, extension in extensions.items():\n if name not in self.unchained.extensions:\n if isinstance(extension, (list, tuple)):\n extension, dependencies = extension\n self.unchained.extensions[name] = extension",
"extensions = {}\nfor b in bundle._iter_class_hierarchy():\n for m... | <|body_start_0|>
for name, extension in extensions.items():
if name not in self.unchained.extensions:
if isinstance(extension, (list, tuple)):
extension, dependencies = extension
self.unchained.extensions[name] = extension
<|end_body_0|>
<|body_st... | Registers extensions found in bundles with the ``unchained`` extension. | RegisterExtensionsHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterExtensionsHook:
"""Registers extensions found in bundles with the ``unchained`` extension."""
def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None:
"""Discover extensions in bundles and register them with the Unchained extension."""
<|... | stack_v2_sparse_classes_36k_train_017477 | 1,568 | permissive | [
{
"docstring": "Discover extensions in bundles and register them with the Unchained extension.",
"name": "process_objects",
"signature": "def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None"
},
{
"docstring": "Collect declared extensions from a bundle hierarchy.... | 2 | stack_v2_sparse_classes_30k_train_020179 | Implement the Python class `RegisterExtensionsHook` described below.
Class description:
Registers extensions found in bundles with the ``unchained`` extension.
Method signatures and docstrings:
- def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None: Discover extensions in bundles and ... | Implement the Python class `RegisterExtensionsHook` described below.
Class description:
Registers extensions found in bundles with the ``unchained`` extension.
Method signatures and docstrings:
- def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None: Discover extensions in bundles and ... | a1f1323f63f59760e430001efef43af9b829ebed | <|skeleton|>
class RegisterExtensionsHook:
"""Registers extensions found in bundles with the ``unchained`` extension."""
def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None:
"""Discover extensions in bundles and register them with the Unchained extension."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterExtensionsHook:
"""Registers extensions found in bundles with the ``unchained`` extension."""
def process_objects(self, app: FlaskUnchained, extensions: Dict[str, object]) -> None:
"""Discover extensions in bundles and register them with the Unchained extension."""
for name, exten... | the_stack_v2_python_sparse | flask_unchained/hooks/register_extensions_hook.py | briancappello/flask-unchained | train | 77 |
dd0093c52fd3694d0bc828552f2e51775f773a70 | [
"data = self.cleaned_data['image_raw']\nif not data:\n return data\nmatch = BASE64_CONTENT_PATTERN.match(data)\nif not match:\n raise ValidationError(_('Not a valid image file.'))\ncontent_type = match.group('content_type')\ndata = b64decode(match.group('data'))\nfilename = uuid.uuid4()\nextension = IMAGE_TYP... | <|body_start_0|>
data = self.cleaned_data['image_raw']
if not data:
return data
match = BASE64_CONTENT_PATTERN.match(data)
if not match:
raise ValidationError(_('Not a valid image file.'))
content_type = match.group('content_type')
data = b64decode... | CreateForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateForm:
def clean_image_raw(self):
"""Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data, if present, is picked apart into its content type, decoded to the binary payload, its size measur... | stack_v2_sparse_classes_36k_train_017478 | 4,748 | no_license | [
{
"docstring": "Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data, if present, is picked apart into its content type, decoded to the binary payload, its size measured, and a simulated ``UploadedFile`` is generated ... | 2 | stack_v2_sparse_classes_30k_train_019309 | Implement the Python class `CreateForm` described below.
Class description:
Implement the CreateForm class.
Method signatures and docstrings:
- def clean_image_raw(self): Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data... | Implement the Python class `CreateForm` described below.
Class description:
Implement the CreateForm class.
Method signatures and docstrings:
- def clean_image_raw(self): Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data... | 9f1ddcfc4ae765402ed2a1c939b94f0f1d870560 | <|skeleton|>
class CreateForm:
def clean_image_raw(self):
"""Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data, if present, is picked apart into its content type, decoded to the binary payload, its size measur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateForm:
def clean_image_raw(self):
"""Some trickery to make the fake file field pass through the normal machinery without having been sent via ``request.FILES``. The base64-encoded data, if present, is picked apart into its content type, decoded to the binary payload, its size measured, and a simu... | the_stack_v2_python_sparse | wtds/wallpapers/forms.py | tiliv/wtds | train | 1 | |
2a1c52730009a26b5e2ad9951b855613d0a71494 | [
"if self.request.is_ajax():\n return JsonResponse({'error': form.errors}, status=400)\nelse:\n return JsonResponse({'error': 'Invalid form and request'}, status=400)",
"if self.request.is_ajax():\n notice = Notice.objects.get(pk=self.kwargs['pk'])\n form.instance.notice = notice\n form.instance.use... | <|body_start_0|>
if self.request.is_ajax():
return JsonResponse({'error': form.errors}, status=400)
else:
return JsonResponse({'error': 'Invalid form and request'}, status=400)
<|end_body_0|>
<|body_start_1|>
if self.request.is_ajax():
notice = Notice.objects... | Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class. | CreateComment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateComment:
"""Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class."""
def form_invalid(self, form):
"""Handles comment form invalid nArgs: * Arg1: Self - the current instance of the class * Arg2: the comment form Returns: * ... | stack_v2_sparse_classes_36k_train_017479 | 16,067 | no_license | [
{
"docstring": "Handles comment form invalid nArgs: * Arg1: Self - the current instance of the class * Arg2: the comment form Returns: * Json response of the error",
"name": "form_invalid",
"signature": "def form_invalid(self, form)"
},
{
"docstring": "Handles comment form valid * Sets the comme... | 2 | stack_v2_sparse_classes_30k_test_000003 | Implement the Python class `CreateComment` described below.
Class description:
Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class.
Method signatures and docstrings:
- def form_invalid(self, form): Handles comment form invalid nArgs: * Arg1: Self - the current i... | Implement the Python class `CreateComment` described below.
Class description:
Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class.
Method signatures and docstrings:
- def form_invalid(self, form): Handles comment form invalid nArgs: * Arg1: Self - the current i... | dc7ff47249809f377fbccbb40667b83011930b7b | <|skeleton|>
class CreateComment:
"""Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class."""
def form_invalid(self, form):
"""Handles comment form invalid nArgs: * Arg1: Self - the current instance of the class * Arg2: the comment form Returns: * ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateComment:
"""Handles creating a comment Args: * Arg1: The LoginRequiredMixin * Arg2: Inherits the Generic FormView class."""
def form_invalid(self, form):
"""Handles comment form invalid nArgs: * Arg1: Self - the current instance of the class * Arg2: the comment form Returns: * Json response... | the_stack_v2_python_sparse | notices/views.py | alychinque/eHand | train | 0 |
8865dfe158b150b0a67e9939b9d6180d4c4a3997 | [
"self.epsilon = float(self.parameters['epsilon_mbb'])\nself.T = float(self.parameters['t_mbb'])\nself.beta = float(self.parameters['beta_mbb'])\nself.energy_balance = bool(self.parameters['energy_balance'])\nif self.epsilon < 0.0:\n raise Exception('Error, epsilon_mbb must be ≥ 0.')\nc = cst.c * 1000000000.0\nla... | <|body_start_0|>
self.epsilon = float(self.parameters['epsilon_mbb'])
self.T = float(self.parameters['t_mbb'])
self.beta = float(self.parameters['beta_mbb'])
self.energy_balance = bool(self.parameters['energy_balance'])
if self.epsilon < 0.0:
raise Exception('Error, e... | One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep the energy balance or not.. | MBB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBB:
"""One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep the energy balance or not.."""
def _... | stack_v2_sparse_classes_36k_train_017480 | 4,961 | no_license | [
{
"docstring": "Build the model for a given set of parameters.",
"name": "_init_code",
"signature": "def _init_code(self)"
},
{
"docstring": "Add the IR re-emission contributions. Parameters ---------- sed: pcigale.sed.SED object",
"name": "process",
"signature": "def process(self, sed)"... | 2 | stack_v2_sparse_classes_30k_train_000377 | Implement the Python class `MBB` described below.
Class description:
One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep th... | Implement the Python class `MBB` described below.
Class description:
One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep th... | 9ef9b99425537350b8706fddfe90ed47301107a5 | <|skeleton|>
class MBB:
"""One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep the energy balance or not.."""
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBB:
"""One modified black body IR re-emission Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises MBB plus any previous IR contribution to this amount of energy. The final SED allows to keep the energy balance or not.."""
def _init_code(sel... | the_stack_v2_python_sparse | pcigale/sed_modules/mbb.py | JohannesBuchner/cigale | train | 5 |
2c2a77a4c2aa7086290aa538d60fbbb9e99e9b0d | [
"self.bigSpots = big\nself.mediumSpots = medium\nself.smallSpots = small\nself.bigCurrent = 0\nself.mediumCurrent = 0\nself.smallCurrent = 0",
"if carType == 1:\n if self.bigCurrent < self.bigSpots:\n self.bigCurrent += 1\n return True\n return False\nelif carType == 2:\n if self.mediumCurr... | <|body_start_0|>
self.bigSpots = big
self.mediumSpots = medium
self.smallSpots = small
self.bigCurrent = 0
self.mediumCurrent = 0
self.smallCurrent = 0
<|end_body_0|>
<|body_start_1|>
if carType == 1:
if self.bigCurrent < self.bigSpots:
... | ParkingSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.bigSpots = b... | stack_v2_sparse_classes_36k_train_017481 | 1,329 | no_license | [
{
"docstring": ":type big: int :type medium: int :type small: int",
"name": "__init__",
"signature": "def __init__(self, big, medium, small)"
},
{
"docstring": ":type carType: int :rtype: bool",
"name": "addCar",
"signature": "def addCar(self, carType)"
}
] | 2 | null | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool
<|skeleton|>
cla... | d40c24736a6fee43b56aa1c80150c5f14be4ff22 | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
self.bigSpots = big
self.mediumSpots = medium
self.smallSpots = small
self.bigCurrent = 0
self.mediumCurrent = 0
self.smallCurrent = 0
def... | the_stack_v2_python_sparse | GeneralPractice/1603. Design Parking System.py | deepika087/CompetitiveProgramming | train | 10 | |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"super(forms.ModelForm, self).__init__(*args, **kwargs)\nself.helper = FormHelper()\nself.helper.form_tag = False\nself.helper.form_show_errors = True\n\"\\n Create a default 'layout' for this form.\\n Ref: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html\\n This is required to... | <|body_start_0|>
super(forms.ModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_show_errors = True
"\n Create a default 'layout' for this form.\n Ref: https://django-crispy-forms.readthedocs.io/en/late... | Provides simple integration of crispy_forms extension. | HelperForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelperForm:
"""Provides simple integration of crispy_forms extension."""
def __init__(self, *args, **kwargs):
"""Setup layout."""
<|body_0|>
def rebuild_layout(self):
"""Build crispy layout out of current fields."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_017482 | 12,546 | permissive | [
{
"docstring": "Setup layout.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Build crispy layout out of current fields.",
"name": "rebuild_layout",
"signature": "def rebuild_layout(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001136 | Implement the Python class `HelperForm` described below.
Class description:
Provides simple integration of crispy_forms extension.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Setup layout.
- def rebuild_layout(self): Build crispy layout out of current fields. | Implement the Python class `HelperForm` described below.
Class description:
Provides simple integration of crispy_forms extension.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Setup layout.
- def rebuild_layout(self): Build crispy layout out of current fields.
<|skeleton|>
class HelperFor... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class HelperForm:
"""Provides simple integration of crispy_forms extension."""
def __init__(self, *args, **kwargs):
"""Setup layout."""
<|body_0|>
def rebuild_layout(self):
"""Build crispy layout out of current fields."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelperForm:
"""Provides simple integration of crispy_forms extension."""
def __init__(self, *args, **kwargs):
"""Setup layout."""
super(forms.ModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_show_er... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
416ae4d2524997a7965cb59f11d03659ee016ba3 | [
"dict = Counter(nums)\nfor val in dict:\n if dict[val] == 1:\n return val",
"elements = set(nums)\nele = (sum(elements) * 3 - sum(nums)) // 2\nreturn ele",
"low = high = 0\nfor val in nums:\n low = (low ^ val) & ~high\n high = (high ^ val) & ~low\nreturn low"
] | <|body_start_0|>
dict = Counter(nums)
for val in dict:
if dict[val] == 1:
return val
<|end_body_0|>
<|body_start_1|>
elements = set(nums)
ele = (sum(elements) * 3 - sum(nums)) // 2
return ele
<|end_body_1|>
<|body_start_2|>
low = high = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_017483 | 1,101 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
},
{
"docstring": ":type nums: List... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
dict = Counter(nums)
for val in dict:
if dict[val] == 1:
return val
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
elements = set(num... | the_stack_v2_python_sparse | 137. Single Number II/sinNum.py | Macielyoung/LeetCode | train | 1 | |
ea1ca9c5ee5dc238b00842769e78908cdde99227 | [
"if typedef is None:\n typedef = {}\nreturn {k: encode_type(v, typedef=typedef.get(k, None)) for k, v in instance.items()}",
"for k in prop2.keys():\n if k not in prop1:\n yield (\"Missing property '%s'\" % k)\n continue\n for e in compare_schema(prop1[k], prop2[k], root1=root1, root2=root2... | <|body_start_0|>
if typedef is None:
typedef = {}
return {k: encode_type(v, typedef=typedef.get(k, None)) for k, v in instance.items()}
<|end_body_0|>
<|body_start_1|>
for k in prop2.keys():
if k not in prop1:
yield ("Missing property '%s'" % k)
... | Property class for 'properties' property. | PropertiesMetaschemaProperty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertiesMetaschemaProperty:
"""Property class for 'properties' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'properties' container property."""
<|body_0|>
def compare(cls, prop1, prop2, root1=None, root2=None):
"""Comparison method f... | stack_v2_sparse_classes_36k_train_017484 | 1,962 | permissive | [
{
"docstring": "Encoder for the 'properties' container property.",
"name": "encode",
"signature": "def encode(cls, instance, typedef=None)"
},
{
"docstring": "Comparison method for 'properties' container property.",
"name": "compare",
"signature": "def compare(cls, prop1, prop2, root1=No... | 4 | stack_v2_sparse_classes_30k_train_009054 | Implement the Python class `PropertiesMetaschemaProperty` described below.
Class description:
Property class for 'properties' property.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Encoder for the 'properties' container property.
- def compare(cls, prop1, prop2, root1=None, root2=None)... | Implement the Python class `PropertiesMetaschemaProperty` described below.
Class description:
Property class for 'properties' property.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Encoder for the 'properties' container property.
- def compare(cls, prop1, prop2, root1=None, root2=None)... | dcc4d75a4d2c6aaa7e50e75095a16df1df6b2b0a | <|skeleton|>
class PropertiesMetaschemaProperty:
"""Property class for 'properties' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'properties' container property."""
<|body_0|>
def compare(cls, prop1, prop2, root1=None, root2=None):
"""Comparison method f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertiesMetaschemaProperty:
"""Property class for 'properties' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'properties' container property."""
if typedef is None:
typedef = {}
return {k: encode_type(v, typedef=typedef.get(k, None)) for k,... | the_stack_v2_python_sparse | yggdrasil/metaschema/properties/JSONObjectMetaschemaProperties.py | leighmatth/yggdrasil | train | 0 |
6d866b3e938649b60506f5ae99fdec08dfcd43eb | [
"yPred0 = self.unsqueeze(yPred0, dim=1)\nlogp0 = self.unsqueeze(logp0, dim=1)\nyTarget0 = self.unsqueeze(yTarget0, dim=1)\nif self.yPred is None or self.yTarget is None:\n self.yPred = yPred0\n self.logp = logp0\n self.yTarget = yTarget0\nelse:\n self.yPred = self.concat(self.yPred, yPred0)\n self.lo... | <|body_start_0|>
yPred0 = self.unsqueeze(yPred0, dim=1)
logp0 = self.unsqueeze(logp0, dim=1)
yTarget0 = self.unsqueeze(yTarget0, dim=1)
if self.yPred is None or self.yTarget is None:
self.yPred = yPred0
self.logp = logp0
self.yTarget = yTarget0
... | Class used to store model predictions overtime | TMGLowPredictionItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TMGLowPredictionItem:
"""Class used to store model predictions overtime"""
def add(self, yPred0, logp0, yTarget0):
"""Adds provided prediction and target tensors to class Time-steps are stored in dimension 1"""
<|body_0|>
def getOutputs(self):
"""Combines yPred a... | stack_v2_sparse_classes_36k_train_017485 | 16,017 | permissive | [
{
"docstring": "Adds provided prediction and target tensors to class Time-steps are stored in dimension 1",
"name": "add",
"signature": "def add(self, yPred0, logp0, yTarget0)"
},
{
"docstring": "Combines yPred and logp into a single tuple for loss evaluation",
"name": "getOutputs",
"sig... | 6 | stack_v2_sparse_classes_30k_train_005394 | Implement the Python class `TMGLowPredictionItem` described below.
Class description:
Class used to store model predictions overtime
Method signatures and docstrings:
- def add(self, yPred0, logp0, yTarget0): Adds provided prediction and target tensors to class Time-steps are stored in dimension 1
- def getOutputs(se... | Implement the Python class `TMGLowPredictionItem` described below.
Class description:
Class used to store model predictions overtime
Method signatures and docstrings:
- def add(self, yPred0, logp0, yTarget0): Adds provided prediction and target tensors to class Time-steps are stored in dimension 1
- def getOutputs(se... | 0daca5daada449d4ba16bce37b703e20b444b6bc | <|skeleton|>
class TMGLowPredictionItem:
"""Class used to store model predictions overtime"""
def add(self, yPred0, logp0, yTarget0):
"""Adds provided prediction and target tensors to class Time-steps are stored in dimension 1"""
<|body_0|>
def getOutputs(self):
"""Combines yPred a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TMGLowPredictionItem:
"""Class used to store model predictions overtime"""
def add(self, yPred0, logp0, yTarget0):
"""Adds provided prediction and target tensors to class Time-steps are stored in dimension 1"""
yPred0 = self.unsqueeze(yPred0, dim=1)
logp0 = self.unsqueeze(logp0, d... | the_stack_v2_python_sparse | tmglow/nn/trainFlowParallel.py | maximilian-tech/deep-turbulence | train | 0 |
4f50a6e5591c36627d8fc55b865cfd1d62d6f1f9 | [
"self._path = path\nself._parser = example_parser.ExampleParser(example_specs)\nself._file_format = file_format",
"splits_dict = splits_lib.SplitDict(split_infos=split_infos)\n\ndef _read_instruction_to_ds(instruction):\n file_instructions = splits_dict[instruction].file_instructions\n return self.read_file... | <|body_start_0|>
self._path = path
self._parser = example_parser.ExampleParser(example_specs)
self._file_format = file_format
<|end_body_0|>
<|body_start_1|>
splits_dict = splits_lib.SplitDict(split_infos=split_infos)
def _read_instruction_to_ds(instruction):
file_i... | Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user. | Reader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reader:
"""Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user."""
def __init__(self, path, example_specs, file_format=file_adapters.DEFAULT_FILE_FORMAT):
"""Initializes Reader. Args: path (str): path where tfreco... | stack_v2_sparse_classes_36k_train_017486 | 16,929 | permissive | [
{
"docstring": "Initializes Reader. Args: path (str): path where tfrecords are stored. example_specs: spec to build ExampleParser. file_format: file_adapters.FileFormat, format of the record files in which the dataset will be read/written from.",
"name": "__init__",
"signature": "def __init__(self, path... | 3 | stack_v2_sparse_classes_30k_train_015102 | Implement the Python class `Reader` described below.
Class description:
Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user.
Method signatures and docstrings:
- def __init__(self, path, example_specs, file_format=file_adapters.DEFAULT_FILE_FORMAT)... | Implement the Python class `Reader` described below.
Class description:
Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user.
Method signatures and docstrings:
- def __init__(self, path, example_specs, file_format=file_adapters.DEFAULT_FILE_FORMAT)... | 41ae3cf1439711ed2f50f99caa0e6702082e6d37 | <|skeleton|>
class Reader:
"""Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user."""
def __init__(self, path, example_specs, file_format=file_adapters.DEFAULT_FILE_FORMAT):
"""Initializes Reader. Args: path (str): path where tfreco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reader:
"""Build a tf.data.Dataset object out of Instruction instance(s). This class should not typically be exposed to the TFDS user."""
def __init__(self, path, example_specs, file_format=file_adapters.DEFAULT_FILE_FORMAT):
"""Initializes Reader. Args: path (str): path where tfrecords are store... | the_stack_v2_python_sparse | tensorflow_datasets/core/reader.py | tensorflow/datasets | train | 4,224 |
4cdcd2254e219ca22f778cf162069424188aa01a | [
"super().__init__()\nself.in_dim = in_dim\nself.out_dim = out_dim\nself.non_linearity = non_linearity\nself.hidden_dims = hidden_dims\nself.self_att = self_att\nself.network = VanillaNN(in_dim, out_dim, hidden_dims, non_linearity=self.non_linearity)\nif self.self_att:\n print('Using multihead self attention.')\n... | <|body_start_0|>
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.non_linearity = non_linearity
self.hidden_dims = hidden_dims
self.self_att = self_att
self.network = VanillaNN(in_dim, out_dim, hidden_dims, non_linearity=self.non_linearity)
... | SelfAttentiveVanillaNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttentiveVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, self_att=True):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param n... | stack_v2_sparse_classes_36k_train_017487 | 16,175 | no_license | [
{
"docstring": ":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linearity: Non-linear activation function to apply after each linear transformation, e.g. relu or tanh.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_021064 | Implement the Python class `SelfAttentiveVanillaNN` described below.
Class description:
Implement the SelfAttentiveVanillaNN class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, self_att=True): :param in_dim: (int) Dimensionality of the input. :param out_di... | Implement the Python class `SelfAttentiveVanillaNN` described below.
Class description:
Implement the SelfAttentiveVanillaNN class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, self_att=True): :param in_dim: (int) Dimensionality of the input. :param out_di... | de60f831ee082ab2ae232c498cf2755da7c14c27 | <|skeleton|>
class SelfAttentiveVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, self_att=True):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttentiveVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, self_att=True):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linearity: ... | the_stack_v2_python_sparse | models/networks/np_networks.py | PenelopeJones/neural_processes | train | 4 | |
4dac33b2d008d235362c4a7055977c2ecf27fc2f | [
"study_id = root._get_study_id(info)\ninvited_by = Membership.objects.get(collaborator=root.node.id, study=study_id).invited_by\nreturn invited_by",
"study_id = root._get_study_id(info)\njoined_on = Membership.objects.get(collaborator=root.node.id, study=study_id).joined_on\nreturn joined_on",
"study_id = root.... | <|body_start_0|>
study_id = root._get_study_id(info)
invited_by = Membership.objects.get(collaborator=root.node.id, study=study_id).invited_by
return invited_by
<|end_body_0|>
<|body_start_1|>
study_id = root._get_study_id(info)
joined_on = Membership.objects.get(collaborator=ro... | Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table. | Edge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Edge:
"""Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table."""
def resolve_invited_by(root, info, **kwargs):
"""Returns the user that invited this collaborator to the study."""
<|body_0|>
def resolve_joined... | stack_v2_sparse_classes_36k_train_017488 | 5,435 | permissive | [
{
"docstring": "Returns the user that invited this collaborator to the study.",
"name": "resolve_invited_by",
"signature": "def resolve_invited_by(root, info, **kwargs)"
},
{
"docstring": "Returns the date the collaborator joined the study.",
"name": "resolve_joined_on",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_002626 | Implement the Python class `Edge` described below.
Class description:
Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table.
Method signatures and docstrings:
- def resolve_invited_by(root, info, **kwargs): Returns the user that invited this collaborator to... | Implement the Python class `Edge` described below.
Class description:
Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table.
Method signatures and docstrings:
- def resolve_invited_by(root, info, **kwargs): Returns the user that invited this collaborator to... | ba62b369e6464259ea92dbb9ba49876513f37fba | <|skeleton|>
class Edge:
"""Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table."""
def resolve_invited_by(root, info, **kwargs):
"""Returns the user that invited this collaborator to the study."""
<|body_0|>
def resolve_joined... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Edge:
"""Extends relay edges on study-collaborator relationships to include information from the 'Membership' through-table."""
def resolve_invited_by(root, info, **kwargs):
"""Returns the user that invited this collaborator to the study."""
study_id = root._get_study_id(info)
inv... | the_stack_v2_python_sparse | creator/users/schema.py | kids-first/kf-api-study-creator | train | 3 |
cf0c5e3ddaecb2f9fd25dcafc1c660631e65a42d | [
"if self.has_permission('RightTPI') is False:\n self.no_access()\nwith Database() as db:\n if id_survey is None:\n data = db.query(Table).all()\n else:\n data = db.query(Table).get(id_survey)\nreturn {'data': data}",
"if self.has_permission('RightTPI') is False:\n self.no_access()\nid_su... | <|body_start_0|>
if self.has_permission('RightTPI') is False:
self.no_access()
with Database() as db:
if id_survey is None:
data = db.query(Table).all()
else:
data = db.query(Table).get(id_survey)
return {'data': data}
<|end_bod... | Survey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Survey:
def get(self, id_survey=None):
"""Return the survey information :param id_survey: UUID"""
<|body_0|>
def create(self, body):
"""Create a new survey :param body: { name: JSON, survey_type: ENUM('test'), questions: JSON }"""
<|body_1|>
def modify(s... | stack_v2_sparse_classes_36k_train_017489 | 2,534 | no_license | [
{
"docstring": "Return the survey information :param id_survey: UUID",
"name": "get",
"signature": "def get(self, id_survey=None)"
},
{
"docstring": "Create a new survey :param body: { name: JSON, survey_type: ENUM('test'), questions: JSON }",
"name": "create",
"signature": "def create(s... | 4 | stack_v2_sparse_classes_30k_train_013832 | Implement the Python class `Survey` described below.
Class description:
Implement the Survey class.
Method signatures and docstrings:
- def get(self, id_survey=None): Return the survey information :param id_survey: UUID
- def create(self, body): Create a new survey :param body: { name: JSON, survey_type: ENUM('test')... | Implement the Python class `Survey` described below.
Class description:
Implement the Survey class.
Method signatures and docstrings:
- def get(self, id_survey=None): Return the survey information :param id_survey: UUID
- def create(self, body): Create a new survey :param body: { name: JSON, survey_type: ENUM('test')... | 43bd57c466a5cd3b133ddc437cb4a6b9f007d267 | <|skeleton|>
class Survey:
def get(self, id_survey=None):
"""Return the survey information :param id_survey: UUID"""
<|body_0|>
def create(self, body):
"""Create a new survey :param body: { name: JSON, survey_type: ENUM('test'), questions: JSON }"""
<|body_1|>
def modify(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Survey:
def get(self, id_survey=None):
"""Return the survey information :param id_survey: UUID"""
if self.has_permission('RightTPI') is False:
self.no_access()
with Database() as db:
if id_survey is None:
data = db.query(Table).all()
... | the_stack_v2_python_sparse | resturls/survey.py | CAUCA-9-1-1/survip-api | train | 1 | |
9f9d94431fb2479decd6f5d49cc561af7f1931d8 | [
"super().__init__(order=CallbackOrder.Optimizer, node=CallbackNode.All)\nself.loss_key: str = loss_key\nself.optimizer_key: str = optimizer_key\nself.accumulation_steps: int = accumulation_steps\nself._accumulation_counter: int = 0\ngrad_clip_params: dict = grad_clip_params or {}\nself.grad_clip_fn = registry.GRAD_... | <|body_start_0|>
super().__init__(order=CallbackOrder.Optimizer, node=CallbackNode.All)
self.loss_key: str = loss_key
self.optimizer_key: str = optimizer_key
self.accumulation_steps: int = accumulation_steps
self._accumulation_counter: int = 0
grad_clip_params: dict = gra... | Optimizer callback, abstraction over optimizer step. | OptimizerCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for grad... | stack_v2_sparse_classes_36k_train_017490 | 5,598 | permissive | [
{
"docstring": "Args: grad_clip_params (dict): params for gradient clipping accumulation_steps (int): number of steps before ``model.zero_grad()`` optimizer_key (str): A key to take a optimizer in case there are several of them and they are in a dictionary format. loss_key (str): key to get loss from ``state.lo... | 6 | stack_v2_sparse_classes_30k_train_002340 | Implement the Python class `OptimizerCallback` described below.
Class description:
Optimizer callback, abstraction over optimizer step.
Method signatures and docstrings:
- def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: b... | Implement the Python class `OptimizerCallback` described below.
Class description:
Optimizer callback, abstraction over optimizer step.
Method signatures and docstrings:
- def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: b... | 75ffa808e2bbb9071a169a1a9c813deb6a69a797 | <|skeleton|>
class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for grad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for gradient clipping... | the_stack_v2_python_sparse | catalyst_rl/core/callbacks/optimizer.py | catalyst-team/catalyst-rl | train | 50 |
166f1110ae1960c9a1910891171dde528767ece6 | [
"params = self.get_set_params(locals())\nresponse = await self.api.request('donut.getFriends', params)\nmodel = donut.GetFriendsResponse\nreturn model(**response).response",
"params = self.get_set_params(locals())\nresponse = await self.api.request('donut.getSubscription', params)\nmodel = donut.GetSubscriptionRe... | <|body_start_0|>
params = self.get_set_params(locals())
response = await self.api.request('donut.getFriends', params)
model = donut.GetFriendsResponse
return model(**response).response
<|end_body_0|>
<|body_start_1|>
params = self.get_set_params(locals())
response = awai... | DonutCategory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
... | stack_v2_sparse_classes_36k_train_017491 | 1,897 | permissive | [
{
"docstring": "donut.getFriends method :param owner_id: :param offset: :param count: :param fields:",
"name": "get_friends",
"signature": "async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRes... | 4 | stack_v2_sparse_classes_30k_train_014494 | Implement the Python class `DonutCategory` described below.
Class description:
Implement the DonutCategory class.
Method signatures and docstrings:
- async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRespons... | Implement the Python class `DonutCategory` described below.
Class description:
Implement the DonutCategory class.
Method signatures and docstrings:
- async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsRespons... | dfcedd4023aa170dd7f802ac662f0e2ed9033904 | <|skeleton|>
class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DonutCategory:
async def get_friends(self, owner_id: int, offset: Optional[int]=None, count: Optional[int]=None, fields: Optional[List[str]]=None, **kwargs) -> donut.GetFriendsResponseModel:
"""donut.getFriends method :param owner_id: :param offset: :param count: :param fields:"""
params = sel... | the_stack_v2_python_sparse | codegen/results/methods/donut.py | ScriptHound/vkbottle-types | train | 0 | |
6fdcdc1ff81c0c895250a396ba3aa74a5059abae | [
"self.name = name\nself.ip = ip\nself.mac = mac",
"if dictionary is None:\n return None\nip = dictionary.get('ip')\nmac = dictionary.get('mac')\nname = dictionary.get('name')\nreturn cls(ip, mac, name)"
] | <|body_start_0|>
self.name = name
self.ip = ip
self.mac = mac
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
ip = dictionary.get('ip')
mac = dictionary.get('mac')
name = dictionary.get('name')
return cls(ip, mac, name)
<|en... | Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (string): The MAC address of the server or device that hosts the internal resource that yo... | FixedIpAssignmentModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedIpAssignmentModel:
"""Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (string): The MAC address of the server ... | stack_v2_sparse_classes_36k_train_017492 | 1,946 | permissive | [
{
"docstring": "Constructor for the FixedIpAssignmentModel class",
"name": "__init__",
"signature": "def __init__(self, ip=None, mac=None, name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object a... | 2 | stack_v2_sparse_classes_30k_train_018094 | Implement the Python class `FixedIpAssignmentModel` described below.
Class description:
Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (... | Implement the Python class `FixedIpAssignmentModel` described below.
Class description:
Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class FixedIpAssignmentModel:
"""Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (string): The MAC address of the server ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixedIpAssignmentModel:
"""Implementation of the 'FixedIpAssignment' model. TODO: type model description here. Attributes: name (string): A descriptive name of the assignment ip (string): The IP address you want to assign to a specific server or device mac (string): The MAC address of the server or device tha... | the_stack_v2_python_sparse | meraki_sdk/models/fixed_ip_assignment_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
f1b9ffd0783dc24d6f107a342142a255d5d6ab9e | [
"super(GRU, self).__init__()\nself.dict_size = conf_dict['dict_size']\nself.task_mode = conf_dict['task_mode']\nself.emb_dim = conf_dict['net']['emb_dim']\nself.gru_dim = conf_dict['net']['gru_dim']\nself.hidden_dim = conf_dict['net']['hidden_dim']\nself.emb_layer = layers.EmbeddingLayer(self.dict_size, self.emb_di... | <|body_start_0|>
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
self.hidden_dim = conf_dict['net']['hidden_dim']
self... | GRU | GRU | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_siz... | stack_v2_sparse_classes_36k_train_017493 | 3,335 | permissive | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self, conf_dict)"
},
{
"docstring": "Forward network",
"name": "forward",
"signature": "def forward(self, left, right)"
}
] | 2 | null | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network | Implement the Python class `GRU` described below.
Class description:
GRU
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network
<|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRU:
"""GRU"""
def __init__(self, conf_dict):
"""initialize"""
super(GRU, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.gru_dim = conf_dict['net']['gru_dim']
... | the_stack_v2_python_sparse | dygraph/similarity_net/nets/gru.py | littletomatodonkey/models | train | 5 |
9fc93bd8a4c0ed787fa04015cc811f9e2df2d878 | [
"context = self.context\nresult = {}\nresult['id'] = context.getId()\nresult['title'] = context.Title()\nresult['description'] = context.Description()\nreturn result",
"data = self.collect_data()\nbody = term_template.format(**data)\nif core:\n return body\nfull = header + body + footer\nfull = full.replace('&... | <|body_start_0|>
context = self.context
result = {}
result['id'] = context.getId()
result['title'] = context.Title()
result['description'] = context.Description()
return result
<|end_body_0|>
<|body_start_1|>
data = self.collect_data()
body = term_templat... | Render a simple vocabulary term info like GOCDB does. This is needed for teh service types. | TermView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TermView:
"""Render a simple vocabulary term info like GOCDB does. This is needed for teh service types."""
def collect_data(self):
"""Helper to collect the values to be rendered as XML"""
<|body_0|>
def xml(self, core=False, indent=2):
"""Render as XML compatibl... | stack_v2_sparse_classes_36k_train_017494 | 16,639 | no_license | [
{
"docstring": "Helper to collect the values to be rendered as XML",
"name": "collect_data",
"signature": "def collect_data(self)"
},
{
"docstring": "Render as XML compatible with GOCDB",
"name": "xml",
"signature": "def xml(self, core=False, indent=2)"
}
] | 2 | null | Implement the Python class `TermView` described below.
Class description:
Render a simple vocabulary term info like GOCDB does. This is needed for teh service types.
Method signatures and docstrings:
- def collect_data(self): Helper to collect the values to be rendered as XML
- def xml(self, core=False, indent=2): Re... | Implement the Python class `TermView` described below.
Class description:
Render a simple vocabulary term info like GOCDB does. This is needed for teh service types.
Method signatures and docstrings:
- def collect_data(self): Helper to collect the values to be rendered as XML
- def xml(self, core=False, indent=2): Re... | 6d7656dfd1687df055f7f8cedb2e7fad92468988 | <|skeleton|>
class TermView:
"""Render a simple vocabulary term info like GOCDB does. This is needed for teh service types."""
def collect_data(self):
"""Helper to collect the values to be rendered as XML"""
<|body_0|>
def xml(self, core=False, indent=2):
"""Render as XML compatibl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TermView:
"""Render a simple vocabulary term info like GOCDB does. This is needed for teh service types."""
def collect_data(self):
"""Helper to collect the values to be rendered as XML"""
context = self.context
result = {}
result['id'] = context.getId()
result['ti... | the_stack_v2_python_sparse | src/pcp/contenttypes/browser/gocdb_views.py | EUDAT-DPMT/pcp.contenttypes | train | 1 |
6020c3f6d71c7685417a2b3493419b6c3a5f7197 | [
"left, right = (0, len(nums) - 1)\nwhile right > left:\n if nums[right] > nums[left]:\n return nums[left]\n else:\n mid = (right + left) // 2\n if nums[mid] >= nums[left]:\n left = mid + 1\n else:\n right = mid\nreturn nums[left]",
"left, right = (0, len(num... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while right > left:
if nums[right] > nums[left]:
return nums[left]
else:
mid = (right + left) // 2
if nums[mid] >= nums[left]:
left = mid + 1
else... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
<|body_0|>
def findMin1(self, nums):
"""may have duplicates :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, l... | stack_v2_sparse_classes_36k_train_017495 | 1,244 | no_license | [
{
"docstring": "no duplicate :type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": "may have duplicates :type nums: List[int] :rtype: int",
"name": "findMin1",
"signature": "def findMin1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007225 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): no duplicate :type nums: List[int] :rtype: int
- def findMin1(self, nums): may have duplicates :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): no duplicate :type nums: List[int] :rtype: int
- def findMin1(self, nums): may have duplicates :type nums: List[int] :rtype: int
<|skeleton|>
class Solu... | c9fb0b623501b3746444b05da55405e3a6c42bbf | <|skeleton|>
class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
<|body_0|>
def findMin1(self, nums):
"""may have duplicates :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums):
"""no duplicate :type nums: List[int] :rtype: int"""
left, right = (0, len(nums) - 1)
while right > left:
if nums[right] > nums[left]:
return nums[left]
else:
mid = (right + left) // 2
... | the_stack_v2_python_sparse | Archive-1/FindMinimuminRotatedSortedArray.py | smsxgz/my-leetcode | train | 0 | |
a20d519881ca401ca644c2ceb93c5ce58635cbb8 | [
"for article in self.articles['all']:\n if self.mock_tornado():\n headers = {'ETag': article['response']['etag']}\n self.mocked_response.headers.__getitem__.side_effect = lambda _: headers[_]\n type(self.mocked_response).buffer = mock.PropertyMock(return_value=article['response']['html'])\n ... | <|body_start_0|>
for article in self.articles['all']:
if self.mock_tornado():
headers = {'ETag': article['response']['etag']}
self.mocked_response.headers.__getitem__.side_effect = lambda _: headers[_]
type(self.mocked_response).buffer = mock.PropertyM... | SpreadArticleSanitizeWithDatastoreTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpreadArticleSanitizeWithDatastoreTest:
def test_article_sanitize_unsanitized(self):
"""spread.articles—sanitize—unmocked datastores,unsanitized"""
<|body_0|>
def test_article_sanitize_sanitized_unmodified(self):
"""spread.articles—sanitize—unmocked datastores,saniti... | stack_v2_sparse_classes_36k_train_017496 | 8,186 | no_license | [
{
"docstring": "spread.articles—sanitize—unmocked datastores,unsanitized",
"name": "test_article_sanitize_unsanitized",
"signature": "def test_article_sanitize_unsanitized(self)"
},
{
"docstring": "spread.articles—sanitize—unmocked datastores,sanitized,unmodified",
"name": "test_article_sani... | 3 | stack_v2_sparse_classes_30k_val_001153 | Implement the Python class `SpreadArticleSanitizeWithDatastoreTest` described below.
Class description:
Implement the SpreadArticleSanitizeWithDatastoreTest class.
Method signatures and docstrings:
- def test_article_sanitize_unsanitized(self): spread.articles—sanitize—unmocked datastores,unsanitized
- def test_artic... | Implement the Python class `SpreadArticleSanitizeWithDatastoreTest` described below.
Class description:
Implement the SpreadArticleSanitizeWithDatastoreTest class.
Method signatures and docstrings:
- def test_article_sanitize_unsanitized(self): spread.articles—sanitize—unmocked datastores,unsanitized
- def test_artic... | a1eaa4d46824222dbab840df06bce2302e8407e7 | <|skeleton|>
class SpreadArticleSanitizeWithDatastoreTest:
def test_article_sanitize_unsanitized(self):
"""spread.articles—sanitize—unmocked datastores,unsanitized"""
<|body_0|>
def test_article_sanitize_sanitized_unmodified(self):
"""spread.articles—sanitize—unmocked datastores,saniti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpreadArticleSanitizeWithDatastoreTest:
def test_article_sanitize_unsanitized(self):
"""spread.articles—sanitize—unmocked datastores,unsanitized"""
for article in self.articles['all']:
if self.mock_tornado():
headers = {'ETag': article['response']['etag']}
... | the_stack_v2_python_sparse | test_margarine/test_integration/test_spread/test_articles.py | alunduil/margarine | train | 3 | |
bab3069e705106e8eca4dbd4c1513e0df2bc4626 | [
"sum1, sum2 = (0, 0)\nwhile l1:\n sum1 = sum1 * 10 + l1.val\n l1 = l1.next\nwhile l2:\n sum2 = sum2 * 10 + l2.val\n l2 = l2.next\nsum_all = sum1 + sum2\nhead = ListNode(0)\nif sum_all == 0:\n return head\nwhile sum_all:\n v, sum_all = (sum_all % 10, sum_all // 10)\n head.next, head.next.next = ... | <|body_start_0|>
sum1, sum2 = (0, 0)
while l1:
sum1 = sum1 * 10 + l1.val
l1 = l1.next
while l2:
sum2 = sum2 * 10 + l2.val
l2 = l2.next
sum_all = sum1 + sum2
head = ListNode(0)
if sum_all == 0:
return head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
"""my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers_stack(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|bod... | stack_v2_sparse_classes_36k_train_017497 | 1,489 | no_license | [
{
"docstring": "my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers_stack",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers_stack(self, l1, l2): :type l1: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers_stack(self, l1, l2): :type l1: ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
"""my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers_stack(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers(self, l1, l2):
"""my method time O(max(m, n)) space O(1) :type l1: ListNode :type l2: ListNode :rtype: ListNode"""
sum1, sum2 = (0, 0)
while l1:
sum1 = sum1 * 10 + l1.val
l1 = l1.next
while l2:
sum2 = sum2 * 10 + l... | the_stack_v2_python_sparse | LeetCode/LinkedList/445_add_two_numbers_ii.py | XyK0907/for_work | train | 0 | |
73a5bb9645ca677accd0f9c1e35d6285e5fd534f | [
"super().__init__()\nif layer_sizes is None:\n layer_sizes = [1200, 600, 220]\nself._layer_sizes = layer_sizes\nself._num_shared_layers = shared_layers\nassert 0 < shared_layers <= len(self._layer_sizes)\nself._polynomial = polynomial\nself._input_size = None\nself._belief_size = None\nself._num_players = None\n... | <|body_start_0|>
super().__init__()
if layer_sizes is None:
layer_sizes = [1200, 600, 220]
self._layer_sizes = layer_sizes
self._num_shared_layers = shared_layers
assert 0 < shared_layers <= len(self._layer_sizes)
self._polynomial = polynomial
self._in... | Multilayered perceptron to approximate T: (b, a) -> b' | MultitaskTransitionModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultitaskTransitionModel:
"""Multilayered perceptron to approximate T: (b, a) -> b'"""
def __init__(self, layer_sizes: List[int]=None, shared_layers: int=2, polynomial: bool=True):
""":param layer_sizes: sizes of the hidden layers in the network (there will be len(layer_sizes) + 1 Li... | stack_v2_sparse_classes_36k_train_017498 | 13,214 | permissive | [
{
"docstring": ":param layer_sizes: sizes of the hidden layers in the network (there will be len(layer_sizes) + 1 Linear layers) :param shared_layers: number of layers to maintain as a shared backbone :param polynomial: whether or not to use the polynomial basis",
"name": "__init__",
"signature": "def _... | 6 | stack_v2_sparse_classes_30k_train_019491 | Implement the Python class `MultitaskTransitionModel` described below.
Class description:
Multilayered perceptron to approximate T: (b, a) -> b'
Method signatures and docstrings:
- def __init__(self, layer_sizes: List[int]=None, shared_layers: int=2, polynomial: bool=True): :param layer_sizes: sizes of the hidden lay... | Implement the Python class `MultitaskTransitionModel` described below.
Class description:
Multilayered perceptron to approximate T: (b, a) -> b'
Method signatures and docstrings:
- def __init__(self, layer_sizes: List[int]=None, shared_layers: int=2, polynomial: bool=True): :param layer_sizes: sizes of the hidden lay... | ae32e85583c61cc27a44946a6b5fa7c1e2c152ff | <|skeleton|>
class MultitaskTransitionModel:
"""Multilayered perceptron to approximate T: (b, a) -> b'"""
def __init__(self, layer_sizes: List[int]=None, shared_layers: int=2, polynomial: bool=True):
""":param layer_sizes: sizes of the hidden layers in the network (there will be len(layer_sizes) + 1 Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultitaskTransitionModel:
"""Multilayered perceptron to approximate T: (b, a) -> b'"""
def __init__(self, layer_sizes: List[int]=None, shared_layers: int=2, polynomial: bool=True):
""":param layer_sizes: sizes of the hidden layers in the network (there will be len(layer_sizes) + 1 Linear layers) ... | the_stack_v2_python_sparse | src/agents/models/multitask_models.py | lilianluong/multitask-card-games | train | 1 |
d08a973a22b40cced952ff5b908fba8ca3f29caf | [
"self.operating_system = os\nself.template = template\nself.installer_template = installer_template\nself.system_profile = system_profile\nself.installer_cmdline = installation_options.get('linux-kargs-installer')\nself.target_cmdline = installation_options.get('linux-kargs-target')\nself.ubuntu20_legacy_installer ... | <|body_start_0|>
self.operating_system = os
self.template = template
self.installer_template = installer_template
self.system_profile = system_profile
self.installer_cmdline = installation_options.get('linux-kargs-installer')
self.target_cmdline = installation_options.get... | Data model for autoinstall machine | AutoinstallMachineModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoinstallMachineModel:
"""Data model for autoinstall machine"""
def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]', custom_package_repos: 'list[PackageRepository]', system_profile: ... | stack_v2_sparse_classes_36k_train_017499 | 23,282 | permissive | [
{
"docstring": "Create model from controller data",
"name": "__init__",
"signature": "def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]', custom_package_repos: 'list[PackageRepository]', system_p... | 3 | stack_v2_sparse_classes_30k_train_018697 | Implement the Python class `AutoinstallMachineModel` described below.
Class description:
Data model for autoinstall machine
Method signatures and docstrings:
- def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]... | Implement the Python class `AutoinstallMachineModel` described below.
Class description:
Data model for autoinstall machine
Method signatures and docstrings:
- def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]... | 9c9040f6a173af5c495f5447889e9349fa56f234 | <|skeleton|>
class AutoinstallMachineModel:
"""Data model for autoinstall machine"""
def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]', custom_package_repos: 'list[PackageRepository]', system_profile: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoinstallMachineModel:
"""Data model for autoinstall machine"""
def __init__(self, os: OperatingSystem, os_repos: 'list[OsRepository]', template: Template, installer_template: Template, custom_os_repos: 'list[OsRepository]', custom_package_repos: 'list[PackageRepository]', system_profile: SystemProfile... | the_stack_v2_python_sparse | tessia/server/state_machines/autoinstall/model.py | tessia-project/tessia | train | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.