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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b3eed381cdf866eac3b3daa910cf0d901b2c66c | [
"with TemporaryFile(suffix='.py', dir='.', mode='x+') as file:\n file.write('\\n'.join(file_content))\n file_name = file.name\n file.seek(0)\n overwrite = 'Y'\n input_list = [file_name, lang_to, outfile_name, overwrite]\n io_stream = GetIO()\n with patch('builtins.input', side_effect=input_list... | <|body_start_0|>
with TemporaryFile(suffix='.py', dir='.', mode='x+') as file:
file.write('\n'.join(file_content))
file_name = file.name
file.seek(0)
overwrite = 'Y'
input_list = [file_name, lang_to, outfile_name, overwrite]
io_stream = Get... | TestOutfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOutfile:
def get_output(file_content, lang_to, outfile_name):
"""Returns PLC output for given input parameters"""
<|body_0|>
def test_python_1(self):
"""Test Case for file - test_exampes/python_1.py"""
<|body_1|>
def test_python_2(self):
"""T... | stack_v2_sparse_classes_36k_train_014400 | 6,697 | permissive | [
{
"docstring": "Returns PLC output for given input parameters",
"name": "get_output",
"signature": "def get_output(file_content, lang_to, outfile_name)"
},
{
"docstring": "Test Case for file - test_exampes/python_1.py",
"name": "test_python_1",
"signature": "def test_python_1(self)"
},... | 5 | stack_v2_sparse_classes_30k_train_009034 | Implement the Python class `TestOutfile` described below.
Class description:
Implement the TestOutfile class.
Method signatures and docstrings:
- def get_output(file_content, lang_to, outfile_name): Returns PLC output for given input parameters
- def test_python_1(self): Test Case for file - test_exampes/python_1.py
... | Implement the Python class `TestOutfile` described below.
Class description:
Implement the TestOutfile class.
Method signatures and docstrings:
- def get_output(file_content, lang_to, outfile_name): Returns PLC output for given input parameters
- def test_python_1(self): Test Case for file - test_exampes/python_1.py
... | f349659a7fcc980d31ddf58f38b35a4aae28561b | <|skeleton|>
class TestOutfile:
def get_output(file_content, lang_to, outfile_name):
"""Returns PLC output for given input parameters"""
<|body_0|>
def test_python_1(self):
"""Test Case for file - test_exampes/python_1.py"""
<|body_1|>
def test_python_2(self):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOutfile:
def get_output(file_content, lang_to, outfile_name):
"""Returns PLC output for given input parameters"""
with TemporaryFile(suffix='.py', dir='.', mode='x+') as file:
file.write('\n'.join(file_content))
file_name = file.name
file.seek(0)
... | the_stack_v2_python_sparse | test_outfile.py | Tejas-P-Herle/PLC | train | 3 | |
f17bc693587f8cf15c9c808117c8599155ca5f19 | [
"self.translation = translation\nif not isinstance(translation, tuple) or isinstance(translation, list):\n self.translation = (translation, translation)\nself.flow_keys = flow_keys\nself.occlusion_keys = occlusion_keys",
"_, _, h, w = inputs[self.flow_keys[0]].shape\nth, tw = self.translation\ntw = random.rand... | <|body_start_0|>
self.translation = translation
if not isinstance(translation, tuple) or isinstance(translation, list):
self.translation = (translation, translation)
self.flow_keys = flow_keys
self.occlusion_keys = occlusion_keys
<|end_body_0|>
<|body_start_1|>
_, _,... | Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cropped by a reversed translation -t. The third will be cropped by t again, and so on... | RandomTranslate | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomTranslate:
"""Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cropped by a reversed translation -t. The ... | stack_v2_sparse_classes_36k_train_014401 | 42,078 | permissive | [
{
"docstring": "Initialize RandomTranslate. Parameters ---------- translation : Union[int, Tuple[int, int]], default 0 Maximum translation (in pixels) to be applied to the inputs. If a tuple, it corresponds to the maximum in the (y, x) axes. flow_keys : Union[KeysView, Sequence[str]], default ['flows', 'flows_b... | 2 | stack_v2_sparse_classes_30k_train_017475 | Implement the Python class `RandomTranslate` described below.
Class description:
Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cro... | Implement the Python class `RandomTranslate` described below.
Class description:
Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cro... | d6582a0fd386517fdefbe2c347cef53150b5b1da | <|skeleton|>
class RandomTranslate:
"""Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cropped by a reversed translation -t. The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomTranslate:
"""Creates a translation between images by applying a random alternated crop on the sequence of inputs. A translation value t is randomly selected first. Then, the first image is cropped by a box translated by t. The second image will be cropped by a reversed translation -t. The third will be... | the_stack_v2_python_sparse | ptlflow/data/flow_transforms.py | hmorimitsu/ptlflow | train | 140 |
b6f5a597e9476892597190aedabef8077c18ef43 | [
"if isinstance(self, Empty):\n return self.valid\nelif isinstance(self, All):\n return len(self.rules) == 1 and self.rules[0].is_valid\nelif isinstance(self, Any):\n return all((rule.is_valid for rule in self.rules))\nelif isinstance(self, Branch):\n return self.rule.is_valid\nelif isinstance(self, Elem... | <|body_start_0|>
if isinstance(self, Empty):
return self.valid
elif isinstance(self, All):
return len(self.rules) == 1 and self.rules[0].is_valid
elif isinstance(self, Any):
return all((rule.is_valid for rule in self.rules))
elif isinstance(self, Branc... | HasState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
<|body_0|>
def is_error(self) -> bool:
"""Return True when a Rule is error"""
<|body_1|>
def is_terminal(self) -> bool:
"""Return True when a Rule is terminal"""
... | stack_v2_sparse_classes_36k_train_014402 | 16,154 | permissive | [
{
"docstring": "Return True when a Rule is valid",
"name": "is_valid",
"signature": "def is_valid(self) -> bool"
},
{
"docstring": "Return True when a Rule is error",
"name": "is_error",
"signature": "def is_error(self) -> bool"
},
{
"docstring": "Return True when a Rule is termi... | 3 | stack_v2_sparse_classes_30k_train_013677 | Implement the Python class `HasState` described below.
Class description:
Implement the HasState class.
Method signatures and docstrings:
- def is_valid(self) -> bool: Return True when a Rule is valid
- def is_error(self) -> bool: Return True when a Rule is error
- def is_terminal(self) -> bool: Return True when a Ru... | Implement the Python class `HasState` described below.
Class description:
Implement the HasState class.
Method signatures and docstrings:
- def is_valid(self) -> bool: Return True when a Rule is valid
- def is_error(self) -> bool: Return True when a Rule is error
- def is_terminal(self) -> bool: Return True when a Ru... | 39ceb323a63af35e32c4be34ae35a77e811bc973 | <|skeleton|>
class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
<|body_0|>
def is_error(self) -> bool:
"""Return True when a Rule is error"""
<|body_1|>
def is_terminal(self) -> bool:
"""Return True when a Rule is terminal"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
if isinstance(self, Empty):
return self.valid
elif isinstance(self, All):
return len(self.rules) == 1 and self.rules[0].is_valid
elif isinstance(self, Any):
return a... | the_stack_v2_python_sparse | item_engine/base.py | GabrielAmare/TextEngine | train | 0 | |
cdd26fcae9b29bdd70101d3edd484c1dcee03993 | [
"super().__init__()\nself.nr_points_smooth = 50\nself.corr_nr_iters = 10\nself.delta_kickx = 15\nself.delta_kicky = 15\nself.delta_rf = 80\nself.respmat_name = ''",
"dtmp = '{0:26s} = {1:9d} {2:s}\\n'.format\nftmp = '{0:26s} = {1:9.2f} {2:s}\\n'.format\nstg = dtmp('nr_points_smooth', self.nr_points_smooth, '')\... | <|body_start_0|>
super().__init__()
self.nr_points_smooth = 50
self.corr_nr_iters = 10
self.delta_kickx = 15
self.delta_kicky = 15
self.delta_rf = 80
self.respmat_name = ''
<|end_body_0|>
<|body_start_1|>
dtmp = '{0:26s} = {1:9d} {2:s}\n'.format
... | . | RespMatParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RespMatParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.nr_points_smooth = 50
self.corr_nr_iters = 10
self.delta_kickx ... | stack_v2_sparse_classes_36k_train_014403 | 5,185 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `RespMatParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `RespMatParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class RespMatParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class RespMatParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RespMatParams:
"""."""
def __init__(self):
"""."""
super().__init__()
self.nr_points_smooth = 50
self.corr_nr_iters = 10
self.delta_kickx = 15
self.delta_kicky = 15
self.delta_rf = 80
self.respmat_name = ''
def __str__(self):
""... | the_stack_v2_python_sparse | apsuite/commisslib/measure_respmat.py | lnls-fac/apsuite | train | 1 |
bb199b1e282a9949748c56fcefd6739e6d05e6de | [
"self.feature_of_interest_id = BNode()\nself.label = Literal(label)\nself.comment = Literal(comment)",
"return self.feature_of_interest_id\nobsgraph.add((self.feature_of_interest_id, RDF.type, sosa.FeatureOfInterest))\nobsgraph.add((self.feature_of_interest_id, RDFS.comment, self.comment))\nobsgraph.add((self.fea... | <|body_start_0|>
self.feature_of_interest_id = BNode()
self.label = Literal(label)
self.comment = Literal(comment)
<|end_body_0|>
<|body_start_1|>
return self.feature_of_interest_id
obsgraph.add((self.feature_of_interest_id, RDF.type, sosa.FeatureOfInterest))
obsgraph.ad... | Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an act of Sampling. | FeatureOfInterest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureOfInterest:
"""Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an a... | stack_v2_sparse_classes_36k_train_014404 | 1,302 | permissive | [
{
"docstring": "constructor for Feature of Interest Args: label, comment (literal): label and comment for the feature of interest Returns: FOI object: instantiated with feature_of_interest_id, label and comment",
"name": "__init__",
"signature": "def __init__(self, label, comment)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_011026 | Implement the Python class `FeatureOfInterest` described below.
Class description:
Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which ... | Implement the Python class `FeatureOfInterest` described below.
Class description:
Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which ... | 1993668bd75bc882286da818955a40dd01d2f7c6 | <|skeleton|>
class FeatureOfInterest:
"""Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureOfInterest:
"""Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an act of Samplin... | the_stack_v2_python_sparse | PySOSA/FeatureOfInterest.py | landrs-toolkit/PySOSA | train | 1 |
7da4ad02a956f6a9f0fb617eb71d20c4dea10399 | [
"if nums == []:\n return 1\nn = len(nums)\nbitflag = 2 ** (n + 1) - 1\ngetbit = lambda num, k: num >> k - 1 & 1\nsetbitzero = lambda num, k: num & ~(1 << k - 1)\nfor num in nums:\n if num > 0 and getbit(bitflag, num) == 1:\n bitflag = setbitzero(bitflag, num)\ntmp = bitflag & (bitflag ^ bitflag - 1)\ni... | <|body_start_0|>
if nums == []:
return 1
n = len(nums)
bitflag = 2 ** (n + 1) - 1
getbit = lambda num, k: num >> k - 1 & 1
setbitzero = lambda num, k: num & ~(1 << k - 1)
for num in nums:
if num > 0 and getbit(bitflag, num) == 1:
bi... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums == []:
... | stack_v2_sparse_classes_36k_train_014405 | 1,873 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive_2",
"signature": "def firstMissingPositive_2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008877 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive_2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive_2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 38eb0556f865fd06f517ca45253d00aaca39d70b | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive_2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
if nums == []:
return 1
n = len(nums)
bitflag = 2 ** (n + 1) - 1
getbit = lambda num, k: num >> k - 1 & 1
setbitzero = lambda num, k: num & ~(1 << k - 1)
... | the_stack_v2_python_sparse | Python3/no41_First_Missing_Positive.py | yif042/leetcode | train | 0 | |
2a98cd4ae11d3910ca20f87248a6c7ccfd553033 | [
"self.entities = entities\nself.decimal = decimal\nself.hexadecimal = hexadecimal\nself.max_length = max_length\nself.word_boundary = word_boundary\nself.save_order = save_order\nself.separator = separator\nself.stopwords = stopwords\nself.regex_pattern = regex_pattern\nself.lowercase = lowercase\nself.replacements... | <|body_start_0|>
self.entities = entities
self.decimal = decimal
self.hexadecimal = hexadecimal
self.max_length = max_length
self.word_boundary = word_boundary
self.save_order = save_order
self.separator = separator
self.stopwords = stopwords
self.... | Slugify filter Uses python-slugify library to create a url-compatible slug from the given text. | Slugify | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slugify:
"""Slugify filter Uses python-slugify library to create a url-compatible slug from the given text."""
def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_order=False, separator='-', stopwords=(), regex_pattern=None, lowercase... | stack_v2_sparse_classes_36k_train_014406 | 2,733 | permissive | [
{
"docstring": "Initialise filter Accepts input keyword arguments to allow overriding defaults",
"name": "__init__",
"signature": "def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_order=False, separator='-', stopwords=(), regex_pattern=None, l... | 2 | null | Implement the Python class `Slugify` described below.
Class description:
Slugify filter Uses python-slugify library to create a url-compatible slug from the given text.
Method signatures and docstrings:
- def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_ord... | Implement the Python class `Slugify` described below.
Class description:
Slugify filter Uses python-slugify library to create a url-compatible slug from the given text.
Method signatures and docstrings:
- def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_ord... | c598d1af5df40fae65cf3878b8f67accbcd059b7 | <|skeleton|>
class Slugify:
"""Slugify filter Uses python-slugify library to create a url-compatible slug from the given text."""
def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_order=False, separator='-', stopwords=(), regex_pattern=None, lowercase... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Slugify:
"""Slugify filter Uses python-slugify library to create a url-compatible slug from the given text."""
def __init__(self, *_, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False, save_order=False, separator='-', stopwords=(), regex_pattern=None, lowercase=True, replac... | the_stack_v2_python_sparse | shiftschema/filters/slugify.py | projectshift/shift-schema | train | 2 |
91049764543557bed8d8bf82e4e707f4ab4b0be6 | [
"super(Critic, self).__init__()\nself.hidden_layers = nn.ModuleList([nn.Linear(state_size * num_agents, hidden_layers[0])])\nedited_hidden_layers = [hl for hl in hidden_layers]\nedited_hidden_layers[0] = hidden_layers[0] + action_size * num_agents\nA = edited_hidden_layers[:-1]\nB = edited_hidden_layers[1:]\nself.h... | <|body_start_0|>
super(Critic, self).__init__()
self.hidden_layers = nn.ModuleList([nn.Linear(state_size * num_agents, hidden_layers[0])])
edited_hidden_layers = [hl for hl in hidden_layers]
edited_hidden_layers[0] = hidden_layers[0] + action_size * num_agents
A = edited_hidden_l... | Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers. | Critic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers."""
def __init__(self, state_size, action_size, num_agents, hidden_layers=[512, 2... | stack_v2_sparse_classes_36k_train_014407 | 2,717 | permissive | [
{
"docstring": "Create an instance of a critic network. Parameters ---------- state_size : int The number of values in the input vector action_size : int The number of values in the output vector num_agents : int The number of agents in the environment hidden_layers : [int] Number of neurons in each hidden laye... | 2 | stack_v2_sparse_classes_30k_train_001222 | Implement the Python class `Critic` described below.
Class description:
Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers.
Method signatures and docstrings:
- def __ini... | Implement the Python class `Critic` described below.
Class description:
Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers.
Method signatures and docstrings:
- def __ini... | 396648570aa53c9e727a8de69175e4a139d4ded5 | <|skeleton|>
class Critic:
"""Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers."""
def __init__(self, state_size, action_size, num_agents, hidden_layers=[512, 2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
"""Architecture for a critic network. Given a state and action, estimate its Q value. Input, output and hidden layers can be customized. ReLU is used between layers. Doesn't contain convolutional layers."""
def __init__(self, state_size, action_size, num_agents, hidden_layers=[512, 256]):
... | the_stack_v2_python_sparse | p3-collab-compet/code/Critic.py | francescotorregrossa/deep-reinforcement-learning-nanodegree | train | 2 |
5f1990d10b5630f8fb3af48a8d05319a5ea7ca10 | [
"try:\n result = data.ImageManager().get_preview_list(nnid)\n return_data = {'status': '200', 'result': result}\n print(json.dumps(return_data))\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(retur... | <|body_start_0|>
try:
result = data.ImageManager().get_preview_list(nnid)
return_data = {'status': '200', 'result': result}
print(json.dumps(return_data))
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': ... | ImageFilePreview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageFilePreview:
def get(self, request, nnid):
"""- desc : get image file list"""
<|body_0|>
def delete(self, request, nnid):
"""- desc : get image file list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
result = data.ImageManage... | stack_v2_sparse_classes_36k_train_014408 | 1,218 | no_license | [
{
"docstring": "- desc : get image file list",
"name": "get",
"signature": "def get(self, request, nnid)"
},
{
"docstring": "- desc : get image file list",
"name": "delete",
"signature": "def delete(self, request, nnid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012846 | Implement the Python class `ImageFilePreview` described below.
Class description:
Implement the ImageFilePreview class.
Method signatures and docstrings:
- def get(self, request, nnid): - desc : get image file list
- def delete(self, request, nnid): - desc : get image file list | Implement the Python class `ImageFilePreview` described below.
Class description:
Implement the ImageFilePreview class.
Method signatures and docstrings:
- def get(self, request, nnid): - desc : get image file list
- def delete(self, request, nnid): - desc : get image file list
<|skeleton|>
class ImageFilePreview:
... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class ImageFilePreview:
def get(self, request, nnid):
"""- desc : get image file list"""
<|body_0|>
def delete(self, request, nnid):
"""- desc : get image file list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageFilePreview:
def get(self, request, nnid):
"""- desc : get image file list"""
try:
result = data.ImageManager().get_preview_list(nnid)
return_data = {'status': '200', 'result': result}
print(json.dumps(return_data))
return Response(json.dump... | the_stack_v2_python_sparse | tfmsarest/views/imagefile_preview.py | TensorMSA/tensormsa_old | train | 6 | |
33537e9c37f439bbf482f47b17a6903cdbbc60ec | [
"logs = set(logs) if logs else set()\nmetrics = tuple(metrics) if metrics else tuple()\nlabels = tuple(labels) if labels else tuple()\nreturn super(cls, ReportingRules).__new__(cls, logs, metrics, labels)",
"if not metric_names:\n metric_names = ()\nif not label_names:\n label_names = ()\nknown_labels = []\... | <|body_start_0|>
logs = set(logs) if logs else set()
metrics = tuple(metrics) if metrics else tuple()
labels = tuple(labels) if labels else tuple()
return super(cls, ReportingRules).__new__(cls, logs, metrics, labels)
<|end_body_0|>
<|body_start_1|>
if not metric_names:
... | Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): the metrics to be added to a `ReportRequest` labels (iterable[:class:`google.api.co... | ReportingRules | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportingRules:
"""Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): the metrics to be added to a `ReportReque... | stack_v2_sparse_classes_36k_train_014409 | 18,948 | permissive | [
{
"docstring": "Invokes the base constructor with default values.",
"name": "__new__",
"signature": "def __new__(cls, logs=None, metrics=None, labels=None)"
},
{
"docstring": "An alternate constructor that assumes known metrics and labels. This differs from the default constructor in that the me... | 2 | null | Implement the Python class `ReportingRules` described below.
Class description:
Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): th... | Implement the Python class `ReportingRules` described below.
Class description:
Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): th... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class ReportingRules:
"""Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): the metrics to be added to a `ReportReque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportingRules:
"""Holds information that determines how to fill a `ReportRequest`. Attributes: logs (iterable[string]): the name of logs to be included in the `ReportRequest` metrics (iterable[:class:`google.api.control.metric_descriptor.KnownMetrics`]): the metrics to be added to a `ReportRequest` labels (i... | the_stack_v2_python_sparse | third_party/google-endpoints/google/api/control/report_request.py | catapult-project/catapult | train | 2,032 |
ebca4c458902bcb267808b954653a1f1fc743989 | [
"dashborad_type = int(request.DATA.get('dashborad_type', 1))\nagent = request.user.userinfo.agent\ntry:\n dashborad = models.SSADashBorad.objects.get(type=dashborad_type, agent=agent)\nexcept models.SSADashBorad.DoesNotExist:\n return Response({'status': 500, 'msg': 'dashborad不存在'})\nobj_serializer = serializ... | <|body_start_0|>
dashborad_type = int(request.DATA.get('dashborad_type', 1))
agent = request.user.userinfo.agent
try:
dashborad = models.SSADashBorad.objects.get(type=dashborad_type, agent=agent)
except models.SSADashBorad.DoesNotExist:
return Response({'status': ... | 态势感知DashBorad | SSADashBorad | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSADashBorad:
"""态势感知DashBorad"""
def put(self, request):
"""修改dashborad名称"""
<|body_0|>
def get(self, request):
"""获取相应态势感知图表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dashborad_type = int(request.DATA.get('dashborad_type', 1))
ag... | stack_v2_sparse_classes_36k_train_014410 | 13,980 | no_license | [
{
"docstring": "修改dashborad名称",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "获取相应态势感知图表",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | null | Implement the Python class `SSADashBorad` described below.
Class description:
态势感知DashBorad
Method signatures and docstrings:
- def put(self, request): 修改dashborad名称
- def get(self, request): 获取相应态势感知图表 | Implement the Python class `SSADashBorad` described below.
Class description:
态势感知DashBorad
Method signatures and docstrings:
- def put(self, request): 修改dashborad名称
- def get(self, request): 获取相应态势感知图表
<|skeleton|>
class SSADashBorad:
"""态势感知DashBorad"""
def put(self, request):
"""修改dashborad名称"""
... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class SSADashBorad:
"""态势感知DashBorad"""
def put(self, request):
"""修改dashborad名称"""
<|body_0|>
def get(self, request):
"""获取相应态势感知图表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSADashBorad:
"""态势感知DashBorad"""
def put(self, request):
"""修改dashborad名称"""
dashborad_type = int(request.DATA.get('dashborad_type', 1))
agent = request.user.userinfo.agent
try:
dashborad = models.SSADashBorad.objects.get(type=dashborad_type, agent=agent)
... | the_stack_v2_python_sparse | soc_ssa/views/ssa_views/dashboard_view.py | sundw2015/841 | train | 4 |
5d9277c41c0436de48eeb2f06b1c9a9739629d33 | [
"self.__k = k\nself.__tol = tol\nself.__max_iter = max_iter\nself.__centroids = {}\nself.__metric = metric",
"optimized = False\ni = 0\nwhile not optimized and i < self.__k:\n self.__centroids[i] = data[i]\nfor i in range(self.__max_iter):\n classifications = {}\n for j in range(self.__k):\n class... | <|body_start_0|>
self.__k = k
self.__tol = tol
self.__max_iter = max_iter
self.__centroids = {}
self.__metric = metric
<|end_body_0|>
<|body_start_1|>
optimized = False
i = 0
while not optimized and i < self.__k:
self.__centroids[i] = data[i]
... | Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executing K-Means algorithm. __metric : function Metric used in the algorithm. | K_Means | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class K_Means:
"""Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executing K-Means algorithm. __metric : functio... | stack_v2_sparse_classes_36k_train_014411 | 3,525 | no_license | [
{
"docstring": "Class constructor Parameters ---------- k : int (optional) Number of clusters. The default value is 3. tol : float (optional) Tolerance. The default value is 0.001. max_iter : int (optional) Maximum number of iterations. The default value is 3000. metric : function (optional) Metric used in the ... | 3 | stack_v2_sparse_classes_30k_train_017596 | Implement the Python class `K_Means` described below.
Class description:
Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executin... | Implement the Python class `K_Means` described below.
Class description:
Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executin... | fd414bc18aa6c5faedb6bb4af025a8a187df983c | <|skeleton|>
class K_Means:
"""Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executing K-Means algorithm. __metric : functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class K_Means:
"""Class which implements K-Means algorithm with the required distance. Attributes ---------- __k : int Number of clusters. __tol : float Tolerance. __max_iter : int Maximum number of iterations. __centroids : dict Resulting centroids after executing K-Means algorithm. __metric : function Metric used... | the_stack_v2_python_sparse | bin/MyKMeans.py | aarondlc/teselado | train | 0 |
60b4835afdf9b4444dc10aafe135bba0748f8ee5 | [
"self.cpu_throttle_count = {}\ncores = [str(core) for core in cores] if cores else ['*']\nfor core in cores:\n for file in glob.iglob(f'/sys/devices/system/cpu/cpu{core}/thermal_throttle/*_throttle_count'):\n try:\n self.cpu_throttle_count[file] = int(util.read_file(file))\n except Excep... | <|body_start_0|>
self.cpu_throttle_count = {}
cores = [str(core) for core in cores] if cores else ['*']
for core in cores:
for file in glob.iglob(f'/sys/devices/system/cpu/cpu{core}/thermal_throttle/*_throttle_count'):
try:
self.cpu_throttle_count[... | Class for checking whether the CPU has throttled during some time period. | CPUThrottleCheck | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPUThrottleCheck:
"""Class for checking whether the CPU has throttled during some time period."""
def __init__(self, cores=None):
"""Create an instance that monitors the given list of cores (or all CPUs)."""
<|body_0|>
def has_throttled(self):
"""Check whether an... | stack_v2_sparse_classes_36k_train_014412 | 7,810 | permissive | [
{
"docstring": "Create an instance that monitors the given list of cores (or all CPUs).",
"name": "__init__",
"signature": "def __init__(self, cores=None)"
},
{
"docstring": "Check whether any of the CPU cores monitored by this instance has throttled since this instance was created. @return a bo... | 2 | stack_v2_sparse_classes_30k_val_001040 | Implement the Python class `CPUThrottleCheck` described below.
Class description:
Class for checking whether the CPU has throttled during some time period.
Method signatures and docstrings:
- def __init__(self, cores=None): Create an instance that monitors the given list of cores (or all CPUs).
- def has_throttled(se... | Implement the Python class `CPUThrottleCheck` described below.
Class description:
Class for checking whether the CPU has throttled during some time period.
Method signatures and docstrings:
- def __init__(self, cores=None): Create an instance that monitors the given list of cores (or all CPUs).
- def has_throttled(se... | 2c56e08d5f0f44b3073f9c82a6c5f166a12b45e7 | <|skeleton|>
class CPUThrottleCheck:
"""Class for checking whether the CPU has throttled during some time period."""
def __init__(self, cores=None):
"""Create an instance that monitors the given list of cores (or all CPUs)."""
<|body_0|>
def has_throttled(self):
"""Check whether an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPUThrottleCheck:
"""Class for checking whether the CPU has throttled during some time period."""
def __init__(self, cores=None):
"""Create an instance that monitors the given list of cores (or all CPUs)."""
self.cpu_throttle_count = {}
cores = [str(core) for core in cores] if cor... | the_stack_v2_python_sparse | benchexec/systeminfo.py | sosy-lab/benchexec | train | 176 |
99994b10ce19355f3621eb6aaf7f4948c9f51257 | [
"try:\n parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')\nexcept ArgumentError:\n pass",
"params = ctx.get_params('mccabe')\noptions = ctx.options\nif options:\n params.setdefault('max-complexity', options.max_complexity)\nMcCabeChecker.max_complexity = int(p... | <|body_start_0|>
try:
parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')
except ArgumentError:
pass
<|end_body_0|>
<|body_start_1|>
params = ctx.get_params('mccabe')
options = ctx.options
if options:
... | Run complexity checking. | Linter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Run Mccabe code checker."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try... | stack_v2_sparse_classes_36k_train_014413 | 1,355 | permissive | [
{
"docstring": "Add --max-complexity option.",
"name": "add_args",
"signature": "def add_args(cls, parser: ArgumentParser)"
},
{
"docstring": "Run Mccabe code checker.",
"name": "run_check",
"signature": "def run_check(self, ctx: RunContext)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007999 | Implement the Python class `Linter` described below.
Class description:
Run complexity checking.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Run Mccabe code checker. | Implement the Python class `Linter` described below.
Class description:
Run complexity checking.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Run Mccabe code checker.
<|skeleton|>
class Linter:
"""Run complexit... | 53ad214de0aa9534e59bcd5f97d9d723d16cfdb8 | <|skeleton|>
class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Run Mccabe code checker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linter:
"""Run complexity checking."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
try:
parser.add_argument('--max-complexity', default=10, type=int, help='Max complexity threshold')
except ArgumentError:
pass
def run_... | the_stack_v2_python_sparse | pylama/lint/pylama_mccabe.py | klen/pylama | train | 1,022 |
41a937c0f0b63e2ecf56b9041c2aa1e7b7700854 | [
"self.mode = mode\nself.config = config\nif mode == 'train':\n self.data_files = config['train_data_files']\nelif mode == 'train_eval':\n self.data_files = [config['train_data_files'][0]]\nelif mode == 'valid':\n self.data_files = [config['valid_data_file']]\nelif mode == 'test':\n self.data_files = [co... | <|body_start_0|>
self.mode = mode
self.config = config
if mode == 'train':
self.data_files = config['train_data_files']
elif mode == 'train_eval':
self.data_files = [config['train_data_files'][0]]
elif mode == 'valid':
self.data_files = [config... | Wrapper class for input_fn passed to TPUEstimator. | CIFARInput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"... | stack_v2_sparse_classes_36k_train_014414 | 5,838 | permissive | [
{
"docstring": "Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files",
"name": "__init__",
"signature": "def __init__(self, mode, config)"
},
{
"docstring": "Number of ima... | 3 | stack_v2_sparse_classes_30k_train_002260 | Implement the Python class `CIFARInput` described below.
Class description:
Wrapper class for input_fn passed to TPUEstimator.
Method signatures and docstrings:
- def __init__(self, mode, config): Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from ... | Implement the Python class `CIFARInput` described below.
Class description:
Wrapper class for input_fn passed to TPUEstimator.
Method signatures and docstrings:
- def __init__(self, mode, config): Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from ... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CIFARInput:
"""Wrapper class for input_fn passed to TPUEstimator."""
def __init__(self, mode, config):
"""Initializes a CIFARInput object. Args: mode: one of [train, valid, test, augment, sample] config: config dict built from config.py Raises: ValueError: invalid mode or data files"""
se... | the_stack_v2_python_sparse | nasws/cnn/search_space/nasbench101/lib/cifar.py | kcyu2014/nas-landmarkreg | train | 10 |
5b14b164a3fb642c0364e6e6c3d0bb459b9ec96f | [
"@functools.wraps(func)\ndef wrapper(self, *args, **kwargs):\n if not isinstance(self.source_file, str):\n raise RuntimeError('<self.source_file> is not given.')\n return func(self, *args, **kwargs)\nreturn wrapper",
"file_helper = FileHelper(self.source_file)\nif file_helper.exists():\n with file... | <|body_start_0|>
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not isinstance(self.source_file, str):
raise RuntimeError('<self.source_file> is not given.')
return func(self, *args, **kwargs)
return wrapper
<|end_body_0|>
<|body_start_1|>
... | Provides the base of all CSV file migrator classes. | CSVFileMigratorBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVFileMigratorBase:
"""Provides the base of all CSV file migrator classes."""
def ensure_source_file_is_given(func):
"""Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the:code:`self.source_file` is not given."""
<|body_... | stack_v2_sparse_classes_36k_train_014415 | 5,781 | permissive | [
{
"docstring": "Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the:code:`self.source_file` is not given.",
"name": "ensure_source_file_is_given",
"signature": "def ensure_source_file_is_given(func)"
},
{
"docstring": "Provides the migrator ... | 3 | stack_v2_sparse_classes_30k_train_012254 | Implement the Python class `CSVFileMigratorBase` described below.
Class description:
Provides the base of all CSV file migrator classes.
Method signatures and docstrings:
- def ensure_source_file_is_given(func): Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the... | Implement the Python class `CSVFileMigratorBase` described below.
Class description:
Provides the base of all CSV file migrator classes.
Method signatures and docstrings:
- def ensure_source_file_is_given(func): Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the... | 214a57d0eca3df7c4ed3421937aaff9998452ba6 | <|skeleton|>
class CSVFileMigratorBase:
"""Provides the base of all CSV file migrator classes."""
def ensure_source_file_is_given(func):
"""Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the:code:`self.source_file` is not given."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSVFileMigratorBase:
"""Provides the base of all CSV file migrator classes."""
def ensure_source_file_is_given(func):
"""Ensures that the source file is given before launching the decorated method. :raise RuntimeError: When the:code:`self.source_file` is not given."""
@functools.wraps(fun... | the_stack_v2_python_sparse | PyFunceble/cli/migrators/csv_file/base.py | funilrys/PyFunceble | train | 267 |
ef34f2d3b064ee1dc59f887e4554fdb8306d6ba8 | [
"data = YTdl.extract_info(url, download=not stream)\nif 'entries' in data:\n data = data['entries'][0]\nif stream:\n path = data['url']\n before_options = STREAM_OPTIONS\nelse:\n path = YTdl.prepare_filename(data)\n before_options = None\nargs = cls._create_process_preprocess(path, DEFAULT_EXECUTABLE... | <|body_start_0|>
data = YTdl.extract_info(url, download=not stream)
if 'entries' in data:
data = data['entries'][0]
if stream:
path = data['url']
before_options = STREAM_OPTIONS
else:
path = YTdl.prepare_filename(data)
before_op... | Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`)) Parameters and the stdin used to open the postprocess when postprocess ... | YTAudio | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YTAudio:
"""Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`)) Parameters and the stdin used to ope... | stack_v2_sparse_classes_36k_train_014416 | 18,873 | permissive | [
{
"docstring": "Downloads the audio source by the given url or title. This function runs inside of an executor thread. Parameters ---------- url : `str` Returns ------- path : `str` The title of the downloaded audio. data : `dict` of (`str`, `Any`) All extracted data by YTDL. args : `list` of `str` Subprocess p... | 2 | null | Implement the Python class `YTAudio` described below.
Class description:
Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`... | Implement the Python class `YTAudio` described below.
Class description:
Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class YTAudio:
"""Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`)) Parameters and the stdin used to ope... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YTAudio:
"""Represents an audio sourced downloaded from youtube. You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Attributes ---------- _process_args : `tuple` ((`list` of `str`), (`None`, `file-like`)) Parameters and the stdin used to open the postpro... | the_stack_v2_python_sparse | hata/discord/voice/audio_source.py | HuyaneMatsu/hata | train | 3 |
dc9f2b5a622ad692b84ad80bbc56873f84697c84 | [
"if not root:\n return True\nreturn self.helper(root)[2]",
"if not root.left and (not root.right):\n return (root.val, root.val, True)\nl_min, l_max = (None, None)\nr_min, r_max = (None, None)\nis_valid = True\nif root.left:\n l_min, l_max, l_valid = self.helper(root.left)\n if l_valid == False:\n ... | <|body_start_0|>
if not root:
return True
return self.helper(root)[2]
<|end_body_0|>
<|body_start_1|>
if not root.left and (not root.right):
return (root.val, root.val, True)
l_min, l_max = (None, None)
r_min, r_max = (None, None)
is_valid = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def helper(self, root):
"""return min_val, max_val, is_valid"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
return... | stack_v2_sparse_classes_36k_train_014417 | 1,300 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": "return min_val, max_val, is_valid",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def helper(self, root): return min_val, max_val, is_valid | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def helper(self, root): return min_val, max_val, is_valid
<|skeleton|>
class Solution:
def isValidBST(self, ... | 24aaca7585c59255a86474c1f8088bd5b81ebf51 | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def helper(self, root):
"""return min_val, max_val, is_valid"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
return self.helper(root)[2]
def helper(self, root):
"""return min_val, max_val, is_valid"""
if not root.left and (not root.right):
return ... | the_stack_v2_python_sparse | Tree/98. Validate Binary Search Tree.py | burnmg/LC_algorithms_practice | train | 0 | |
2c8a7388339745243238b4d5af28053188297fae | [
"OCRequest.__init__(self)\nself.host_ip = os_pub_ip\nself.tenant_id = tenant_id\nself.tenant_token = tenant_token",
"_url = 'http://' + self.host_ip + ':8004/v1/' + self.tenant_id + '/stacks'\n_headers = {'Content-type': 'application/json', 'x-auth-token': self.tenant_token}\n_body = None\nresponse = self.request... | <|body_start_0|>
OCRequest.__init__(self)
self.host_ip = os_pub_ip
self.tenant_id = tenant_id
self.tenant_token = tenant_token
<|end_body_0|>
<|body_start_1|>
_url = 'http://' + self.host_ip + ':8004/v1/' + self.tenant_id + '/stacks'
_headers = {'Content-type': 'applicat... | This class contains basic operation on stack like stack list, show, stack resource list, etc. | HeatLibrary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
<|body_0|>
def stack_list(self):
"""To get t... | stack_v2_sparse_classes_36k_train_014418 | 6,881 | no_license | [
{
"docstring": "It requires the ID and token of the tenant.",
"name": "__init__",
"signature": "def __init__(self, os_pub_ip, tenant_id, tenant_token)"
},
{
"docstring": "To get the list of created stacks. Return: List of all stacks created in the tenant.",
"name": "stack_list",
"signatu... | 6 | stack_v2_sparse_classes_30k_train_011568 | Implement the Python class `HeatLibrary` described below.
Class description:
This class contains basic operation on stack like stack list, show, stack resource list, etc.
Method signatures and docstrings:
- def __init__(self, os_pub_ip, tenant_id, tenant_token): It requires the ID and token of the tenant.
- def stack... | Implement the Python class `HeatLibrary` described below.
Class description:
This class contains basic operation on stack like stack list, show, stack resource list, etc.
Method signatures and docstrings:
- def __init__(self, os_pub_ip, tenant_id, tenant_token): It requires the ID and token of the tenant.
- def stack... | cd5f98de9b82ffeb267e9f2e1fd9c84a3c24d7bf | <|skeleton|>
class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
<|body_0|>
def stack_list(self):
"""To get t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeatLibrary:
"""This class contains basic operation on stack like stack list, show, stack resource list, etc."""
def __init__(self, os_pub_ip, tenant_id, tenant_token):
"""It requires the ID and token of the tenant."""
OCRequest.__init__(self)
self.host_ip = os_pub_ip
self... | the_stack_v2_python_sparse | merge-master-fw-norule/ATF/atf/lib/lib_heat.py | deekshithpatnala/nsd_atf | train | 0 |
820d99d5a9211eb39116a44f2c03cd59d99c5a25 | [
"cur = head\nidx = 0\npassed_dict = {}\nwhile cur:\n if cur in passed_dict:\n return cur\n passed_dict[cur] = idx\n cur = cur.next\n idx += 1\nelse:\n return None",
"fast = slow = head\nwhile slow and fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\... | <|body_start_0|>
cur = head
idx = 0
passed_dict = {}
while cur:
if cur in passed_dict:
return cur
passed_dict[cur] = idx
cur = cur.next
idx += 1
else:
return None
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle(self, head):
"""快慢指针法 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
... | stack_v2_sparse_classes_36k_train_014419 | 2,258 | no_license | [
{
"docstring": "集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode",
"name": "detectCycle2",
"signature": "def detectCycle2(self, head)"
},
{
"docstring": "快慢指针法 :type head: ListNode :rtype: bool",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle2(self, head): 集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode
- def detectCycle(self, head): 快慢指针法 :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle2(self, head): 集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode
- def detectCycle(self, head): 快慢指针法 :type head: ListNode :rtype: bool
<|skeleton|>
class Solu... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle(self, head):
"""快慢指针法 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCycle2(self, head):
"""集合法, 需要额外的存储空间 :type head: ListNode :rtype: ListNode"""
cur = head
idx = 0
passed_dict = {}
while cur:
if cur in passed_dict:
return cur
passed_dict[cur] = idx
cur = cur.next
... | the_stack_v2_python_sparse | leetcode/142.linked-list-cycle-ii.py | iamkissg/leetcode | train | 0 | |
89ccd82de8599c07112014d1c6fa851bacecc33d | [
"url = 'http://third.payment.pay/'\ndata = {'card_num': card_num, 'amount': amount}\nresponse = requests.post(url=url, data=data)\nreturn requests.status_codes",
"try:\n resp = self.requestOutofSystem(card_num, amount)\n print('调用第三方支付接口返回结果:%s' % resp)\nexcept TimeoutError:\n print('支付超时,重新支付')\n res... | <|body_start_0|>
url = 'http://third.payment.pay/'
data = {'card_num': card_num, 'amount': amount}
response = requests.post(url=url, data=data)
return requests.status_codes
<|end_body_0|>
<|body_start_1|>
try:
resp = self.requestOutofSystem(card_num, amount)
... | Payment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
<|body_0|>
def doPay(self, user_id, card_num, amount):
"""支付 :param user_id:用户id :param card_num:卡号 :param a... | stack_v2_sparse_classes_36k_train_014420 | 3,097 | no_license | [
{
"docstring": "请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败",
"name": "requestOutofSystem",
"signature": "def requestOutofSystem(self, card_num, amount)"
},
{
"docstring": "支付 :param user_id:用户id :param card_num:卡号 :param amount: 支付金额 :return:"... | 2 | null | Implement the Python class `Payment` described below.
Class description:
Implement the Payment class.
Method signatures and docstrings:
- def requestOutofSystem(self, card_num, amount): 请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败
- def doPay(self, user_id, card_num,... | Implement the Python class `Payment` described below.
Class description:
Implement the Payment class.
Method signatures and docstrings:
- def requestOutofSystem(self, card_num, amount): 请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败
- def doPay(self, user_id, card_num,... | 8f10d3c70ab785d4120d24673b0945a169f2355c | <|skeleton|>
class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
<|body_0|>
def doPay(self, user_id, card_num, amount):
"""支付 :param user_id:用户id :param card_num:卡号 :param a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
url = 'http://third.payment.pay/'
data = {'card_num': card_num, 'amount': amount}
response = requests.post(url=url, dat... | the_stack_v2_python_sparse | mystudy/mockdemo/mock_03.py | zhenfang95/Hello-World | train | 0 | |
b0f7473b5387043ecb040ede04506630850022a2 | [
"super(PPO_ActorNetwork, self).__init__()\nxp_input = L.Placeholder((None, D_obs))\nxp = L.Linear(hidden_sizes[0])(xp_input)\nxp = L.ReLU()(xp)\nxp = L.Linear(hidden_sizes[1])(xp)\nxp = L.ReLU()(xp)\nxp = L.Linear(D_act)(xp)\nxp = L.Tanh()(xp)\nself.model = L.Functional(inputs=xp_input, outputs=xp)\nself.model.buil... | <|body_start_0|>
super(PPO_ActorNetwork, self).__init__()
xp_input = L.Placeholder((None, D_obs))
xp = L.Linear(hidden_sizes[0])(xp_input)
xp = L.ReLU()(xp)
xp = L.Linear(hidden_sizes[1])(xp)
xp = L.ReLU()(xp)
xp = L.Linear(D_act)(xp)
xp = L.Tanh()(xp)
... | PPO custom actor network structure | PPO_ActorNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PPO_ActorNetwork:
"""PPO custom actor network structure"""
def __init__(self, D_obs, D_act, hidden_sizes=[64, 64], init_log_sig=0):
"""Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: action space dimension, scalar hidden_sizes: list of fully ... | stack_v2_sparse_classes_36k_train_014421 | 5,859 | permissive | [
{
"docstring": "Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: action space dimension, scalar hidden_sizes: list of fully connected dimension init_log_sig: initial value for log standard deviation parameter",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_007973 | Implement the Python class `PPO_ActorNetwork` described below.
Class description:
PPO custom actor network structure
Method signatures and docstrings:
- def __init__(self, D_obs, D_act, hidden_sizes=[64, 64], init_log_sig=0): Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: ac... | Implement the Python class `PPO_ActorNetwork` described below.
Class description:
PPO custom actor network structure
Method signatures and docstrings:
- def __init__(self, D_obs, D_act, hidden_sizes=[64, 64], init_log_sig=0): Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: ac... | 2556bd9c362a53e0a94da914ba59b5d4621c4081 | <|skeleton|>
class PPO_ActorNetwork:
"""PPO custom actor network structure"""
def __init__(self, D_obs, D_act, hidden_sizes=[64, 64], init_log_sig=0):
"""Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: action space dimension, scalar hidden_sizes: list of fully ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PPO_ActorNetwork:
"""PPO custom actor network structure"""
def __init__(self, D_obs, D_act, hidden_sizes=[64, 64], init_log_sig=0):
"""Constructor for PPO actor network Args: D_obs: observation space dimension, scalar D_act: action space dimension, scalar hidden_sizes: list of fully connected dim... | the_stack_v2_python_sparse | surreal/model/model_builders/builders.py | PeihongYu/surreal | train | 0 |
57998053c305a12dea390ed3fc15ddb538d1dff9 | [
"part1 = volumePartition(7, VolumeOffset(3, 1, 5))\npart2 = volumePartition(7, VolumeOffset(3, 2, 5))\npart3 = volumePartition(8, VolumeOffset(3, 1, 5))\nself.assertEqual(hash(part1), hash(part2))\nself.assertNotEqual(hash(part1), hash(part3))",
"part1 = volumePartition(7, VolumeOffset(3, 1, 5))\npart2 = volumePa... | <|body_start_0|>
part1 = volumePartition(7, VolumeOffset(3, 1, 5))
part2 = volumePartition(7, VolumeOffset(3, 2, 5))
part3 = volumePartition(8, VolumeOffset(3, 1, 5))
self.assertEqual(hash(part1), hash(part2))
self.assertNotEqual(hash(part1), hash(part3))
<|end_body_0|>
<|body_s... | TestVolumePartition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
<|body_0|>
def test_partitioneq(self):
"""Check equivalence function for volumePartition."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
part1 = vo... | stack_v2_sparse_classes_36k_train_014422 | 6,793 | permissive | [
{
"docstring": "Check hashing function for volumePartition.",
"name": "test_partitionhash",
"signature": "def test_partitionhash(self)"
},
{
"docstring": "Check equivalence function for volumePartition.",
"name": "test_partitioneq",
"signature": "def test_partitioneq(self)"
}
] | 2 | null | Implement the Python class `TestVolumePartition` described below.
Class description:
Implement the TestVolumePartition class.
Method signatures and docstrings:
- def test_partitionhash(self): Check hashing function for volumePartition.
- def test_partitioneq(self): Check equivalence function for volumePartition. | Implement the Python class `TestVolumePartition` described below.
Class description:
Implement the TestVolumePartition class.
Method signatures and docstrings:
- def test_partitionhash(self): Check hashing function for volumePartition.
- def test_partitioneq(self): Check equivalence function for volumePartition.
<|s... | 14b271b150508ad247347898c0b1ac7365931b05 | <|skeleton|>
class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
<|body_0|>
def test_partitioneq(self):
"""Check equivalence function for volumePartition."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestVolumePartition:
def test_partitionhash(self):
"""Check hashing function for volumePartition."""
part1 = volumePartition(7, VolumeOffset(3, 1, 5))
part2 = volumePartition(7, VolumeOffset(3, 2, 5))
part3 = volumePartition(8, VolumeOffset(3, 1, 5))
self.assertEqual(ha... | the_stack_v2_python_sparse | obsolete/unit_tests/io_util/test_partitionSchema.py | janelia-flyem/flyemflows | train | 1 | |
de5ffca24098cdb977cfc2c9dac9c21e2ff4f604 | [
"for graph, expectedoutput in self.knownpairs:\n output = [list(C) for C in StronglyConnectedComponents(graph)]\n for component in output:\n component.sort()\n output.sort()\n self.assertEqual(output, expectedoutput)",
"for graph, expectedoutput in self.knownpairs:\n components = StronglyCon... | <|body_start_0|>
for graph, expectedoutput in self.knownpairs:
output = [list(C) for C in StronglyConnectedComponents(graph)]
for component in output:
component.sort()
output.sort()
self.assertEqual(output, expectedoutput)
<|end_body_0|>
<|body_st... | StrongConnectivityTest | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrongConnectivityTest:
def testStronglyConnectedComponents(self):
"""Check known graph/component pairs."""
<|body_0|>
def testSubgraph(self):
"""Check that each SCC is an induced subgraph."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for graph, ... | stack_v2_sparse_classes_36k_train_014423 | 3,739 | permissive | [
{
"docstring": "Check known graph/component pairs.",
"name": "testStronglyConnectedComponents",
"signature": "def testStronglyConnectedComponents(self)"
},
{
"docstring": "Check that each SCC is an induced subgraph.",
"name": "testSubgraph",
"signature": "def testSubgraph(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001929 | Implement the Python class `StrongConnectivityTest` described below.
Class description:
Implement the StrongConnectivityTest class.
Method signatures and docstrings:
- def testStronglyConnectedComponents(self): Check known graph/component pairs.
- def testSubgraph(self): Check that each SCC is an induced subgraph. | Implement the Python class `StrongConnectivityTest` described below.
Class description:
Implement the StrongConnectivityTest class.
Method signatures and docstrings:
- def testStronglyConnectedComponents(self): Check known graph/component pairs.
- def testSubgraph(self): Check that each SCC is an induced subgraph.
<... | f985a988fdf7554aabb68e89f705942d13bd3ceb | <|skeleton|>
class StrongConnectivityTest:
def testStronglyConnectedComponents(self):
"""Check known graph/component pairs."""
<|body_0|>
def testSubgraph(self):
"""Check that each SCC is an induced subgraph."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrongConnectivityTest:
def testStronglyConnectedComponents(self):
"""Check known graph/component pairs."""
for graph, expectedoutput in self.knownpairs:
output = [list(C) for C in StronglyConnectedComponents(graph)]
for component in output:
component.so... | the_stack_v2_python_sparse | lib/PADS/StrongConnectivity.py | winex/pystream | train | 0 | |
28675f56e89776b8adf51ad1feb4f7c8186bc5e0 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * Profiles can be created in either online or offline mode, see below. | ProfilerServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilerServiceServicer:
"""Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * Profiles can be created in either online... | stack_v2_sparse_classes_36k_train_014424 | 4,186 | no_license | [
{
"docstring": "CreateProfile creates a new profile resource. In the online creation mode: * The server ensures that the new profiles are created at a constant rate per deployment, so the creation request may hang for some time until the next profile session is available. * The request may fail with ABORTED err... | 2 | stack_v2_sparse_classes_30k_train_015191 | Implement the Python class `ProfilerServiceServicer` described below.
Class description:
Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * P... | Implement the Python class `ProfilerServiceServicer` described below.
Class description:
Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * P... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class ProfilerServiceServicer:
"""Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * Profiles can be created in either online... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfilerServiceServicer:
"""Service for recording the profiling data from profiling agents running in the cloud or from an offline provider of profiling data. General guidelines: * Profiles for a single deployment must be created in ascending time order. * Profiles can be created in either online or offline m... | the_stack_v2_python_sparse | google/devtools/cloudprofiler/v2/profiler_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
a39273827da5a139d0ae4b1b1a2ee992980b92b8 | [
"super().__init__()\nself.flows = torch.nn.ModuleList()\nfor i in range(flows):\n self.flows += [ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_channels=global_channels, dropout_rate=dropo... | <|body_start_0|>
super().__init__()
self.flows = torch.nn.ModuleList()
for i in range(flows):
self.flows += [ResidualAffineCouplingLayer(in_channels=in_channels, hidden_channels=hidden_channels, kernel_size=kernel_size, base_dilation=base_dilation, layers=layers, stacks=1, global_cha... | Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://ar... | ResidualAffineCouplingBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_36k_train_014425 | 7,596 | permissive | [
{
"docstring": "Initilize ResidualAffineCouplingBlock module. Args: in_channels (int): Number of input channels. hidden_channels (int): Number of hidden channels. flows (int): Number of flows. kernel_size (int): Kernel size for WaveNet. base_dilation (int): Base dilation factor for WaveNet. layers (int): Number... | 2 | stack_v2_sparse_classes_30k_train_017102 | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | Implement the Python class `ResidualAffineCouplingBlock` described below.
Class description:
Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditiona... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualAffineCouplingBlock:
"""Residual affine coupling block module. This is a module of residual affine coupling block, which used as "Flow" in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning ... | the_stack_v2_python_sparse | espnet2/gan_tts/vits/residual_coupling.py | espnet/espnet | train | 7,242 |
97322b1a1663f996942b3ad36f20fed78340d95a | [
"super(MCBertForPretrainingModel, self).__init__()\nself.vis_feat_dim = vis_feat_dim\nself.spatial_size = spatial_size\nself.hidden_dim = hidden_dim\nself.cmb_feat_dim = cmb_feat_dim\nself.kernel_size = kernel_size\nself.mcbert_model = MCBertModel(vis_feat_dim=vis_feat_dim, spatial_size=spatial_size, hidden_dim=hid... | <|body_start_0|>
super(MCBertForPretrainingModel, self).__init__()
self.vis_feat_dim = vis_feat_dim
self.spatial_size = spatial_size
self.hidden_dim = hidden_dim
self.cmb_feat_dim = cmb_feat_dim
self.kernel_size = kernel_size
self.mcbert_model = MCBertModel(vis_fe... | Class implementing MCBERT model for unsupervised pre-training. | MCBertForPretrainingModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
<|body_0|>
def forward(self, vis_fe... | stack_v2_sparse_classes_36k_train_014426 | 2,272 | no_license | [
{
"docstring": "Initialize SkipGramDistNet.",
"name": "__init__",
"signature": "def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3)"
},
{
"docstring": "Forward Pass.",
"name": "forward",
"signature": "def forward(self, vis_feats, input... | 2 | stack_v2_sparse_classes_30k_train_005498 | Implement the Python class `MCBertForPretrainingModel` described below.
Class description:
Class implementing MCBERT model for unsupervised pre-training.
Method signatures and docstrings:
- def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3): Initialize SkipGramDis... | Implement the Python class `MCBertForPretrainingModel` described below.
Class description:
Class implementing MCBERT model for unsupervised pre-training.
Method signatures and docstrings:
- def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3): Initialize SkipGramDis... | fbfa1766dbc52cbf39036abe1a44f9315fad4a5c | <|skeleton|>
class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
<|body_0|>
def forward(self, vis_fe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MCBertForPretrainingModel:
"""Class implementing MCBERT model for unsupervised pre-training."""
def __init__(self, vis_feat_dim=2208, spatial_size=7, hidden_dim=768, cmb_feat_dim=16000, kernel_size=3):
"""Initialize SkipGramDistNet."""
super(MCBertForPretrainingModel, self).__init__()
... | the_stack_v2_python_sparse | mcbert/models/mcbert_for_pretraining.py | estebandito22/MC-BERT | train | 0 |
a0496adb71c318a6facb38a1e5125654ab563aec | [
"if head is None:\n return head\nnode = head\nvalue_list = []\nwhile node is not None:\n value_list.append(node.val)\n node = node.next\nleft_index = 0\nright_index = len(value_list) - 1\nroot_node = self.sortedListToBSTCore(value_list, left_index, right_index)\nreturn root_node",
"if value_list is None ... | <|body_start_0|>
if head is None:
return head
node = head
value_list = []
while node is not None:
value_list.append(node.val)
node = node.next
left_index = 0
right_index = len(value_list) - 1
root_node = self.sortedListToBSTCore... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedListToBSTCore(self, value_list, left, right):
"""try to assign equal nodes (not bigger than 1) to each left & right child; from big sub tree to child sub tree,... | stack_v2_sparse_classes_36k_train_014427 | 2,039 | no_license | [
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
},
{
"docstring": "try to assign equal nodes (not bigger than 1) to each left & right child; from big sub tree to child sub tree, keep the balance",
"name": "sort... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def sortedListToBSTCore(self, value_list, left, right): try to assign equal nodes (not bigger than 1) to ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def sortedListToBSTCore(self, value_list, left, right): try to assign equal nodes (not bigger than 1) to ... | 00abbb9909dc8a10f274a6e8605c665ba361fa3e | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedListToBSTCore(self, value_list, left, right):
"""try to assign equal nodes (not bigger than 1) to each left & right child; from big sub tree to child sub tree,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
if head is None:
return head
node = head
value_list = []
while node is not None:
value_list.append(node.val)
node = node.next
left_index = ... | the_stack_v2_python_sparse | 02_list/04list_to_tree/109.ConvertSortedListtoBinarySearchTree.py | harverywxu/algorithm_python | train | 0 | |
d49c7eddf657e4cadc22b5a982fdd661fd897d97 | [
"super().__init__(False, universeSettings)\nself.fastPeriod = fastPeriod\nself.slowPeriod = slowPeriod\nself.universeCount = universeCount\nself.tolerance = 0.01\nself.averages = {}",
"filtered = []\nfor cf in coarse:\n if cf.Symbol not in self.averages:\n self.averages[cf.Symbol] = self.SelectionData(c... | <|body_start_0|>
super().__init__(False, universeSettings)
self.fastPeriod = fastPeriod
self.slowPeriod = slowPeriod
self.universeCount = universeCount
self.tolerance = 0.01
self.averages = {}
<|end_body_0|>
<|body_start_1|>
filtered = []
for cf in coarse... | Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average | EmaCrossUniverseSelectionModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmaCrossUniverseSelectionModel:
"""Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average"""
def __init__(self, fastPeriod=100, slowPeriod=300, universeCount=500, universeSettin... | stack_v2_sparse_classes_36k_train_014428 | 4,147 | permissive | [
{
"docstring": "Initializes a new instance of the EmaCrossUniverseSelectionModel class Args: fastPeriod: Fast EMA period slowPeriod: Slow EMA period universeCount: Maximum number of members of this universe selection universeSettings: The settings used when adding symbols to the algorithm, specify null to use a... | 2 | stack_v2_sparse_classes_30k_train_018663 | Implement the Python class `EmaCrossUniverseSelectionModel` described below.
Class description:
Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `EmaCrossUniverseSelectionModel` described below.
Class description:
Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average
Method signatures and docstrings:
- def __init__(sel... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class EmaCrossUniverseSelectionModel:
"""Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average"""
def __init__(self, fastPeriod=100, slowPeriod=300, universeCount=500, universeSettin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmaCrossUniverseSelectionModel:
"""Provides an implementation of FundamentalUniverseSelectionModel that subscribes to symbols with the larger delta by percentage between the two exponential moving average"""
def __init__(self, fastPeriod=100, slowPeriod=300, universeCount=500, universeSettings=None):
... | the_stack_v2_python_sparse | Algorithm.Framework/Selection/EmaCrossUniverseSelectionModel.py | Capnode/Algoloop | train | 87 |
e88f654ea304df2031b12a019ec4815fc6c65348 | [
"super(GreedyPCTRAgent, self).__init__(action_space)\nself._choice_model = choice_model\nself._belief_state = belief_state",
"del reward\ndoc_obs = observation['doc']\nself._choice_model.score_documents(self._belief_state, doc_obs.values())\nslate = self.findBestDocuments(self._choice_model.scores)\nlogging.debug... | <|body_start_0|>
super(GreedyPCTRAgent, self).__init__(action_space)
self._choice_model = choice_model
self._belief_state = belief_state
<|end_body_0|>
<|body_start_1|>
del reward
doc_obs = observation['doc']
self._choice_model.score_documents(self._belief_state, doc_obs... | An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that have the highest probability of being clicked... | GreedyPCTRAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that ha... | stack_v2_sparse_classes_36k_train_014429 | 3,737 | permissive | [
{
"docstring": "Initializes a new greedy pCTR agent. Args: action_space: A gym.spaces object that specifies the format of actions belief_state: An instantiation of AbstractUserState assumed by the agent choice_model: An instantiation of AbstractChoiceModel assumed by the agent Default to a multinomial logit cho... | 3 | stack_v2_sparse_classes_30k_train_012844 | Implement the Python class `GreedyPCTRAgent` described below.
Class description:
An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopi... | Implement the Python class `GreedyPCTRAgent` described below.
Class description:
An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopi... | 63fcacb177a029196abe57910bde88f737d5cca0 | <|skeleton|>
class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that have the highes... | the_stack_v2_python_sparse | recsim/agents/greedy_pctr_agent.py | kittipatv/recsim-no-tf | train | 1 |
2a0a552bc1a695ff000a0896e199ca8ee1df5e7e | [
"super(Get_Reacheable_Waypoint, self).__init__(outcomes=['done'], input_keys=['pose_in', 'distance'], output_keys=['pose_out'])\nself._topic = '/robot_pose'\nself._sub = ProxySubscriberCached({self._topic: Pose})",
"mypose = self._sub.get_last_msg(self._topic)\nLogger.loginfo('my pose is:' + str(mypose))\nOut = P... | <|body_start_0|>
super(Get_Reacheable_Waypoint, self).__init__(outcomes=['done'], input_keys=['pose_in', 'distance'], output_keys=['pose_out'])
self._topic = '/robot_pose'
self._sub = ProxySubscriberCached({self._topic: Pose})
<|end_body_0|>
<|body_start_1|>
mypose = self._sub.get_last_... | Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position found | Get_Reacheable_Waypoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Get_Reacheable_Waypoint:
"""Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position found"""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_014430 | 2,203 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Execute this state",
"name": "execute",
"signature": "def execute(self, userdata)"
}
] | 2 | null | Implement the Python class `Get_Reacheable_Waypoint` described below.
Class description:
Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position... | Implement the Python class `Get_Reacheable_Waypoint` described below.
Class description:
Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position... | fcb55d274331915cd39d7d444546f17a39f85a44 | <|skeleton|>
class Get_Reacheable_Waypoint:
"""Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position found"""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Get_Reacheable_Waypoint:
"""Get a position close enough to reach a point without stepping on it #> Distance float decalage distance to point #> pose_in geometry_msgs.Pose/Point Position to reach #< pose_out geometry_msgs.Pose Output position <= done position found"""
def __init__(self):
"""Constr... | the_stack_v2_python_sparse | sara_flexbe_states/src/sara_flexbe_states/get_reachable_waypoint.py | WalkingMachine/sara_behaviors | train | 5 |
931b328fbaf30efd4dc3ac2ffe55b64c5bb4c7a6 | [
"HyppopySolver.__init__(self, project)\nself._searchspace = None\nself.candidates_list = list()",
"self._add_member('max_iterations', int)\nself._add_hyperparameter_signature(name='domain', dtype=str, options=['uniform', 'categorical'])\nself._add_hyperparameter_signature(name='data', dtype=list)\nself._add_hyper... | <|body_start_0|>
HyppopySolver.__init__(self, project)
self._searchspace = None
self.candidates_list = list()
<|end_body_0|>
<|body_start_1|>
self._add_member('max_iterations', int)
self._add_hyperparameter_signature(name='domain', dtype=str, options=['uniform', 'categorical'])
... | OptunaSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
<|body_0|>
def define_interface(self):
"""This function is called when HyppopySolver.__init__ function fini... | stack_v2_sparse_classes_36k_train_014431 | 6,091 | no_license | [
{
"docstring": "The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None",
"name": "__init__",
"signature": "def __init__(self, project=None)"
},
{
"docstring": "This function is called when HyppopySolver.__init__ function finished. Child classes ... | 6 | stack_v2_sparse_classes_30k_train_016518 | Implement the Python class `OptunaSolver` described below.
Class description:
Implement the OptunaSolver class.
Method signatures and docstrings:
- def __init__(self, project=None): The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None
- def define_interface(self): ... | Implement the Python class `OptunaSolver` described below.
Class description:
Implement the OptunaSolver class.
Method signatures and docstrings:
- def __init__(self, project=None): The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None
- def define_interface(self): ... | 254adacd6164aceca27794611f57a7ab82e4dc29 | <|skeleton|>
class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
<|body_0|>
def define_interface(self):
"""This function is called when HyppopySolver.__init__ function fini... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
HyppopySolver.__init__(self, project)
self._searchspace = None
self.candidates_list = list()
def define_interface... | the_stack_v2_python_sparse | hyppopy/solvers/OptunaSolver.py | MIC-DKFZ/Hyppopy | train | 27 | |
a5e816f3195a7a9996b348e880b1b915b3a0b198 | [
"if not text1 or not text2:\n return 0\nm, n = (len(text1), len(text2))\ndp = [[0] * (n + 1) for _ in range(m + 1)]\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if text1[i - 1] == text2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i - 1]... | <|body_start_0|>
if not text1 or not text2:
return 0
m, n = (len(text1), len(text2))
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1, text2):
""":type text1: str :type text2: str :rtype: int"""
<|body_0|>
def longestCommonSubsequence(self, text1, text2):
""":type text1: str :type text2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_014432 | 1,658 | no_license | [
{
"docstring": ":type text1: str :type text2: str :rtype: int",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1, text2)"
},
{
"docstring": ":type text1: str :type text2: str :rtype: int",
"name": "longestCommonSubsequence",
"signature": "def lon... | 2 | stack_v2_sparse_classes_30k_train_019128 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1, text2): :type text1: str :type text2: str :rtype: int
- def longestCommonSubsequence(self, text1, text2): :type text1: str :type text2: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonSubsequence(self, text1, text2): :type text1: str :type text2: str :rtype: int
- def longestCommonSubsequence(self, text1, text2): :type text1: str :type text2: ... | c162817f717b78997197649c084c27af48c3fd6f | <|skeleton|>
class Solution:
def longestCommonSubsequence(self, text1, text2):
""":type text1: str :type text2: str :rtype: int"""
<|body_0|>
def longestCommonSubsequence(self, text1, text2):
""":type text1: str :type text2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonSubsequence(self, text1, text2):
""":type text1: str :type text2: str :rtype: int"""
if not text1 or not text2:
return 0
m, n = (len(text1), len(text2))
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
... | the_stack_v2_python_sparse | Week_06/1143.最长公共子序列.py | dream201188/algorithm017 | train | 1 | |
555c8a6f8091c7e47c2c87f6762c78fae3129f34 | [
"super().__init__()\nif out_channels % in_channels != 0:\n raise ValueError(f'16 should be divisible by in_channels, got in_channels={in_channels}.')\nself.in_channels = in_channels\nself.act_function = act(inplace=True)\nself.conv_block = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=5, padding... | <|body_start_0|>
super().__init__()
if out_channels % in_channels != 0:
raise ValueError(f'16 should be divisible by in_channels, got in_channels={in_channels}.')
self.in_channels = in_channels
self.act_function = act(inplace=True)
self.conv_block = nn.Sequential(nn.C... | Input Transition Block. | InputTransition | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputTransition:
"""Input Transition Block."""
def __init__(self, in_channels: int, out_channels: int=16, act: nn.Module=nn.ELU, bias: bool=False):
"""Parameters ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. act : nn.Module Activ... | stack_v2_sparse_classes_36k_train_014433 | 8,968 | permissive | [
{
"docstring": "Parameters ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. act : nn.Module Activation function. bias : bool Whether to use bias.",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, out_channels: int=16, act: nn.Mod... | 2 | stack_v2_sparse_classes_30k_train_009365 | Implement the Python class `InputTransition` described below.
Class description:
Input Transition Block.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int=16, act: nn.Module=nn.ELU, bias: bool=False): Parameters ---------- in_channels : int Number of input channels. out_channe... | Implement the Python class `InputTransition` described below.
Class description:
Input Transition Block.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int=16, act: nn.Module=nn.ELU, bias: bool=False): Parameters ---------- in_channels : int Number of input channels. out_channe... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class InputTransition:
"""Input Transition Block."""
def __init__(self, in_channels: int, out_channels: int=16, act: nn.Module=nn.ELU, bias: bool=False):
"""Parameters ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. act : nn.Module Activ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputTransition:
"""Input Transition Block."""
def __init__(self, in_channels: int, out_channels: int=16, act: nn.Module=nn.ELU, bias: bool=False):
"""Parameters ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. act : nn.Module Activation functio... | the_stack_v2_python_sparse | mridc/collections/segmentation/models/vnet_base/vnet_block.py | wdika/mridc | train | 40 |
28de5fe99b8805911f53ee9c31f5aa62e82436a8 | [
"self.in_channels = 1\nself.out_channels = 2\nself.height = 512\nself.width = 512\nself.rare_class = 0\nself.frequencies = [0.07, 0.93]\nself.bundle_size = 20\nself.base_dir = Path(lis_dir)\nself.train_dir = self.base_dir / 'training'\nself.val_dir = self.base_dir / 'validation'\nself.x_n_pfx = 'x-ntl-'\nself.y_n_p... | <|body_start_0|>
self.in_channels = 1
self.out_channels = 2
self.height = 512
self.width = 512
self.rare_class = 0
self.frequencies = [0.07, 0.93]
self.bundle_size = 20
self.base_dir = Path(lis_dir)
self.train_dir = self.base_dir / 'training'
... | Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command | LiSAdapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiSAdapter:
"""Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command"""
def __init__(self, lis_dir, trn_lim=-1):
"""Constructor for the LiS A... | stack_v2_sparse_classes_36k_train_014434 | 3,999 | no_license | [
{
"docstring": "Constructor for the LiS Adapter object Takes root lis directory on this machine and optionally a limit on how many bundles to use",
"name": "__init__",
"signature": "def __init__(self, lis_dir, trn_lim=-1)"
},
{
"docstring": "Load a bundle from disk Provide location, prefixes, an... | 4 | stack_v2_sparse_classes_30k_train_012469 | Implement the Python class `LiSAdapter` described below.
Class description:
Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command
Method signatures and docstrings:
- def __ini... | Implement the Python class `LiSAdapter` described below.
Class description:
Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command
Method signatures and docstrings:
- def __ini... | 4a74a86740196f927ee3f6519983393a083c3083 | <|skeleton|>
class LiSAdapter:
"""Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command"""
def __init__(self, lis_dir, trn_lim=-1):
"""Constructor for the LiS A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiSAdapter:
"""Adapter for Liver Segmentation Data-set (ignoring tumors for now) Keeps track of number of bundles stored on disk, and frequencies of the classes. Returns a bundle of the requested type on command"""
def __init__(self, lis_dir, trn_lim=-1):
"""Constructor for the LiS Adapter object... | the_stack_v2_python_sparse | learning/adapters/lisadapter.py | neheller/eus18 | train | 0 |
d6f5bde319ef84f1b3254d18583650f8e7e07f5b | [
"super(Deflection, self).__init__()\nself.time = self.start\nself.level = {}",
"level = '-' if not self.level else min(self.level.itervalues())\nlead = '-' if not self.level else min(self.level, key=self.level.get)\nreturn '{0} ({1}, {2})'.format(super(Deflection, self).__str__(), level, lead)"
] | <|body_start_0|>
super(Deflection, self).__init__()
self.time = self.start
self.level = {}
<|end_body_0|>
<|body_start_1|>
level = '-' if not self.level else min(self.level.itervalues())
lead = '-' if not self.level else min(self.level, key=self.level.get)
return '{0} ({... | This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal. | Deflection | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deflection:
"""This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal."""
def __init__(self):
"""Creates a new Defl... | stack_v2_sparse_classes_36k_train_014435 | 1,698 | permissive | [
{
"docstring": "Creates a new Deflection instance, at level 0",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Obtains the representation of the observable as a character string.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `Deflection` described below.
Class description:
This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal.
Method signatures... | Implement the Python class `Deflection` described below.
Class description:
This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal.
Method signatures... | c6f1648a148335babc0a26d8a589120616327548 | <|skeleton|>
class Deflection:
"""This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal."""
def __init__(self):
"""Creates a new Defl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Deflection:
"""This class represents a signal deviation consistent with the electrical activity of the cardiac muscle fibers. It is associated with a certain energy level derived from the wavelet decomposition/reconstruction of the signal."""
def __init__(self):
"""Creates a new Deflection instan... | the_stack_v2_python_sparse | kardioml/segmentation/teijeiro/knowledge/observables/Spectrum.py | arianasatryan/physionet-challenge-2020 | train | 0 |
81359baebcad64695e37836e3996cf4e4aba69bb | [
"if os.path.exists(xml_file) and os.path.isfile(xml_file):\n content = fs.file_get_contents(xml_file)\n self.xsd_validate(content)\nelse:\n raise InputError(0, [], \"File doesn't exists: {0}\".format(xml_file))",
"if xml_str not in (None, ''):\n doc = etree.fromstring(xml_str)\n self._xml_schema.as... | <|body_start_0|>
if os.path.exists(xml_file) and os.path.isfile(xml_file):
content = fs.file_get_contents(xml_file)
self.xsd_validate(content)
else:
raise InputError(0, [], "File doesn't exists: {0}".format(xml_file))
<|end_body_0|>
<|body_start_1|>
if xml_st... | Class XMLValidate | XMLValidate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLValidate:
"""Class XMLValidate"""
def xsd_validate_file(self, xml_file):
"""Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError"""
<|body_0|>
def xsd_validate(self, xml_str):
"""Metho... | stack_v2_sparse_classes_36k_train_014436 | 2,019 | permissive | [
{
"docstring": "Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError",
"name": "xsd_validate_file",
"signature": "def xsd_validate_file(self, xml_file)"
},
{
"docstring": "Method validates XML string according to XSD Arg... | 4 | null | Implement the Python class `XMLValidate` described below.
Class description:
Class XMLValidate
Method signatures and docstrings:
- def xsd_validate_file(self, xml_file): Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError
- def xsd_validate(... | Implement the Python class `XMLValidate` described below.
Class description:
Class XMLValidate
Method signatures and docstrings:
- def xsd_validate_file(self, xml_file): Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError
- def xsd_validate(... | 79b698998bac9a04b5a345e5d3212c87b5564af3 | <|skeleton|>
class XMLValidate:
"""Class XMLValidate"""
def xsd_validate_file(self, xml_file):
"""Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError"""
<|body_0|>
def xsd_validate(self, xml_str):
"""Metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XMLValidate:
"""Class XMLValidate"""
def xsd_validate_file(self, xml_file):
"""Method validates XML file according to XSD Args: xml_file (str): filename including path Returns: void Raises: error: InputError"""
if os.path.exists(xml_file) and os.path.isfile(xml_file):
content ... | the_stack_v2_python_sparse | src/hydratk/lib/data/xml.py | hydratk/hydratk-lib-network | train | 0 |
3a22897ae9fbf3a754be03343fbd247a0f715fc0 | [
"expected = [0, 20, 50, 80, 100]\npercentiles = np.array([20, 50, 80])\nresult = insert_lower_and_upper_endpoint_to_1d_array(percentiles, 0, 100)\nself.assertIsInstance(result, np.ndarray)\nself.assertArrayAlmostEqual(result, expected)",
"percentiles = np.array([[-40, 200, 1000], [-40, 200, 1000]])\nmsg = 'Expect... | <|body_start_0|>
expected = [0, 20, 50, 80, 100]
percentiles = np.array([20, 50, 80])
result = insert_lower_and_upper_endpoint_to_1d_array(percentiles, 0, 100)
self.assertIsInstance(result, np.ndarray)
self.assertArrayAlmostEqual(result, expected)
<|end_body_0|>
<|body_start_1|>... | Test the insert_lower_and_upper_endpoint_to_1d_array. | Test_insert_lower_and_upper_endpoint_to_1d_array | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_insert_lower_and_upper_endpoint_to_1d_array:
"""Test the insert_lower_and_upper_endpoint_to_1d_array."""
def test_basic(self):
"""Test that the result is a numpy array with the expected contents."""
<|body_0|>
def test_2d_example(self):
"""Test 2D input resu... | stack_v2_sparse_classes_36k_train_014437 | 28,421 | permissive | [
{
"docstring": "Test that the result is a numpy array with the expected contents.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test 2D input results in expected error",
"name": "test_2d_example",
"signature": "def test_2d_example(self)"
}
] | 2 | null | Implement the Python class `Test_insert_lower_and_upper_endpoint_to_1d_array` described below.
Class description:
Test the insert_lower_and_upper_endpoint_to_1d_array.
Method signatures and docstrings:
- def test_basic(self): Test that the result is a numpy array with the expected contents.
- def test_2d_example(self... | Implement the Python class `Test_insert_lower_and_upper_endpoint_to_1d_array` described below.
Class description:
Test the insert_lower_and_upper_endpoint_to_1d_array.
Method signatures and docstrings:
- def test_basic(self): Test that the result is a numpy array with the expected contents.
- def test_2d_example(self... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_insert_lower_and_upper_endpoint_to_1d_array:
"""Test the insert_lower_and_upper_endpoint_to_1d_array."""
def test_basic(self):
"""Test that the result is a numpy array with the expected contents."""
<|body_0|>
def test_2d_example(self):
"""Test 2D input resu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_insert_lower_and_upper_endpoint_to_1d_array:
"""Test the insert_lower_and_upper_endpoint_to_1d_array."""
def test_basic(self):
"""Test that the result is a numpy array with the expected contents."""
expected = [0, 20, 50, 80, 100]
percentiles = np.array([20, 50, 80])
... | the_stack_v2_python_sparse | improver_tests/ensemble_copula_coupling/test_utilities.py | metoppv/improver | train | 101 |
cfdf639de869b1e733da013226e10d9ef34e155c | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service for configuring logs-based metrics. | MetricsServiceV2Servicer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricsServiceV2Servicer:
"""Service for configuring logs-based metrics."""
def ListLogMetrics(self, request, context):
"""Lists logs-based metrics."""
<|body_0|>
def GetLogMetric(self, request, context):
"""Gets a logs-based metric."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_014438 | 6,690 | permissive | [
{
"docstring": "Lists logs-based metrics.",
"name": "ListLogMetrics",
"signature": "def ListLogMetrics(self, request, context)"
},
{
"docstring": "Gets a logs-based metric.",
"name": "GetLogMetric",
"signature": "def GetLogMetric(self, request, context)"
},
{
"docstring": "Create... | 5 | null | Implement the Python class `MetricsServiceV2Servicer` described below.
Class description:
Service for configuring logs-based metrics.
Method signatures and docstrings:
- def ListLogMetrics(self, request, context): Lists logs-based metrics.
- def GetLogMetric(self, request, context): Gets a logs-based metric.
- def Cr... | Implement the Python class `MetricsServiceV2Servicer` described below.
Class description:
Service for configuring logs-based metrics.
Method signatures and docstrings:
- def ListLogMetrics(self, request, context): Lists logs-based metrics.
- def GetLogMetric(self, request, context): Gets a logs-based metric.
- def Cr... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class MetricsServiceV2Servicer:
"""Service for configuring logs-based metrics."""
def ListLogMetrics(self, request, context):
"""Lists logs-based metrics."""
<|body_0|>
def GetLogMetric(self, request, context):
"""Gets a logs-based metric."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricsServiceV2Servicer:
"""Service for configuring logs-based metrics."""
def ListLogMetrics(self, request, context):
"""Lists logs-based metrics."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError(... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/third_party/logging_v2/proto/logging_metrics_pb2_grpc.py | twistedpair/google-cloud-sdk | train | 58 |
c0e75dd9bc59ac46487d67c3844e622d6e0a866a | [
"parser = parent.add_parser('run', help='Run container from image')\nCreateArguments.add_arguments(parser)\nparser.add_argument('image', nargs=1, help='source image id.')\nparser.add_argument('command', nargs=parent.REMAINDER, help='command and args to run.')\nparser.set_defaults(class_=cls, method='run')",
"supe... | <|body_start_0|>
parser = parent.add_parser('run', help='Run container from image')
CreateArguments.add_arguments(parser)
parser.add_argument('image', nargs=1, help='source image id.')
parser.add_argument('command', nargs=parent.REMAINDER, help='command and args to run.')
parser.... | Class for running a command in a container. | Run | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Run:
"""Class for running a command in a container."""
def subparser(cls, parent):
"""Add Run command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct Run class."""
<|body_1|>
def run(self):
"""Run container."""
... | stack_v2_sparse_classes_36k_train_014439 | 2,426 | permissive | [
{
"docstring": "Add Run command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Construct Run class.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Run container.",
"name": "run",
"sig... | 3 | stack_v2_sparse_classes_30k_train_004959 | Implement the Python class `Run` described below.
Class description:
Class for running a command in a container.
Method signatures and docstrings:
- def subparser(cls, parent): Add Run command to parent parser.
- def __init__(self, args): Construct Run class.
- def run(self): Run container. | Implement the Python class `Run` described below.
Class description:
Class for running a command in a container.
Method signatures and docstrings:
- def subparser(cls, parent): Add Run command to parent parser.
- def __init__(self, args): Construct Run class.
- def run(self): Run container.
<|skeleton|>
class Run:
... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class Run:
"""Class for running a command in a container."""
def subparser(cls, parent):
"""Add Run command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct Run class."""
<|body_1|>
def run(self):
"""Run container."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Run:
"""Class for running a command in a container."""
def subparser(cls, parent):
"""Add Run command to parent parser."""
parser = parent.add_parser('run', help='Run container from image')
CreateArguments.add_arguments(parser)
parser.add_argument('image', nargs=1, help='s... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/run_action.py | 4383/python-podman | train | 0 |
93a7c2a9db6cdc0847db634aad809ecc038fe1ec | [
"super().__init__(base_url=base_url, proxy=proxy, verify=verify)\nself.api_key = api_key\nif self.api_key:\n self._headers = {'Key': self.api_key}",
"request_params: Dict[str, Any] = {}\nif offset:\n request_params['offset'] = offset\nif max_results:\n request_params['limit'] = max_results\nif start_time... | <|body_start_0|>
super().__init__(base_url=base_url, proxy=proxy, verify=verify)
self.api_key = api_key
if self.api_key:
self._headers = {'Key': self.api_key}
<|end_body_0|>
<|body_start_1|>
request_params: Dict[str, Any] = {}
if offset:
request_params['o... | This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events. | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events."""
def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]):
... | stack_v2_sparse_classes_36k_train_014440 | 14,388 | permissive | [
{
"docstring": "This function initializes the connection with the API server by collecting curcial information from the users.",
"name": "__init__",
"signature": "def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool])"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_015698 | Implement the Python class `Client` described below.
Class description:
This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.
Method signatures and docstrings:
- def __init__(self, api_key: Optional[str], base_url: ... | Implement the Python class `Client` described below.
Class description:
This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.
Method signatures and docstrings:
- def __init__(self, api_key: Optional[str], base_url: ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Client:
"""This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events."""
def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
"""This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events."""
def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]):
"""This fu... | the_stack_v2_python_sparse | Packs/Zerohack_XDR/Integrations/ZerohackXDR/ZerohackXDR.py | demisto/content | train | 1,023 |
a72f672b4466b2e25908879f1c929d6864afdc91 | [
"if isinstance(key, int):\n return AccessType(key)\nif key not in AccessType._member_map_:\n return extend_enum(AccessType, key, default)\nreturn AccessType[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 14 <= value <=... | <|body_start_0|>
if isinstance(key, int):
return AccessType(key)
if key not in AccessType._member_map_:
return extend_enum(AccessType, key, default)
return AccessType[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
... | [AccessType] Access Technology Type Option Type Values | AccessType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_014441 | 2,583 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'AccessType'"
},
{
"docstring": "Lookup function used when value is not found. ... | 2 | stack_v2_sparse_classes_30k_train_006228 | Implement the Python class `AccessType` described below.
Class description:
[AccessType] Access Technology Type Option Type Values
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'AccessType': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | Implement the Python class `AccessType` described below.
Class description:
[AccessType] Access Technology Type Option Type Values
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'AccessType': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
... | the_stack_v2_python_sparse | pcapkit/const/mh/access_type.py | JarryShaw/PyPCAPKit | train | 204 |
2ecd56bafe05303196afacdc6ff5eaeb468638fd | [
"f = open(file_trace, 'r')\ncount = 0\ntxt = f.readlines()\nf.close()\ntopic_dict = {}\ntopic_unpro_dict = {}\nword = []\nword_value = []\nfor line in txt:\n if 'Topic' in line:\n line_clean = line.split(':')\n line_clean_clean = line_clean[0].split()\n name = ''.join(line_clean_clean)\n ... | <|body_start_0|>
f = open(file_trace, 'r')
count = 0
txt = f.readlines()
f.close()
topic_dict = {}
topic_unpro_dict = {}
word = []
word_value = []
for line in txt:
if 'Topic' in line:
line_clean = line.split(':')
... | 主题两两之间的相似,并输出 | lda | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
<|body_0|>
def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50):
"""统计词并输出"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_014442 | 2,462 | no_license | [
{
"docstring": "打开模型并保存为字典",
"name": "f_open_file",
"signature": "def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt')"
},
{
"docstring": "统计词并输出",
"name": "f_static_word",
"signature": "def f_static_word(static_word_dict, static_word_topicNum=30, static... | 4 | stack_v2_sparse_classes_30k_train_003060 | Implement the Python class `lda` described below.
Class description:
主题两两之间的相似,并输出
Method signatures and docstrings:
- def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'): 打开模型并保存为字典
- def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50): 统计词并输出
- def... | Implement the Python class `lda` described below.
Class description:
主题两两之间的相似,并输出
Method signatures and docstrings:
- def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'): 打开模型并保存为字典
- def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50): 统计词并输出
- def... | 309f6fecf9b8ee9c69472c0aedb0004c00e8f682 | <|skeleton|>
class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
<|body_0|>
def f_static_word(static_word_dict, static_word_topicNum=30, static_word_wordNum=50):
"""统计词并输出"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class lda:
"""主题两两之间的相似,并输出"""
def f_open_file(word_number=50, file_trace='./lda/iphone5s/diff-sampling/model-1.txt'):
"""打开模型并保存为字典"""
f = open(file_trace, 'r')
count = 0
txt = f.readlines()
f.close()
topic_dict = {}
topic_unpro_dict = {}
word = ... | the_stack_v2_python_sparse | 20140814/topic_combination.py | KAI-YIP/nlp | train | 2 |
67ed960d956815c07bbc2ce3cbbfbc5b040720bb | [
"self.conv1 = nn.Conv2d(4, 32, 8, 4)\nself.conv2 = nn.Conv2d(32, 64, 4, 2)\nself.conv3 = nn.Conv2d(64, 64, 3, 1)\nshape = self.observation_space.shape[1:]\nfor c in [self.conv1, self.conv2, self.conv3]:\n shape = conv_out_shape(shape, c)\nself.nunits = 64 * np.prod(shape)\nself.fc = nn.Linear(self.nunits, 512)\n... | <|body_start_0|>
self.conv1 = nn.Conv2d(4, 32, 8, 4)
self.conv2 = nn.Conv2d(32, 64, 4, 2)
self.conv3 = nn.Conv2d(64, 64, 3, 1)
shape = self.observation_space.shape[1:]
for c in [self.conv1, self.conv2, self.conv3]:
shape = conv_out_shape(shape, c)
self.nunits ... | Deep network from https://www.nature.com/articles/nature14236. | NatureDQN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NatureDQN:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.conv1 = nn.Conv2d(4, 32, 8, 4... | stack_v2_sparse_classes_36k_train_014443 | 10,080 | no_license | [
{
"docstring": "Build network.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014298 | Implement the Python class `NatureDQN` described below.
Class description:
Deep network from https://www.nature.com/articles/nature14236.
Method signatures and docstrings:
- def build(self): Build network.
- def forward(self, x): Forward. | Implement the Python class `NatureDQN` described below.
Class description:
Deep network from https://www.nature.com/articles/nature14236.
Method signatures and docstrings:
- def build(self): Build network.
- def forward(self, x): Forward.
<|skeleton|>
class NatureDQN:
"""Deep network from https://www.nature.com/... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class NatureDQN:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NatureDQN:
"""Deep network from https://www.nature.com/articles/nature14236."""
def build(self):
"""Build network."""
self.conv1 = nn.Conv2d(4, 32, 8, 4)
self.conv2 = nn.Conv2d(32, 64, 4, 2)
self.conv3 = nn.Conv2d(64, 64, 3, 1)
shape = self.observation_space.shape[... | the_stack_v2_python_sparse | dl/rl/algorithms/ppo.py | cbschaff/dl | train | 1 |
8c7f2bcc24e4b8112a6199ec2b4cd0c1653310b5 | [
"if 'owner' in self.request.data:\n self.update_owners(serializer)\nsuper(FeedDetail, self).perform_update(serializer)",
"feed = self.get_object()\nowners = feed.owner.values('username')\nusername = self.request.data.pop('owner')\nif {'username': username} not in owners:\n new_owner = serializer.validate_ne... | <|body_start_0|>
if 'owner' in self.request.data:
self.update_owners(serializer)
super(FeedDetail, self).perform_update(serializer)
<|end_body_0|>
<|body_start_1|>
feed = self.get_object()
owners = feed.owner.values('username')
username = self.request.data.pop('owner... | A feed view. | FeedDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedDetail:
"""A feed view."""
def perform_update(self, serializer):
"""Overriden to update feed's owners if requested by a PUT request."""
<|body_0|>
def update_owners(self, serializer):
"""Custom method to update the feed's owners."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_014444 | 21,257 | permissive | [
{
"docstring": "Overriden to update feed's owners if requested by a PUT request.",
"name": "perform_update",
"signature": "def perform_update(self, serializer)"
},
{
"docstring": "Custom method to update the feed's owners.",
"name": "update_owners",
"signature": "def update_owners(self, ... | 3 | null | Implement the Python class `FeedDetail` described below.
Class description:
A feed view.
Method signatures and docstrings:
- def perform_update(self, serializer): Overriden to update feed's owners if requested by a PUT request.
- def update_owners(self, serializer): Custom method to update the feed's owners.
- def re... | Implement the Python class `FeedDetail` described below.
Class description:
A feed view.
Method signatures and docstrings:
- def perform_update(self, serializer): Overriden to update feed's owners if requested by a PUT request.
- def update_owners(self, serializer): Custom method to update the feed's owners.
- def re... | 20d3eedf20610af9182f6cca8db8f0b3546b5336 | <|skeleton|>
class FeedDetail:
"""A feed view."""
def perform_update(self, serializer):
"""Overriden to update feed's owners if requested by a PUT request."""
<|body_0|>
def update_owners(self, serializer):
"""Custom method to update the feed's owners."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedDetail:
"""A feed view."""
def perform_update(self, serializer):
"""Overriden to update feed's owners if requested by a PUT request."""
if 'owner' in self.request.data:
self.update_owners(serializer)
super(FeedDetail, self).perform_update(serializer)
def updat... | the_stack_v2_python_sparse | chris_backend/feeds/views.py | FNNDSC/ChRIS_ultron_backEnd | train | 36 |
4968edca5bf2dbe7f70859c115e0fd0ba798ea34 | [
"if hasattr(view_func.__class__, 'json') and view_func.__class__.json:\n request.response_type = 'json'\nelse:\n request.response_type = 'html'",
"if request.response_type == 'json':\n code = 500\n level = 'error'\n data = None\n if isinstance(exception, PermissionDenied):\n messages = '权... | <|body_start_0|>
if hasattr(view_func.__class__, 'json') and view_func.__class__.json:
request.response_type = 'json'
else:
request.response_type = 'html'
<|end_body_0|>
<|body_start_1|>
if request.response_type == 'json':
code = 500
level = 'erro... | ExceptionProcessingMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionProcessingMiddleware:
def process_view(self, request, view_func, *view_args, **view_kwargs):
"""call before view executing"""
<|body_0|>
def process_exception(self, request, exception):
"""Call when raise an exception"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_014445 | 2,532 | no_license | [
{
"docstring": "call before view executing",
"name": "process_view",
"signature": "def process_view(self, request, view_func, *view_args, **view_kwargs)"
},
{
"docstring": "Call when raise an exception",
"name": "process_exception",
"signature": "def process_exception(self, request, exce... | 2 | stack_v2_sparse_classes_30k_train_016588 | Implement the Python class `ExceptionProcessingMiddleware` described below.
Class description:
Implement the ExceptionProcessingMiddleware class.
Method signatures and docstrings:
- def process_view(self, request, view_func, *view_args, **view_kwargs): call before view executing
- def process_exception(self, request,... | Implement the Python class `ExceptionProcessingMiddleware` described below.
Class description:
Implement the ExceptionProcessingMiddleware class.
Method signatures and docstrings:
- def process_view(self, request, view_func, *view_args, **view_kwargs): call before view executing
- def process_exception(self, request,... | 5b538e85606cd22c34ac10f53438fc0d3ff131a0 | <|skeleton|>
class ExceptionProcessingMiddleware:
def process_view(self, request, view_func, *view_args, **view_kwargs):
"""call before view executing"""
<|body_0|>
def process_exception(self, request, exception):
"""Call when raise an exception"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExceptionProcessingMiddleware:
def process_view(self, request, view_func, *view_args, **view_kwargs):
"""call before view executing"""
if hasattr(view_func.__class__, 'json') and view_func.__class__.json:
request.response_type = 'json'
else:
request.response_typ... | the_stack_v2_python_sparse | sandbook/base/middleware.py | lwaxx/novel | train | 0 | |
3ea614c150c99296cac7392f5825d260e1d2273a | [
"self.__include_deps_supply = include_deps_supply\nif closure:\n self.__transform_pre = GraphAlgorithms.transitive_closure\nelse:\n self.__transform_pre = lambda x: x\nif sort:\n self.__transform_post = sorted\nelse:\n self.__transform_post = lambda x: x",
"args_set = set(args)\nedge_list = self.__tra... | <|body_start_0|>
self.__include_deps_supply = include_deps_supply
if closure:
self.__transform_pre = GraphAlgorithms.transitive_closure
else:
self.__transform_pre = lambda x: x
if sort:
self.__transform_post = sorted
else:
self.__tr... | FileIncludeDepsListerFacade | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_36k_train_014446 | 2,930 | permissive | [
{
"docstring": "@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param sort: if True, return output sorted by filenames @type sort: Boolean",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_009458 | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | Implement the Python class `FileIncludeDepsListerFacade` described below.
Class description:
Implement the FileIncludeDepsListerFacade class.
Method signatures and docstrings:
- def __init__(self, include_deps_supply, closure, sort): @param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param ... | d58680ef7d6bdc8ef518860d5d13a5acc0d01758 | <|skeleton|>
class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileIncludeDepsListerFacade:
def __init__(self, include_deps_supply, closure, sort):
"""@param include_deps_supply: @type include_deps_supply: FileIncludeDepsSupply @param closure: if True, consider transitive closure of dependencies, otherwise only direct dependencies @type closure: Boolean @param so... | the_stack_v2_python_sparse | cpp/incl_deps/include_deps_util.py | btc-ag/revengtools | train | 2 | |
6bed7b53d874153f576069edb90ed47a800e7013 | [
"if wwan:\n self.iface = system.interfaces.WwanInterface(iface)\n self.iface.configure(apn=wwan_apn, pin=wwan_pin)\nelse:\n self.iface = system.interfaces.Interface(iface)\nself.ip = None\nself.connect_timeout = 10\nself.connect_retry_interval = 10\nself.connected = False\nself.max_connection_duration = 30... | <|body_start_0|>
if wwan:
self.iface = system.interfaces.WwanInterface(iface)
self.iface.configure(apn=wwan_apn, pin=wwan_pin)
else:
self.iface = system.interfaces.Interface(iface)
self.ip = None
self.connect_timeout = 10
self.connect_retry_int... | Simple network connection representation | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
"""Simple network connection representation"""
def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin=''):
"""Initialize a new network instance."""
<|body_0|>
def connect(self, max_attempts=3):
"""Initiates a connection to the network."""
<|... | stack_v2_sparse_classes_36k_train_014447 | 4,241 | no_license | [
{
"docstring": "Initialize a new network instance.",
"name": "__init__",
"signature": "def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin='')"
},
{
"docstring": "Initiates a connection to the network.",
"name": "connect",
"signature": "def connect(self, max_attempts=3)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_014655 | Implement the Python class `Network` described below.
Class description:
Simple network connection representation
Method signatures and docstrings:
- def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin=''): Initialize a new network instance.
- def connect(self, max_attempts=3): Initiates a connection to the n... | Implement the Python class `Network` described below.
Class description:
Simple network connection representation
Method signatures and docstrings:
- def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin=''): Initialize a new network instance.
- def connect(self, max_attempts=3): Initiates a connection to the n... | c859bddc445600e7cfaebffcdfcc086d70d18607 | <|skeleton|>
class Network:
"""Simple network connection representation"""
def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin=''):
"""Initialize a new network instance."""
<|body_0|>
def connect(self, max_attempts=3):
"""Initiates a connection to the network."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Network:
"""Simple network connection representation"""
def __init__(self, iface, wwan=False, wwan_apn='', wwan_pin=''):
"""Initialize a new network instance."""
if wwan:
self.iface = system.interfaces.WwanInterface(iface)
self.iface.configure(apn=wwan_apn, pin=wwa... | the_stack_v2_python_sparse | dlmclient/network.py | rguenthe/dlms-client | train | 0 |
79c10b0a95283500f970c23a3d23d0483d8b998b | [
"try:\n nova = osclients.Clients(self.context['admin']['credential']).nova()\n self.context['flavor'] = nova.flavors.create(name=self.config.get('flavor_name', 'rally_test_flavor'), ram=self.config.get('ram', 1), vcpus=self.config.get('vcpus', 1), disk=self.config.get('disk', 1)).to_dict()\n LOG.debug(\"Fl... | <|body_start_0|>
try:
nova = osclients.Clients(self.context['admin']['credential']).nova()
self.context['flavor'] = nova.flavors.create(name=self.config.get('flavor_name', 'rally_test_flavor'), ram=self.config.get('ram', 1), vcpus=self.config.get('vcpus', 1), disk=self.config.get('disk',... | Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context | CreateFlavorContext | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateFlavorContext:
"""Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context"""
def setup(self):
"""This method is called before the ... | stack_v2_sparse_classes_36k_train_014448 | 3,127 | permissive | [
{
"docstring": "This method is called before the task start.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "This method is called after the task finish.",
"name": "cleanup",
"signature": "def cleanup(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015788 | Implement the Python class `CreateFlavorContext` described below.
Class description:
Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context
Method signatures and docstri... | Implement the Python class `CreateFlavorContext` described below.
Class description:
Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context
Method signatures and docstri... | 8da58ac92d36de736138240cc825a0423e11ff83 | <|skeleton|>
class CreateFlavorContext:
"""Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context"""
def setup(self):
"""This method is called before the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateFlavorContext:
"""Create sample flavor This sample create flavor with specified options before task starts and delete it after task completion. To create your own context plugin, inherit it from rally.task.context.Context"""
def setup(self):
"""This method is called before the task start.""... | the_stack_v2_python_sparse | samples/plugins/context/context_plugin.py | boris-42/rally | train | 1 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError('If degrees is a single number, it must be positive.')\n self.degrees = (-degrees, degrees)\nelse:\n if len(degrees) != 2:\n raise ValueError('If degrees is a sequence, it must be of len 2.')\n self.degrees = deg... | <|body_start_0|>
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError('If degrees... | Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the ce... | RandomRotation3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_36k_train_014449 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, degrees, rotate_planes=[[0, 1], [0, 2], [1, 2]])"
},
{
"docstring": "Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation.",
"name": "get_param... | 3 | stack_v2_sparse_classes_30k_train_013914 | Implement the Python class `RandomRotation3D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | Implement the Python class `RandomRotation3D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
f71043721417d00212bc58287a844aacdc4aca5b | [
"image = self.model()\nif url:\n for source_type, regexp in self.model.SOURCE_REGEXP.items():\n source_id = re.compile(regexp).findall(url)\n if source_id:\n try:\n return self.get(source_type=source_type, source_id=source_id[0])\n except self.model.DoesNotExist... | <|body_start_0|>
image = self.model()
if url:
for source_type, regexp in self.model.SOURCE_REGEXP.items():
source_id = re.compile(regexp).findall(url)
if source_id:
try:
return self.get(source_type=source_type, sourc... | ImageManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageManager:
def get_image_from_url(self, url=None):
"""Check if image has ever been downloaded before and return if found, otherwise initialize new"""
<|body_0|>
def download(self, url, **kwargs):
"""Download image from URL save and return it"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_014450 | 5,904 | permissive | [
{
"docstring": "Check if image has ever been downloaded before and return if found, otherwise initialize new",
"name": "get_image_from_url",
"signature": "def get_image_from_url(self, url=None)"
},
{
"docstring": "Download image from URL save and return it",
"name": "download",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_007447 | Implement the Python class `ImageManager` described below.
Class description:
Implement the ImageManager class.
Method signatures and docstrings:
- def get_image_from_url(self, url=None): Check if image has ever been downloaded before and return if found, otherwise initialize new
- def download(self, url, **kwargs): ... | Implement the Python class `ImageManager` described below.
Class description:
Implement the ImageManager class.
Method signatures and docstrings:
- def get_image_from_url(self, url=None): Check if image has ever been downloaded before and return if found, otherwise initialize new
- def download(self, url, **kwargs): ... | c393dc8c2d59dc99aa2c3314d3372b6e2bf5497f | <|skeleton|>
class ImageManager:
def get_image_from_url(self, url=None):
"""Check if image has ever been downloaded before and return if found, otherwise initialize new"""
<|body_0|>
def download(self, url, **kwargs):
"""Download image from URL save and return it"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageManager:
def get_image_from_url(self, url=None):
"""Check if image has ever been downloaded before and return if found, otherwise initialize new"""
image = self.model()
if url:
for source_type, regexp in self.model.SOURCE_REGEXP.items():
source_id = re.... | the_stack_v2_python_sparse | cinemanio/images/models.py | cinemanio/backend | train | 4 | |
7e4a58a36df8f61d05603bd18ad1ce5a6640051f | [
"def reverse(nums, i, j):\n while i < j:\n nums[i], nums[j] = (nums[j], nums[i])\n i += 1\n j -= 1\nsize = len(nums)\nindex = -1\nfor i in range(size - 1, 0, -1):\n if nums[i] > nums[i - 1]:\n index = i - 1\n break\nif index == -1:\n reverse(nums, 0, size - 1)\n return... | <|body_start_0|>
def reverse(nums, i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
i += 1
j -= 1
size = len(nums)
index = -1
for i in range(size - 1, 0, -1):
if nums[i] > nums[i - 1]:
index ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def nextPermutation1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_014451 | 2,276 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "nextPermutation1",
"signature": "def ne... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def nextPermutation1(self, nums: List[int]) -> None: Do not return any... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def nextPermutation1(self, nums: List[int]) -> None: Do not return any... | e69a94799e8e2bd12d4cd54cae81aba02c448730 | <|skeleton|>
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def nextPermutation1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
def reverse(nums, i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
i += 1
j -= 1
size = len(num... | the_stack_v2_python_sparse | Array/0031_next_permutation.py | harshil1903/leetcode | train | 0 | |
427b4ddfe14fb6017beb99e8d16104443d570791 | [
"res = []\nif k == 0:\n return []\nfor i in range(0, k + 1):\n for j in range(0, k + 1):\n if i + j == k:\n res.append(shorter * i + longer * j)\nreturn sorted(res)",
"if k == 0:\n return []\nres = []\nif shorter == longer:\n return [shorter * k]\nfor i in range(k, -1, -1):\n res.... | <|body_start_0|>
res = []
if k == 0:
return []
for i in range(0, k + 1):
for j in range(0, k + 1):
if i + j == k:
res.append(shorter * i + longer * j)
return sorted(res)
<|end_body_0|>
<|body_start_1|>
if k == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divingBoard(self, shorter, longer, k):
"""暴力 O(k^2) O(m)"""
<|body_0|>
def divingBoard(self, shorter, longer, k):
"""小的从大到小取"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
if k == 0:
return []
for ... | stack_v2_sparse_classes_36k_train_014452 | 790 | no_license | [
{
"docstring": "暴力 O(k^2) O(m)",
"name": "divingBoard",
"signature": "def divingBoard(self, shorter, longer, k)"
},
{
"docstring": "小的从大到小取",
"name": "divingBoard",
"signature": "def divingBoard(self, shorter, longer, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divingBoard(self, shorter, longer, k): 暴力 O(k^2) O(m)
- def divingBoard(self, shorter, longer, k): 小的从大到小取 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divingBoard(self, shorter, longer, k): 暴力 O(k^2) O(m)
- def divingBoard(self, shorter, longer, k): 小的从大到小取
<|skeleton|>
class Solution:
def divingBoard(self, shorter, l... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def divingBoard(self, shorter, longer, k):
"""暴力 O(k^2) O(m)"""
<|body_0|>
def divingBoard(self, shorter, longer, k):
"""小的从大到小取"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def divingBoard(self, shorter, longer, k):
"""暴力 O(k^2) O(m)"""
res = []
if k == 0:
return []
for i in range(0, k + 1):
for j in range(0, k + 1):
if i + j == k:
res.append(shorter * i + longer * j)
re... | the_stack_v2_python_sparse | 4_LEETCODE/4_Sort/面试题 16.11. 跳水板.py | fzingithub/SwordRefers2Offer | train | 1 | |
a68b9565a97edec62497eafc94f3d89a1e5616cc | [
"Company = self.old_state.apps.get_model('company', 'company')\nCompany.objects.create(name='Company 1', address=self.short_l1)\nCompany.objects.create(name='Company 2', address=self.long_l1 + self.l2)",
"Address = self.new_state.apps.get_model('company', 'address')\nCompany = self.new_state.apps.get_model('compa... | <|body_start_0|>
Company = self.old_state.apps.get_model('company', 'company')
Company.objects.create(name='Company 1', address=self.short_l1)
Company.objects.create(name='Company 2', address=self.long_l1 + self.l2)
<|end_body_0|>
<|body_start_1|>
Address = self.new_state.apps.get_model... | Test moving address data into Address model | TestAddressMigration | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAddressMigration:
"""Test moving address data into Address model"""
def prepare(self):
"""Set up some companies with addresses"""
<|body_0|>
def test_address_migration(self):
"""Test database state after applying the migration"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_014453 | 12,626 | permissive | [
{
"docstring": "Set up some companies with addresses",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test database state after applying the migration",
"name": "test_address_migration",
"signature": "def test_address_migration(self)"
}
] | 2 | null | Implement the Python class `TestAddressMigration` described below.
Class description:
Test moving address data into Address model
Method signatures and docstrings:
- def prepare(self): Set up some companies with addresses
- def test_address_migration(self): Test database state after applying the migration | Implement the Python class `TestAddressMigration` described below.
Class description:
Test moving address data into Address model
Method signatures and docstrings:
- def prepare(self): Set up some companies with addresses
- def test_address_migration(self): Test database state after applying the migration
<|skeleton... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestAddressMigration:
"""Test moving address data into Address model"""
def prepare(self):
"""Set up some companies with addresses"""
<|body_0|>
def test_address_migration(self):
"""Test database state after applying the migration"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAddressMigration:
"""Test moving address data into Address model"""
def prepare(self):
"""Set up some companies with addresses"""
Company = self.old_state.apps.get_model('company', 'company')
Company.objects.create(name='Company 1', address=self.short_l1)
Company.objec... | the_stack_v2_python_sparse | InvenTree/company/test_migrations.py | inventree/InvenTree | train | 3,077 |
a6501d242bf6288b8f5bfe643dc2161b244d8298 | [
"self.mode_name = 'playstore'\nBase.__init__(self, self.mode_name)\nself.ime = IME()\nself.debug_print('PlayStore init:%f' % time.time())",
"click_button_by_id('search_button')\nclick_textview_by_id('search_src_text')\nself.ime.IME_input_english(1, name)\nsend_key(KEY_ENTER)\nsleep(20)\nclick_textview_by_text(des... | <|body_start_0|>
self.mode_name = 'playstore'
Base.__init__(self, self.mode_name)
self.ime = IME()
self.debug_print('PlayStore init:%f' % time.time())
<|end_body_0|>
<|body_start_1|>
click_button_by_id('search_button')
click_textview_by_id('search_src_text')
self... | PlayStore is a class for operating google play store application. @see: L{Base <Base>} | PlayStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayStore:
"""PlayStore is a class for operating google play store application. @see: L{Base <Base>}"""
def __init__(self):
"""init function."""
<|body_0|>
def download(self, name, description):
"""download a application according to the application name and desc... | stack_v2_sparse_classes_36k_train_014454 | 2,935 | no_license | [
{
"docstring": "init function.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "download a application according to the application name and description. @type name: string @param name: application's name @type description: string @param description: applicaiton's descr... | 2 | stack_v2_sparse_classes_30k_train_014437 | Implement the Python class `PlayStore` described below.
Class description:
PlayStore is a class for operating google play store application. @see: L{Base <Base>}
Method signatures and docstrings:
- def __init__(self): init function.
- def download(self, name, description): download a application according to the appl... | Implement the Python class `PlayStore` described below.
Class description:
PlayStore is a class for operating google play store application. @see: L{Base <Base>}
Method signatures and docstrings:
- def __init__(self): init function.
- def download(self, name, description): download a application according to the appl... | a04b717ae437511abae1e7e9e399373c161a7b65 | <|skeleton|>
class PlayStore:
"""PlayStore is a class for operating google play store application. @see: L{Base <Base>}"""
def __init__(self):
"""init function."""
<|body_0|>
def download(self, name, description):
"""download a application according to the application name and desc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayStore:
"""PlayStore is a class for operating google play store application. @see: L{Base <Base>}"""
def __init__(self):
"""init function."""
self.mode_name = 'playstore'
Base.__init__(self, self.mode_name)
self.ime = IME()
self.debug_print('PlayStore init:%f' %... | the_stack_v2_python_sparse | test_env/qrd_shared/playstore/PlayStore.py | wwlwwlqaz/Qualcomm | train | 1 |
51c057766a880699d361c702d491ba22be94c61b | [
"col = self._parent\nout = {'data': col.view(np.ndarray)}\nreturn out",
"data = map.pop('data')\nout = self._parent_cls(data, **map)\nreturn out"
] | <|body_start_0|>
col = self._parent
out = {'data': col.view(np.ndarray)}
return out
<|end_body_0|>
<|body_start_1|>
data = map.pop('data')
out = self._parent_cls(data, **map)
return out
<|end_body_1|>
| NdarrayMixinInfo | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NdarrayMixinInfo:
def _represent_as_dict(self):
"""Represent Column as a dict that can be serialized."""
<|body_0|>
def _construct_from_dict(self, map):
"""Construct Column from ``map``."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
col = self._pa... | stack_v2_sparse_classes_36k_train_014455 | 2,171 | permissive | [
{
"docstring": "Represent Column as a dict that can be serialized.",
"name": "_represent_as_dict",
"signature": "def _represent_as_dict(self)"
},
{
"docstring": "Construct Column from ``map``.",
"name": "_construct_from_dict",
"signature": "def _construct_from_dict(self, map)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007071 | Implement the Python class `NdarrayMixinInfo` described below.
Class description:
Implement the NdarrayMixinInfo class.
Method signatures and docstrings:
- def _represent_as_dict(self): Represent Column as a dict that can be serialized.
- def _construct_from_dict(self, map): Construct Column from ``map``. | Implement the Python class `NdarrayMixinInfo` described below.
Class description:
Implement the NdarrayMixinInfo class.
Method signatures and docstrings:
- def _represent_as_dict(self): Represent Column as a dict that can be serialized.
- def _construct_from_dict(self, map): Construct Column from ``map``.
<|skeleton... | 53188c39a23c33b72df5850ec59e31886f84e29d | <|skeleton|>
class NdarrayMixinInfo:
def _represent_as_dict(self):
"""Represent Column as a dict that can be serialized."""
<|body_0|>
def _construct_from_dict(self, map):
"""Construct Column from ``map``."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NdarrayMixinInfo:
def _represent_as_dict(self):
"""Represent Column as a dict that can be serialized."""
col = self._parent
out = {'data': col.view(np.ndarray)}
return out
def _construct_from_dict(self, map):
"""Construct Column from ``map``."""
data = map.... | the_stack_v2_python_sparse | astropy/table/ndarray_mixin.py | astropy/astropy | train | 3,922 | |
8c7f2bcc24e4b8112a6199ec2b4cd0c1653310b5 | [
"user = self.request.user\nif not user.is_authenticated:\n return []\nif user.username == 'chris':\n return Feed.objects.all()\nreturn Feed.objects.filter(owner=user)",
"response = super(FeedList, self).list(request, *args, **kwargs)\nquery_list = [reverse('feed-list-query-search', request=request)]\nrespon... | <|body_start_0|>
user = self.request.user
if not user.is_authenticated:
return []
if user.username == 'chris':
return Feed.objects.all()
return Feed.objects.filter(owner=user)
<|end_body_0|>
<|body_start_1|>
response = super(FeedList, self).list(request, ... | A view for the collection of feeds. This is also the API's "homepage". | FeedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedList:
"""A view for the collection of feeds. This is also the API's "homepage"."""
def get_queryset(self):
"""Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated user."""
<|body_0|>
def list(self, request, *a... | stack_v2_sparse_classes_36k_train_014456 | 21,257 | permissive | [
{
"docstring": "Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated user.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Overriden to append document-level link relations and a query list to the respon... | 2 | null | Implement the Python class `FeedList` described below.
Class description:
A view for the collection of feeds. This is also the API's "homepage".
Method signatures and docstrings:
- def get_queryset(self): Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated us... | Implement the Python class `FeedList` described below.
Class description:
A view for the collection of feeds. This is also the API's "homepage".
Method signatures and docstrings:
- def get_queryset(self): Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated us... | 20d3eedf20610af9182f6cca8db8f0b3546b5336 | <|skeleton|>
class FeedList:
"""A view for the collection of feeds. This is also the API's "homepage"."""
def get_queryset(self):
"""Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated user."""
<|body_0|>
def list(self, request, *a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedList:
"""A view for the collection of feeds. This is also the API's "homepage"."""
def get_queryset(self):
"""Overriden to return a custom queryset that is only comprised by the feeds owned by the currently authenticated user."""
user = self.request.user
if not user.is_authent... | the_stack_v2_python_sparse | chris_backend/feeds/views.py | FNNDSC/ChRIS_ultron_backEnd | train | 36 |
4df837e9bb9fa5f51628b12efb87c19c7119c177 | [
"pokemon['Name'] = 'Richard'\npokemon['Class'] = 'Bulbasaur'\npokemon['Position'] = [0, 2]\npokemon['HP'] = 10",
"random.seed(6)\nexpected_output = 'You attacked Pikachu with a slap and he took 5 damage.\\nSuccess! Your opponent has fainted and you gained 20 prize dollars from your battle.\\n\\n'\nopponent = {'Na... | <|body_start_0|>
pokemon['Name'] = 'Richard'
pokemon['Class'] = 'Bulbasaur'
pokemon['Position'] = [0, 2]
pokemon['HP'] = 10
<|end_body_0|>
<|body_start_1|>
random.seed(6)
expected_output = 'You attacked Pikachu with a slap and he took 5 damage.\nSuccess! Your opponent ha... | TestCombatRound | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCombatRound:
def setUp(self):
"""Assert global variable key-value pairs for unit testing."""
<|body_0|>
def test_combat_round_output(self, mock_stdout):
"""Assert expected print output of function after execution."""
<|body_1|>
def test_combat_round_... | stack_v2_sparse_classes_36k_train_014457 | 2,172 | no_license | [
{
"docstring": "Assert global variable key-value pairs for unit testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Assert expected print output of function after execution.",
"name": "test_combat_round_output",
"signature": "def test_combat_round_output(self, m... | 5 | stack_v2_sparse_classes_30k_train_001425 | Implement the Python class `TestCombatRound` described below.
Class description:
Implement the TestCombatRound class.
Method signatures and docstrings:
- def setUp(self): Assert global variable key-value pairs for unit testing.
- def test_combat_round_output(self, mock_stdout): Assert expected print output of functio... | Implement the Python class `TestCombatRound` described below.
Class description:
Implement the TestCombatRound class.
Method signatures and docstrings:
- def setUp(self): Assert global variable key-value pairs for unit testing.
- def test_combat_round_output(self, mock_stdout): Assert expected print output of functio... | 4053046fffb170104ea4209b156ee97185ef4f6f | <|skeleton|>
class TestCombatRound:
def setUp(self):
"""Assert global variable key-value pairs for unit testing."""
<|body_0|>
def test_combat_round_output(self, mock_stdout):
"""Assert expected print output of function after execution."""
<|body_1|>
def test_combat_round_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCombatRound:
def setUp(self):
"""Assert global variable key-value pairs for unit testing."""
pokemon['Name'] = 'Richard'
pokemon['Class'] = 'Bulbasaur'
pokemon['Position'] = [0, 2]
pokemon['HP'] = 10
def test_combat_round_output(self, mock_stdout):
"""A... | the_stack_v2_python_sparse | A3/test_combat_round.py | truongnguyenlinh/procedural_python | train | 0 | |
f8f5abe5119d83aa6a2066384693226d96de6478 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('div.book-name').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_author = soup.select_one('div.author span.name').text.strip()\nlogger.info('Novel author: %s', self.novel... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('div.book-name').text.strip()
logger.info('Novel title: %s', self.novel_title)
self.novel_author = soup.select_one('div.author span.name').text.str... | NovelUpdatesCC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NovelUpdatesCC:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014458 | 3,146 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_000364 | Implement the Python class `NovelUpdatesCC` described below.
Class description:
Implement the NovelUpdatesCC class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html fo... | Implement the Python class `NovelUpdatesCC` described below.
Class description:
Implement the NovelUpdatesCC class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html fo... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class NovelUpdatesCC:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NovelUpdatesCC:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('div.book-name').text.strip()
logger.info('Novel title: %s', self.novel... | the_stack_v2_python_sparse | lncrawl/sources/novelupdatescc.py | NNTin/lightnovel-crawler | train | 2 | |
c207f521c816f76bc624a1d1cd0fdc9eb4258e13 | [
"self.input_layer = input_layer\nself.loss_function = loss_function\nself.target_var = T.matrix('target')\nif aggregation not in self._valid_aggregation:\n raise ValueError(\"aggregation must be 'mean', 'sum', or None, not {0}\".format(aggregation))\nself.aggregation = aggregation",
"network_output = self.inpu... | <|body_start_0|>
self.input_layer = input_layer
self.loss_function = loss_function
self.target_var = T.matrix('target')
if aggregation not in self._valid_aggregation:
raise ValueError("aggregation must be 'mean', 'sum', or None, not {0}".format(aggregation))
self.aggr... | Objective | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objective:
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)` that returns a scalar loss given tensor... | stack_v2_sparse_classes_36k_train_014459 | 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)` that returns a scalar loss given tensors that represent the predicted and true values as arguments.. - aggregation : either: - `'mean... | 2 | stack_v2_sparse_classes_30k_val_000620 | Implement the Python class `Objective` described below.
Class description:
Implement the Objective 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 given its inp... | Implement the Python class `Objective` described below.
Class description:
Implement the Objective 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 given its inp... | 54b4c07fb9cf39a0fc84f5e384a9fc855f9d016f | <|skeleton|>
class Objective:
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)` that returns a scalar loss given tensor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Objective:
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)` that returns a scalar loss given tensors that represe... | the_stack_v2_python_sparse | attrib/lasagne/objectives.py | thjashin/kblearn | train | 3 | |
c02c521b47e5da981596cb6eee5a78100ecbd665 | [
"super().__init__(config_entry_id, device)\nself.entity_description = description\nself._attr_unique_id = f'{device.id}-{description.key}'",
"sensor_type = self.entity_description.key\nif sensor_type == 'volume':\n return self._device.volume\nif sensor_type == 'battery':\n return self._device.battery_life"
... | <|body_start_0|>
super().__init__(config_entry_id, device)
self.entity_description = description
self._attr_unique_id = f'{device.id}-{description.key}'
<|end_body_0|>
<|body_start_1|>
sensor_type = self.entity_description.key
if sensor_type == 'volume':
return self.... | A sensor implementation for Ring device. | RingSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RingSensor:
"""A sensor implementation for Ring device."""
def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None:
"""Initialize a sensor for Ring device."""
<|body_0|>
def native_value(self):
"""Return the state of the sens... | stack_v2_sparse_classes_36k_train_014460 | 7,714 | permissive | [
{
"docstring": "Initialize a sensor for Ring device.",
"name": "__init__",
"signature": "def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def native_va... | 2 | null | Implement the Python class `RingSensor` described below.
Class description:
A sensor implementation for Ring device.
Method signatures and docstrings:
- def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None: Initialize a sensor for Ring device.
- def native_value(self): Return ... | Implement the Python class `RingSensor` described below.
Class description:
A sensor implementation for Ring device.
Method signatures and docstrings:
- def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None: Initialize a sensor for Ring device.
- def native_value(self): Return ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RingSensor:
"""A sensor implementation for Ring device."""
def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None:
"""Initialize a sensor for Ring device."""
<|body_0|>
def native_value(self):
"""Return the state of the sens... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RingSensor:
"""A sensor implementation for Ring device."""
def __init__(self, config_entry_id, device, description: RingSensorEntityDescription) -> None:
"""Initialize a sensor for Ring device."""
super().__init__(config_entry_id, device)
self.entity_description = description
... | the_stack_v2_python_sparse | homeassistant/components/ring/sensor.py | home-assistant/core | train | 35,501 |
5553ca2491752d544383be876a85cc5a399cb482 | [
"self.id = id\nself.callback_url = callback_url\nself.publish_permissions = publish_permissions\nself.sessions = sessions\nself.subscriptions = subscriptions\nself.tag = tag\nself.device_api_version = device_api_version",
"if dictionary is None:\n return None\nid = dictionary.get('id')\ncallback_url = dictiona... | <|body_start_0|>
self.id = id
self.callback_url = callback_url
self.publish_permissions = publish_permissions
self.sessions = sessions
self.subscriptions = subscriptions
self.tag = tag
self.device_api_version = device_api_version
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of PublishPermissionEnum): Defines if this participant can publish audio or video sessi... | Participant | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Participant:
"""Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of PublishPermissionEnum): Defines if this parti... | stack_v2_sparse_classes_36k_train_014461 | 3,403 | permissive | [
{
"docstring": "Constructor for the Participant class",
"name": "__init__",
"signature": "def __init__(self, id=None, callback_url=None, publish_permissions=None, sessions=None, subscriptions=None, tag=None, device_api_version='V2')"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_val_000968 | Implement the Python class `Participant` described below.
Class description:
Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of Publis... | Implement the Python class `Participant` described below.
Class description:
Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of Publis... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class Participant:
"""Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of PublishPermissionEnum): Defines if this parti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Participant:
"""Implementation of the 'Participant' model. A participant object Attributes: id (string): Unique id of the participant callback_url (string): Full callback url to use for notifications about this participant publish_permissions (list of PublishPermissionEnum): Defines if this participant can pu... | the_stack_v2_python_sparse | bandwidth/webrtc/models/participant.py | Bandwidth/python-sdk | train | 10 |
9a31e766d02dd7a2766c4914a3a843f6f68648ce | [
"if match.group('url'):\n return self._hyper_repl_url(match, '<a href=\"%s\">%s</a>%s')\nelif match.group('email'):\n return self._hyper_repl_email(match, '<a href=\"mailto:%s\">%s</a>')\nelif len(match.group('id')) < 10 and match.group('class') and (match.group('class').lower() in ('msg', 'file')):\n retu... | <|body_start_0|>
if match.group('url'):
return self._hyper_repl_url(match, '<a href="%s">%s</a>%s')
elif match.group('email'):
return self._hyper_repl_email(match, '<a href="mailto:%s">%s</a>')
elif len(match.group('id')) < 10 and match.group('class') and (match.group('cl... | PyDevStringHTMLProperty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyDevStringHTMLProperty:
def _hyper_repl(self, match):
"""Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and other items (except messages and files)."""
<|body_0|>
def pydev_hyperlinked(self):
"""Create p... | stack_v2_sparse_classes_36k_train_014462 | 8,966 | no_license | [
{
"docstring": "Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and other items (except messages and files).",
"name": "_hyper_repl",
"signature": "def _hyper_repl(self, match)"
},
{
"docstring": "Create python-dev-specific links.",
... | 4 | stack_v2_sparse_classes_30k_train_011357 | Implement the Python class `PyDevStringHTMLProperty` described below.
Class description:
Implement the PyDevStringHTMLProperty class.
Method signatures and docstrings:
- def _hyper_repl(self, match): Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and othe... | Implement the Python class `PyDevStringHTMLProperty` described below.
Class description:
Implement the PyDevStringHTMLProperty class.
Method signatures and docstrings:
- def _hyper_repl(self, match): Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and othe... | 1a94f0977ca025d2baf45ef712ef87f394a59b25 | <|skeleton|>
class PyDevStringHTMLProperty:
def _hyper_repl(self, match):
"""Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and other items (except messages and files)."""
<|body_0|>
def pydev_hyperlinked(self):
"""Create p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyDevStringHTMLProperty:
def _hyper_repl(self, match):
"""Override the original method and change it to still linkify URLs and emails but avoid linkification of issues and other items (except messages and files)."""
if match.group('url'):
return self._hyper_repl_url(match, '<a href... | the_stack_v2_python_sparse | extensions/local_replace.py | psf/bpo-tracker-cpython | train | 24 | |
32c71473b23a1945b6b487bab9f9315bfb2dc9e8 | [
"if not root:\n return ''\nqueue = collections.deque([root])\nretval = ''\nwhile queue:\n current = queue.popleft()\n if current != 'null':\n retval += str(current.val) + ','\n else:\n retval += 'null' + ','\n continue\n if current.left:\n queue.append(current.left)\n e... | <|body_start_0|>
if not root:
return ''
queue = collections.deque([root])
retval = ''
while queue:
current = queue.popleft()
if current != 'null':
retval += str(current.val) + ','
else:
retval += 'null' + ','... | 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_014463 | 1,942 | 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_000382 | 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:... | bbfee57ae89d23cd4f4132fbb62d8931ea654a0e | <|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 not root:
return ''
queue = collections.deque([root])
retval = ''
while queue:
current = queue.popleft()
if current != 'nul... | the_stack_v2_python_sparse | Algorithms/Leetcode/449 - Serialize and Deserialize BST.py | timpark0807/self-taught-swe | train | 1 | |
6a192b5d3589512e1186f9a24874c5a71dbb6ea5 | [
"super().__init__(dmm, f'ch{channel}', **kwargs)\nself.channel = channel\nself.dmm = dmm\nself.add_parameter('resistance', unit='Ohm', label=f'Resistance CH{self.channel}', get_parser=float, get_cmd=partial(self._measure, 'RES'))\nself.add_parameter('resistance_4w', unit='Ohm', label=f'Resistance (4-wire) CH{self.c... | <|body_start_0|>
super().__init__(dmm, f'ch{channel}', **kwargs)
self.channel = channel
self.dmm = dmm
self.add_parameter('resistance', unit='Ohm', label=f'Resistance CH{self.channel}', get_parser=float, get_cmd=partial(self._measure, 'RES'))
self.add_parameter('resistance_4w', u... | This is the qcodes driver for a channel of the 2000-SCAN scanner card. | Keithley_2000_Scan_Channel | [
"GPL-2.0-only",
"GPL-2.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keithley_2000_Scan_Channel:
"""This is the qcodes driver for a channel of the 2000-SCAN scanner card."""
def __init__(self, dmm: 'Keithley_6500', channel: int, **kwargs) -> None:
"""Initialize instance of scanner card Keithley 2000-SCAN Args: dmm: Instance of digital multimeter Keith... | stack_v2_sparse_classes_36k_train_014464 | 2,543 | permissive | [
{
"docstring": "Initialize instance of scanner card Keithley 2000-SCAN Args: dmm: Instance of digital multimeter Keithley6500 containing the scanner card channel: Channel number **kwargs: Keyword arguments to pass to __init__ function of InstrumentChannel class",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_006177 | Implement the Python class `Keithley_2000_Scan_Channel` described below.
Class description:
This is the qcodes driver for a channel of the 2000-SCAN scanner card.
Method signatures and docstrings:
- def __init__(self, dmm: 'Keithley_6500', channel: int, **kwargs) -> None: Initialize instance of scanner card Keithley ... | Implement the Python class `Keithley_2000_Scan_Channel` described below.
Class description:
This is the qcodes driver for a channel of the 2000-SCAN scanner card.
Method signatures and docstrings:
- def __init__(self, dmm: 'Keithley_6500', channel: int, **kwargs) -> None: Initialize instance of scanner card Keithley ... | e07c9f23339ab00b0f4c4cc46711593d88f7fc84 | <|skeleton|>
class Keithley_2000_Scan_Channel:
"""This is the qcodes driver for a channel of the 2000-SCAN scanner card."""
def __init__(self, dmm: 'Keithley_6500', channel: int, **kwargs) -> None:
"""Initialize instance of scanner card Keithley 2000-SCAN Args: dmm: Instance of digital multimeter Keith... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keithley_2000_Scan_Channel:
"""This is the qcodes driver for a channel of the 2000-SCAN scanner card."""
def __init__(self, dmm: 'Keithley_6500', channel: int, **kwargs) -> None:
"""Initialize instance of scanner card Keithley 2000-SCAN Args: dmm: Instance of digital multimeter Keithley6500 conta... | the_stack_v2_python_sparse | qcodes_contrib_drivers/drivers/Tektronix/Keithley_2000_Scan.py | QCoDeS/Qcodes_contrib_drivers | train | 32 |
533090537ef05fc6faa3738b6a8c8bfa6c2ca461 | [
"pos = 0\nwhile pos < len(self.value):\n list_entry_header = self.value[pos:pos + 26]\n if len(list_entry_header) != 26:\n break\n attribute_type_code, record_length, attribute_name_length, attribute_name_offset, lowest_vcn, segment_reference, attribute_instance = struct.unpack('<LHBBQQH', list_entr... | <|body_start_0|>
pos = 0
while pos < len(self.value):
list_entry_header = self.value[pos:pos + 26]
if len(list_entry_header) != 26:
break
attribute_type_code, record_length, attribute_name_length, attribute_name_offset, lowest_vcn, segment_reference, a... | $ATTRIBUTE_LIST. | AttributeList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeList:
"""$ATTRIBUTE_LIST."""
def entries(self):
"""This method yields each attribute list entry (AttributeListEntry)."""
<|body_0|>
def print_information(self):
"""Print all information in a human-readable form."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_014465 | 36,119 | permissive | [
{
"docstring": "This method yields each attribute list entry (AttributeListEntry).",
"name": "entries",
"signature": "def entries(self)"
},
{
"docstring": "Print all information in a human-readable form.",
"name": "print_information",
"signature": "def print_information(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007446 | Implement the Python class `AttributeList` described below.
Class description:
$ATTRIBUTE_LIST.
Method signatures and docstrings:
- def entries(self): This method yields each attribute list entry (AttributeListEntry).
- def print_information(self): Print all information in a human-readable form. | Implement the Python class `AttributeList` described below.
Class description:
$ATTRIBUTE_LIST.
Method signatures and docstrings:
- def entries(self): This method yields each attribute list entry (AttributeListEntry).
- def print_information(self): Print all information in a human-readable form.
<|skeleton|>
class A... | f9299b8ad0cb2a6bbbd5e65f01d2ba06406c70ac | <|skeleton|>
class AttributeList:
"""$ATTRIBUTE_LIST."""
def entries(self):
"""This method yields each attribute list entry (AttributeListEntry)."""
<|body_0|>
def print_information(self):
"""Print all information in a human-readable form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeList:
"""$ATTRIBUTE_LIST."""
def entries(self):
"""This method yields each attribute list entry (AttributeListEntry)."""
pos = 0
while pos < len(self.value):
list_entry_header = self.value[pos:pos + 26]
if len(list_entry_header) != 26:
... | the_stack_v2_python_sparse | modules/NTFS/dfir_ntfs/Attributes.py | dfrc-korea/carpe | train | 75 |
794af58bc678a7a921b0eca85c3cc8625849ac8b | [
"self._yLim = kwargs.pop('YLimit', None)\nself._xLim = kwargs.pop('XLimit', None)\nplot.PlotGraphics.__init__(self, *args, **kwargs)",
"bounds = plot.PlotGraphics.boundingBox(self)\nMin, Max = ([bounds[0][0], bounds[1][0]], [bounds[0][1], bounds[1][1]])\nif self._yLim is not None:\n Min[1], Max[1] = (self._yLi... | <|body_start_0|>
self._yLim = kwargs.pop('YLimit', None)
self._xLim = kwargs.pop('XLimit', None)
plot.PlotGraphics.__init__(self, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
bounds = plot.PlotGraphics.boundingBox(self)
Min, Max = ([bounds[0][0], bounds[1][0]], [bounds[0][1]... | ParameterPlotGraphics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterPlotGraphics:
def __init__(self, *args, **kwargs):
"""Basic constructor for the ParameterPlotGraphics"""
<|body_0|>
def boundingBox(self):
"""Calculates the bounds of the box, factoring in custom values"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_014466 | 1,012 | no_license | [
{
"docstring": "Basic constructor for the ParameterPlotGraphics",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Calculates the bounds of the box, factoring in custom values",
"name": "boundingBox",
"signature": "def boundingBox(self)"
}
] | 2 | null | Implement the Python class `ParameterPlotGraphics` described below.
Class description:
Implement the ParameterPlotGraphics class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Basic constructor for the ParameterPlotGraphics
- def boundingBox(self): Calculates the bounds of the box, factorin... | Implement the Python class `ParameterPlotGraphics` described below.
Class description:
Implement the ParameterPlotGraphics class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Basic constructor for the ParameterPlotGraphics
- def boundingBox(self): Calculates the bounds of the box, factorin... | 555739cafdeeed19d3c25c4948416a6ecb7697d5 | <|skeleton|>
class ParameterPlotGraphics:
def __init__(self, *args, **kwargs):
"""Basic constructor for the ParameterPlotGraphics"""
<|body_0|>
def boundingBox(self):
"""Calculates the bounds of the box, factoring in custom values"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterPlotGraphics:
def __init__(self, *args, **kwargs):
"""Basic constructor for the ParameterPlotGraphics"""
self._yLim = kwargs.pop('YLimit', None)
self._xLim = kwargs.pop('XLimit', None)
plot.PlotGraphics.__init__(self, *args, **kwargs)
def boundingBox(self):
... | the_stack_v2_python_sparse | editor/Welder/src/Core/Database/Controls/ParameterPlotGraphics.py | boisei0/arcreator | train | 1 | |
cf11b1e0dac3069d0945f03f4a6410c7d2b45846 | [
"self.dic = {}\nself.freq_dic = {}\nself.curr = ''\nfor j, sentence in enumerate(sentences):\n if sentence not in self.freq_dic:\n self.freq_dic[sentence] = 0\n for i in range(1, len(sentence) + 1):\n prefix = sentence[:i]\n if prefix not in self.dic:\n self.dic... | <|body_start_0|>
self.dic = {}
self.freq_dic = {}
self.curr = ''
for j, sentence in enumerate(sentences):
if sentence not in self.freq_dic:
self.freq_dic[sentence] = 0
for i in range(1, len(sentence) + 1):
prefix = sentence[... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dic = {}
... | stack_v2_sparse_classes_36k_train_014467 | 4,608 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 00fd1397b65c68a303fcf963db3e28cd35c1c003 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.dic = {}
self.freq_dic = {}
self.curr = ''
for j, sentence in enumerate(sentences):
if sentence not in self.freq_dic:
self.... | the_stack_v2_python_sparse | leetcode/642. Design Search Autocomplete System.py | cuiy0006/Algorithms | train | 0 | |
a8363dafe742dbb6ecfca107aecda6d83f758737 | [
"reactions = set()\nfor reaction in self:\n value = reaction['value']\n if UNICODE_EMOJI and (not all_chars):\n if value in UNICODE_EMOJI:\n reactions.add(reaction['value'])\n else:\n reactions.add(reaction['value'])\nreturn reactions",
"for element in self.xml.findall('reaction'... | <|body_start_0|>
reactions = set()
for reaction in self:
value = reaction['value']
if UNICODE_EMOJI and (not all_chars):
if value in UNICODE_EMOJI:
reactions.add(reaction['value'])
else:
reactions.add(reaction['value... | Reactions | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reactions:
def get_values(self, *, all_chars=False) -> Set[str]:
""""Get all reactions as str"""
<|body_0|>
def set_values(self, values: Iterable[str], *, all_chars=False):
""""Set all reactions as str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014468 | 1,699 | permissive | [
{
"docstring": "\"Get all reactions as str",
"name": "get_values",
"signature": "def get_values(self, *, all_chars=False) -> Set[str]"
},
{
"docstring": "\"Set all reactions as str",
"name": "set_values",
"signature": "def set_values(self, values: Iterable[str], *, all_chars=False)"
}
... | 2 | null | Implement the Python class `Reactions` described below.
Class description:
Implement the Reactions class.
Method signatures and docstrings:
- def get_values(self, *, all_chars=False) -> Set[str]: "Get all reactions as str
- def set_values(self, values: Iterable[str], *, all_chars=False): "Set all reactions as str | Implement the Python class `Reactions` described below.
Class description:
Implement the Reactions class.
Method signatures and docstrings:
- def get_values(self, *, all_chars=False) -> Set[str]: "Get all reactions as str
- def set_values(self, values: Iterable[str], *, all_chars=False): "Set all reactions as str
<|... | 7a0fb970833c778ed50dcb49c5b7b4043d57b1e5 | <|skeleton|>
class Reactions:
def get_values(self, *, all_chars=False) -> Set[str]:
""""Get all reactions as str"""
<|body_0|>
def set_values(self, values: Iterable[str], *, all_chars=False):
""""Set all reactions as str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reactions:
def get_values(self, *, all_chars=False) -> Set[str]:
""""Get all reactions as str"""
reactions = set()
for reaction in self:
value = reaction['value']
if UNICODE_EMOJI and (not all_chars):
if value in UNICODE_EMOJI:
... | the_stack_v2_python_sparse | slixmpp/plugins/xep_0444/stanza.py | poezio/slixmpp | train | 97 | |
4c58f6ce4f5f92e69fa53334ce11acbf1e113b63 | [
"entity = self.entities.find_entity_by_id(event.entity_id)\nskill = self.entities.find_entity_by_id(event.skill_entity_id)\nentity_mana_component = entity.components.get('mana', None)\nskill_mana_component = skill.components.get('mana_consuming_skill', None)\nif not skill_mana_component:\n return\nif not entity_... | <|body_start_0|>
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entity_id)
entity_mana_component = entity.components.get('mana', None)
skill_mana_component = skill.components.get('mana_consuming_skill', None)
if not s... | Mana consuming skill system. | ManaConsumingSkillSystem | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManaConsumingSkillSystem:
"""Mana consuming skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_014469 | 21,180 | permissive | [
{
"docstring": "Handle an entity skill usage attempt.",
"name": "on_entity_skill_usage_attempt",
"signature": "def on_entity_skill_usage_attempt(self, event)"
},
{
"docstring": "Handle an entity skill usage.",
"name": "on_entity_skill_usage",
"signature": "def on_entity_skill_usage(self,... | 2 | stack_v2_sparse_classes_30k_train_017951 | Implement the Python class `ManaConsumingSkillSystem` described below.
Class description:
Mana consuming skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill usage. | Implement the Python class `ManaConsumingSkillSystem` described below.
Class description:
Mana consuming skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill usage.
<|sk... | 1d84c2869a242a112e57c6cafc6da7329f9d0808 | <|skeleton|>
class ManaConsumingSkillSystem:
"""Mana consuming skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManaConsumingSkillSystem:
"""Mana consuming skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entity_id)
... | the_stack_v2_python_sparse | akurra/skills.py | multatronic/akurra | train | 0 |
76c6e47a56e50bfee58b0c099b4c5c7e8578ad09 | [
"self.key_value = defaultdict(int)\nself.value_keys = defaultdict(set)\nself.min = 0\nself.max = 0",
"value = self.key_value[key]\nkeys = self.value_keys[value]\nkeys.discard(key)\nif not keys:\n self.value_keys.pop(value)\n \"\\n # What's wrong with the below code? think about after inc('a') twi... | <|body_start_0|>
self.key_value = defaultdict(int)
self.value_keys = defaultdict(set)
self.min = 0
self.max = 0
<|end_body_0|>
<|body_start_1|>
value = self.key_value[key]
keys = self.value_keys[value]
keys.discard(key)
if not keys:
self.value... | AllOne2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne2:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""D... | stack_v2_sparse_classes_36k_train_014470 | 5,064 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void",
"name": "inc",
"signature": "def inc(self, key)"
},
... | 5 | null | Implement the Python class `AllOne2` described below.
Class description:
Implement the AllOne2 class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void... | Implement the Python class `AllOne2` described below.
Class description:
Implement the AllOne2 class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class AllOne2:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""D... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne2:
def __init__(self):
"""Initialize your data structure here."""
self.key_value = defaultdict(int)
self.value_keys = defaultdict(set)
self.min = 0
self.max = 0
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key... | the_stack_v2_python_sparse | code432AllO1DataStructure.py | cybelewang/leetcode-python | train | 0 | |
a292411ac84663d0cae002fb5de7b6e2f4f8bb51 | [
"output = cls._get_ip_link_output(root_helper)\nvf_block_pattern = re.search(cls.VF_BLOCK_REGEX, output, re.DOTALL | re.MULTILINE)\nif vf_block_pattern:\n return vf_block_pattern.group('vf_block')",
"if not vf_section:\n return False\nif subcapability:\n regex = cls.SUB_CAPABILITY_REGEX % {'cap': capabil... | <|body_start_0|>
output = cls._get_ip_link_output(root_helper)
vf_block_pattern = re.search(cls.VF_BLOCK_REGEX, output, re.DOTALL | re.MULTILINE)
if vf_block_pattern:
return vf_block_pattern.group('vf_block')
<|end_body_0|>
<|body_start_1|>
if not vf_section:
ret... | IpLinkSupport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpLinkSupport:
def get_vf_mgmt_section(cls, root_helper=None):
"""Parses ip link help output, and gets vf block :param root_helper: root permission helper"""
<|body_0|>
def vf_mgmt_capability_supported(cls, vf_section, capability, subcapability=None):
"""Validate vf ... | stack_v2_sparse_classes_36k_train_014471 | 3,800 | permissive | [
{
"docstring": "Parses ip link help output, and gets vf block :param root_helper: root permission helper",
"name": "get_vf_mgmt_section",
"signature": "def get_vf_mgmt_section(cls, root_helper=None)"
},
{
"docstring": "Validate vf capability support Checks if given vf capability (and sub capabil... | 3 | null | Implement the Python class `IpLinkSupport` described below.
Class description:
Implement the IpLinkSupport class.
Method signatures and docstrings:
- def get_vf_mgmt_section(cls, root_helper=None): Parses ip link help output, and gets vf block :param root_helper: root permission helper
- def vf_mgmt_capability_suppor... | Implement the Python class `IpLinkSupport` described below.
Class description:
Implement the IpLinkSupport class.
Method signatures and docstrings:
- def get_vf_mgmt_section(cls, root_helper=None): Parses ip link help output, and gets vf block :param root_helper: root permission helper
- def vf_mgmt_capability_suppor... | 207aca054266396cced5a40f24bb0530a4ecf6c7 | <|skeleton|>
class IpLinkSupport:
def get_vf_mgmt_section(cls, root_helper=None):
"""Parses ip link help output, and gets vf block :param root_helper: root permission helper"""
<|body_0|>
def vf_mgmt_capability_supported(cls, vf_section, capability, subcapability=None):
"""Validate vf ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IpLinkSupport:
def get_vf_mgmt_section(cls, root_helper=None):
"""Parses ip link help output, and gets vf block :param root_helper: root permission helper"""
output = cls._get_ip_link_output(root_helper)
vf_block_pattern = re.search(cls.VF_BLOCK_REGEX, output, re.DOTALL | re.MULTILINE)... | the_stack_v2_python_sparse | neutron/agent/linux/ip_link_support.py | projectcalico/calico-neutron | train | 10 | |
91e9ecc535b3a56a5abfe3d8b9504e24391ac5ae | [
"for target in ('schema',):\n if key != target:\n resultSet = self.__dict__.get(target, None) or getattr(self.__class__, target, None)\n try:\n return getattr(resultSet, key)\n except AttributeError:\n pass\nraise AttributeError('%s instance does not have %r attribute' ... | <|body_start_0|>
for target in ('schema',):
if key != target:
resultSet = self.__dict__.get(target, None) or getattr(self.__class__, target, None)
try:
return getattr(resultSet, key)
except AttributeError:
pass
... | A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of changes to the generated dbrow objects. Via the lazyresultset base-class provide... | DBResultSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBResultSet:
"""A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of changes to the generated dbrow objects. V... | stack_v2_sparse_classes_36k_train_014472 | 3,045 | no_license | [
{
"docstring": "Delegate attribute lookup to our schema if it exists",
"name": "__getattr__",
"signature": "def __getattr__(self, key)"
},
{
"docstring": "Retrieve the properties for this particular result-set",
"name": "getProperties",
"signature": "def getProperties(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_007024 | Implement the Python class `DBResultSet` described below.
Class description:
A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of ch... | Implement the Python class `DBResultSet` described below.
Class description:
A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of ch... | 86410d2e8bece963ee7e7306560c94930467a1a7 | <|skeleton|>
class DBResultSet:
"""A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of changes to the generated dbrow objects. V... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBResultSet:
"""A pseudo-sequence with read/write lazy-result-set semantics The DBResultSet wraps a pytable cursor which has a retrieved result-set to provide access to a controlling schema (a table or view schema) and to provide automated commit/abort of changes to the generated dbrow objects. Via the lazyre... | the_stack_v2_python_sparse | build/pytable/pytable/dbresultset.py | icot/euler | train | 0 |
d99dc2f30ed49f3feeab5c90c6523f9f4e5fd513 | [
"parent = range(n)\n\ndef find(x):\n return x if parent[x] == x else find(parent[x])\n\ndef union(xy):\n x, y = map(find, xy)\n parent[x] = y\n return x != y\nreturn len(edges) == n - 1 and all(map(union, edges))",
"parent = range(n)\n\ndef find(x):\n return x if parent[x] == x else find(parent[x])... | <|body_start_0|>
parent = range(n)
def find(x):
return x if parent[x] == x else find(parent[x])
def union(xy):
x, y = map(find, xy)
parent[x] = y
return x != y
return len(edges) == n - 1 and all(map(union, edges))
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 Union-Find beats 90.69%"""
<|body_0|>
def validTree1(self, n, edges):
""":ty... | stack_v2_sparse_classes_36k_train_014473 | 2,125 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 Union-Find beats 90.69%",
"name": "validTree",
"signature": "def validTree(self, n, edges)"
},
{
"docstring": ":type n: int :type edg... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validTree(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validTree(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 ... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 Union-Find beats 90.69%"""
<|body_0|>
def validTree1(self, n, edges):
""":ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validTree(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: bool if there is loop, num_edges > num_vertex - 1 if there is island, num_edges < num_vertex - 1 Union-Find beats 90.69%"""
parent = range(n)
def find(x):
return x if parent[x] ==... | the_stack_v2_python_sparse | LeetCode/261_graph_valid_tree.py | yao23/Machine_Learning_Playground | train | 12 | |
f98e2a7291d449a151deb2134b6d8e16c391dc37 | [
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n nodeid = ''.join([nnid, '_', ver, '_', node])\n return_data = WorkFlowNetConfCNN().get_view_obj(nod... | <|body_start_0|>
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
node... | WorkFlowNetConfCnn | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowNetConfCnn:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get data"""
<|body_1|>
def put(self, request, nnid, ver, node):
"""- desc ; update data"""
... | stack_v2_sparse_classes_36k_train_014474 | 2,184 | permissive | [
{
"docstring": "- desc : insert data",
"name": "post",
"signature": "def post(self, request, nnid, ver, node)"
},
{
"docstring": "- desc : get data",
"name": "get",
"signature": "def get(self, request, nnid, ver, node)"
},
{
"docstring": "- desc ; update data",
"name": "put",... | 4 | null | Implement the Python class `WorkFlowNetConfCnn` described below.
Class description:
Implement the WorkFlowNetConfCnn class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert data
- def get(self, request, nnid, ver, node): - desc : get data
- def put(self, request, nnid, ver... | Implement the Python class `WorkFlowNetConfCnn` described below.
Class description:
Implement the WorkFlowNetConfCnn class.
Method signatures and docstrings:
- def post(self, request, nnid, ver, node): - desc : insert data
- def get(self, request, nnid, ver, node): - desc : get data
- def put(self, request, nnid, ver... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowNetConfCnn:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
<|body_0|>
def get(self, request, nnid, ver, node):
"""- desc : get data"""
<|body_1|>
def put(self, request, nnid, ver, node):
"""- desc ; update data"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkFlowNetConfCnn:
def post(self, request, nnid, ver, node):
"""- desc : insert data"""
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Respon... | the_stack_v2_python_sparse | api/views/workflow_netconf_cnn.py | yurimkoo/tensormsa | train | 1 | |
940624fff1ebfac745dbf5ffabb9ca7060c3ef4e | [
"super().__init__()\nself._beam_size = beam_size\nself._vocab_size = vocab_size\nself._eos_id = eos_id\nself._scorer = scorer\nself._state_batch_axis = state_batch_axis\nself.stochastic = stochastic\nassert eos_id is None or eos_id >= 0, 'eos_id cannot be negative! Received eos_id={}'.format(eos_id)",
"g_phi = ph... | <|body_start_0|>
super().__init__()
self._beam_size = beam_size
self._vocab_size = vocab_size
self._eos_id = eos_id
self._scorer = scorer
self._state_batch_axis = state_batch_axis
self.stochastic = stochastic
assert eos_id is None or eos_id >= 0, 'eos_id c... | _BeamSearchStepUpdate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BeamSearchStepUpdate:
def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False):
"""Parameters ---------- beam_size : int vocab_size : int eos_id : int scorer : BeamSearchScorer state_batch_axis : stochastic: bool prefix : None params : None"""
... | stack_v2_sparse_classes_36k_train_014475 | 32,467 | permissive | [
{
"docstring": "Parameters ---------- beam_size : int vocab_size : int eos_id : int scorer : BeamSearchScorer state_batch_axis : stochastic: bool prefix : None params : None",
"name": "__init__",
"signature": "def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False)"... | 4 | null | Implement the Python class `_BeamSearchStepUpdate` described below.
Class description:
Implement the _BeamSearchStepUpdate class.
Method signatures and docstrings:
- def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False): Parameters ---------- beam_size : int vocab_size : int eo... | Implement the Python class `_BeamSearchStepUpdate` described below.
Class description:
Implement the _BeamSearchStepUpdate class.
Method signatures and docstrings:
- def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False): Parameters ---------- beam_size : int vocab_size : int eo... | 1df42c561ae9552960e3f8b5f22e74de812a29c6 | <|skeleton|>
class _BeamSearchStepUpdate:
def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False):
"""Parameters ---------- beam_size : int vocab_size : int eos_id : int scorer : BeamSearchScorer state_batch_axis : stochastic: bool prefix : None params : None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _BeamSearchStepUpdate:
def __init__(self, beam_size, vocab_size, eos_id, scorer, state_batch_axis, stochastic=False):
"""Parameters ---------- beam_size : int vocab_size : int eos_id : int scorer : BeamSearchScorer state_batch_axis : stochastic: bool prefix : None params : None"""
super().__in... | the_stack_v2_python_sparse | src/gluonnlp/sequence_sampler.py | akshatgui/gluon-nlp | train | 0 | |
4613ba4b57df850b287104fb0ca38e2226e75040 | [
"self.verbose(result.show(display_guest=display_guest), shift=1)\nif verbosity == 1:\n return\nassert self.step.plan.execute.workdir is not None\nfor log_file in result.log:\n log_name = log_file.name\n full_path = self.step.plan.execute.workdir / log_file\n self.verbose(log_name, str(full_path), color=... | <|body_start_0|>
self.verbose(result.show(display_guest=display_guest), shift=1)
if verbosity == 1:
return
assert self.step.plan.execute.workdir is not None
for log_file in result.log:
log_name = log_file.name
full_path = self.step.plan.execute.workdir... | Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode. | ReportDisplay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on t... | stack_v2_sparse_classes_36k_train_014476 | 2,618 | permissive | [
{
"docstring": "Print result details based on the verbose mode",
"name": "details",
"signature": "def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None"
},
{
"docstring": "Discover available tests",
"name": "go",
"signature": "def go(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_000501 | Implement the Python class `ReportDisplay` described below.
Class description:
Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode.
Method signatures and docstrings:
- def details(self, result: tmt.Result, verbosity: int, disp... | Implement the Python class `ReportDisplay` described below.
Class description:
Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode.
Method signatures and docstrings:
- def details(self, result: tmt.Result, verbosity: int, disp... | 805c428eaf26a1d087f4a7a2672ffd1460ffd93a | <|skeleton|>
class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on the verbose mo... | the_stack_v2_python_sparse | tmt/steps/report/display.py | lukaszachy/tmt | train | 0 |
53f36807f85cb5c6de0e623b2795c303145f83d3 | [
"super().__init__()\nself.hidden_dim = hidden_dim\nself.num_convs = num_convs\nself.short_cut = short_cut\nself.concat_hidden = concat_hidden\nself.node_emb = nn.Embedding(100, hidden_dim)\nif isinstance(activation, str):\n self.activation = getattr(F, activation)\nelse:\n self.activation = None\nself.convs =... | <|body_start_0|>
super().__init__()
self.hidden_dim = hidden_dim
self.num_convs = num_convs
self.short_cut = short_cut
self.concat_hidden = concat_hidden
self.node_emb = nn.Embedding(100, hidden_dim)
if isinstance(activation, str):
self.activation = ge... | GIN encoder. | GINEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activatio... | stack_v2_sparse_classes_36k_train_014477 | 15,380 | permissive | [
{
"docstring": "Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activation: activation function. short_cut: whether to use short cut. concat_hidden: whether to concatenate hidden.",
"name": "__init__",
"signature": "def __init__(self, hidden_dim: ... | 2 | stack_v2_sparse_classes_30k_train_005965 | Implement the Python class `GINEncoder` described below.
Class description:
GIN encoder.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None: Construct a GIN encoder. Args: hidden_dim: number of hidd... | Implement the Python class `GINEncoder` described below.
Class description:
GIN encoder.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None: Construct a GIN encoder. Args: hidden_dim: number of hidd... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activation: activation... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/diffusion/geodiff/model/layers.py | GT4SD/gt4sd-core | train | 239 |
e058866aab8b0d075db8236bb6da253417dfcecc | [
"with self.assertRaisesRegex(TypeError, 'must inherit cirq.Sampler.'):\n cirq_ops._get_cirq_samples('junk')\ncirq_ops._get_cirq_samples()\ncirq_ops._get_cirq_samples(cirq.Simulator())\ncirq_ops._get_cirq_samples(cirq.DensityMatrixSimulator())\nmock_engine = mock.Mock()\ncirq_ops._get_cirq_samples(cirq_google.Qua... | <|body_start_0|>
with self.assertRaisesRegex(TypeError, 'must inherit cirq.Sampler.'):
cirq_ops._get_cirq_samples('junk')
cirq_ops._get_cirq_samples()
cirq_ops._get_cirq_samples(cirq.Simulator())
cirq_ops._get_cirq_samples(cirq.DensityMatrixSimulator())
mock_engine = ... | Tests get_cirq_samples. | CirqSamplesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CirqSamplesTest:
"""Tests get_cirq_samples."""
def test_get_cirq_sampling_op(self):
"""Input check the wrapper for the cirq sampling op."""
<|body_0|>
def test_cirq_sampling_op_inputs(self):
"""test input checking in the cirq sampling op."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_014478 | 23,553 | permissive | [
{
"docstring": "Input check the wrapper for the cirq sampling op.",
"name": "test_get_cirq_sampling_op",
"signature": "def test_get_cirq_sampling_op(self)"
},
{
"docstring": "test input checking in the cirq sampling op.",
"name": "test_cirq_sampling_op_inputs",
"signature": "def test_cir... | 6 | stack_v2_sparse_classes_30k_train_001190 | Implement the Python class `CirqSamplesTest` described below.
Class description:
Tests get_cirq_samples.
Method signatures and docstrings:
- def test_get_cirq_sampling_op(self): Input check the wrapper for the cirq sampling op.
- def test_cirq_sampling_op_inputs(self): test input checking in the cirq sampling op.
- d... | Implement the Python class `CirqSamplesTest` described below.
Class description:
Tests get_cirq_samples.
Method signatures and docstrings:
- def test_get_cirq_sampling_op(self): Input check the wrapper for the cirq sampling op.
- def test_cirq_sampling_op_inputs(self): test input checking in the cirq sampling op.
- d... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class CirqSamplesTest:
"""Tests get_cirq_samples."""
def test_get_cirq_sampling_op(self):
"""Input check the wrapper for the cirq sampling op."""
<|body_0|>
def test_cirq_sampling_op_inputs(self):
"""test input checking in the cirq sampling op."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CirqSamplesTest:
"""Tests get_cirq_samples."""
def test_get_cirq_sampling_op(self):
"""Input check the wrapper for the cirq sampling op."""
with self.assertRaisesRegex(TypeError, 'must inherit cirq.Sampler.'):
cirq_ops._get_cirq_samples('junk')
cirq_ops._get_cirq_sampl... | the_stack_v2_python_sparse | tensorflow_quantum/core/ops/cirq_ops_test.py | tensorflow/quantum | train | 1,799 |
a2d6af3d9ec871089d0fe30569f047ec486de9ac | [
"try:\n template_xsl_rendering_list = template_xsl_rendering_api.get_all()\n serializer = TemplateXslRenderingSerializer(template_xsl_rendering_list, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Exception as api_exception:\n content = {'message': str(api_exception)}\n... | <|body_start_0|>
try:
template_xsl_rendering_list = template_xsl_rendering_api.get_all()
serializer = TemplateXslRenderingSerializer(template_xsl_rendering_list, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
except Exception as api_exception:
... | List all template XSL renderings, or create a new one | TemplateXslRenderingList | [
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateXslRenderingList:
"""List all template XSL renderings, or create a new one"""
def get(self, request):
"""Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings - code: 401 content: Unauthorized - code: 500 content: In... | stack_v2_sparse_classes_36k_train_014479 | 14,418 | permissive | [
{
"docstring": "Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings - code: 401 content: Unauthorized - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a XSL te... | 2 | null | Implement the Python class `TemplateXslRenderingList` described below.
Class description:
List all template XSL renderings, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings ... | Implement the Python class `TemplateXslRenderingList` described below.
Class description:
List all template XSL renderings, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings ... | f032036d95076f92b164389fdbec7415567e7b0f | <|skeleton|>
class TemplateXslRenderingList:
"""List all template XSL renderings, or create a new one"""
def get(self, request):
"""Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings - code: 401 content: Unauthorized - code: 500 content: In... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateXslRenderingList:
"""List all template XSL renderings, or create a new one"""
def get(self, request):
"""Get all templates XSL renderings Args: request: HTTP request Returns: - code: 200 content: List of XSL renderings - code: 401 content: Unauthorized - code: 500 content: Internal server... | the_stack_v2_python_sparse | core_main_app/rest/template_xsl_rendering/views.py | usnistgov/core_main_app | train | 3 |
38123d838bf3307f3f9e946c50e14b2108b15dc9 | [
"def reverse(i, j):\n while i < j:\n nums[i], nums[j] = (nums[j], nums[i])\n i += 1\n j -= 1\nif k:\n n = len(nums)\n k = k % n\n reverse(0, n - 1)\n reverse(0, k - 1)\n reverse(k, n - 1)",
"if k:\n n = len(nums)\n k = k % n\n nums[:] = nums[n - k:] + nums[0:n - k]"... | <|body_start_0|>
def reverse(i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
i += 1
j -= 1
if k:
n = len(nums)
k = k % n
reverse(0, n - 1)
reverse(0, k - 1)
reverse(k, n - 1)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k_train_014480 | 1,251 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[in... | 75aef2f6c42aeb51261b9450a24099957a084d51 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
def reverse(i, j):
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
i += 1
j -= 1
... | the_stack_v2_python_sparse | Python/0189_RotateArray/rotate.py | mtmmy/Leetcode | train | 3 | |
f701697a18e6960675f37724737dc2d3c75fc58b | [
"if n < 0:\n return 0\nmemo = [0, 1]\nfor i in range(2, n + 1):\n memo.append(i)\n j = 1\n while j * j <= i:\n memo[-1] = min(memo[-1], 1 + memo[n - j * j])\n j += 1\nreturn memo[-1]",
"from collections import deque\nq = deque()\ni = 1\nwhile i * i <= n:\n remain = n - i * i\n q.ap... | <|body_start_0|>
if n < 0:
return 0
memo = [0, 1]
for i in range(2, n + 1):
memo.append(i)
j = 1
while j * j <= i:
memo[-1] = min(memo[-1], 1 + memo[n - j * j])
j += 1
return memo[-1]
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
<|body_0|>
def numSquares2(self, n: int) -> int:
"""bfs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 0:
return 0
memo = [0, 1]
for i in range(2, n + 1):
... | stack_v2_sparse_classes_36k_train_014481 | 1,136 | no_license | [
{
"docstring": "dp",
"name": "numSquares",
"signature": "def numSquares(self, n: int) -> int"
},
{
"docstring": "bfs",
"name": "numSquares2",
"signature": "def numSquares2(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_000580 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: dp
- def numSquares2(self, n: int) -> int: bfs | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: dp
- def numSquares2(self, n: int) -> int: bfs
<|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
... | 0f16635de49dc63a207d34f7e612546977a5753e | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
<|body_0|>
def numSquares2(self, n: int) -> int:
"""bfs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n: int) -> int:
"""dp"""
if n < 0:
return 0
memo = [0, 1]
for i in range(2, n + 1):
memo.append(i)
j = 1
while j * j <= i:
memo[-1] = min(memo[-1], 1 + memo[n - j * j])
... | the_stack_v2_python_sparse | leetcode/279numOfSquares.py | bycxw/coder | train | 0 | |
67766d909c914465132ff891909fd2f7b2d68b3d | [
"if n <= 0 or k < 0:\n return ''\nres = []\n\ndef helper(i, temp):\n if len(temp) == n:\n res.append(temp)\n return\n for j in range(1, n + 1):\n if str(j) in temp:\n continue\n helper(j, temp + str(j))\nhelper(0, '')\nprint(res)\nreturn res[k - 1]",
"if n == 0:\n ... | <|body_start_0|>
if n <= 0 or k < 0:
return ''
res = []
def helper(i, temp):
if len(temp) == n:
res.append(temp)
return
for j in range(1, n + 1):
if str(j) in temp:
continue
h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制"""
<|body_0|>
def getPermutation1(self, n: int, k: int) -> str:
"""123, 1为首字母,有23,32 ,2! 第n个位置的数字,由 k // (n-1)! 决定"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014482 | 1,879 | no_license | [
{
"docstring": "可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制",
"name": "getPermutation",
"signature": "def getPermutation(self, n: int, k: int) -> str"
},
{
"docstring": "123, 1为首字母,有23,32 ,2! 第n个位置的数字,由 k // (n-1)! 决定",
"name": "getPermutation1",
"signature": "def getPermutation1(self, n: int, k: int)... | 2 | stack_v2_sparse_classes_30k_train_019632 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n: int, k: int) -> str: 可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制
- def getPermutation1(self, n: int, k: int) -> str: 123, 1为首字母,有23,32 ,2! 第n个位置的数字,由 k // (n-1)! 决定 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation(self, n: int, k: int) -> str: 可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制
- def getPermutation1(self, n: int, k: int) -> str: 123, 1为首字母,有23,32 ,2! 第n个位置的数字,由 k // (n-1)! 决定... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制"""
<|body_0|>
def getPermutation1(self, n: int, k: int) -> str:
"""123, 1为首字母,有23,32 ,2! 第n个位置的数字,由 k // (n-1)! 决定"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getPermutation(self, n: int, k: int) -> str:
"""可以使用回溯法来做,套用模板 需要求出所有解,超出时间限制"""
if n <= 0 or k < 0:
return ''
res = []
def helper(i, temp):
if len(temp) == n:
res.append(temp)
return
for j in ra... | the_stack_v2_python_sparse | StringOperation/getPermutation.py | Philex5/codingPractice | train | 0 | |
8aad169fc36be484698fb2c6844496b38eec2304 | [
"if not project_id and (not cohort_id):\n raise ValueError('Must provide a value for the project or cohort ID')\npayload = {'string_query': statement}\nif project_id:\n payload['dataset_id'] = project_id\nif cohort_id:\n payload['cohort_id'] = cohort_id\nreturn self._api_call('analytics/dsl', http_verb='PO... | <|body_start_0|>
if not project_id and (not cohort_id):
raise ValueError('Must provide a value for the project or cohort ID')
payload = {'string_query': statement}
if project_id:
payload['dataset_id'] = project_id
if cohort_id:
payload['cohort_id'] = c... | Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get proxies information from HTTP_PROXY / HTTPS_PROXY environment variables if ... | Analytics | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analytics:
"""Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get proxies information from HTTP_PROXY / ... | stack_v2_sparse_classes_36k_train_014483 | 3,213 | permissive | [
{
"docstring": "Executes a SQL query against Analytics Parameters ---------- project_id : str The project ID cohort_id : str The cohort ID statement : str The SQL statement Returns ------- ApiResponse The API Response Raises ------ ValueError If no project or cohort ID is provided Examples -------- >>> from phc... | 2 | null | Implement the Python class `Analytics` described below.
Class description:
Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get... | Implement the Python class `Analytics` described below.
Class description:
Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get... | b7829b07566855b3e6642a42d215f0f9b5e57dba | <|skeleton|>
class Analytics:
"""Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get proxies information from HTTP_PROXY / ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Analytics:
"""Provides acccess to PHC Analytics Parameters ---------- session : phc.Session The PHC session run_async: bool True to return promises, False to return results (default is False) timeout: int Operation timeout (default is 30) trust_env: bool Get proxies information from HTTP_PROXY / HTTPS_PROXY e... | the_stack_v2_python_sparse | phc/services/analytics.py | lifeomic/phc-sdk-py | train | 2 |
68cc218fe47da911ce1619e66492bdfcd1f91f32 | [
"self.logger = AntiVirusLogger(__name__, debug=debug)\nif config_path is not None:\n self._CONFIG_PATH = config_path\nelse:\n self.logger.log('Configuration file path not found.', logtype='error')\n sys.exit(0)\nself.config_dict = utils.json_to_dict(self._CONFIG_PATH)\nself.os_name = utils.categorize_os()\... | <|body_start_0|>
self.logger = AntiVirusLogger(__name__, debug=debug)
if config_path is not None:
self._CONFIG_PATH = config_path
else:
self.logger.log('Configuration file path not found.', logtype='error')
sys.exit(0)
self.config_dict = utils.json_to_... | UpdateHash class. | UpdateHash | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateHash:
"""UpdateHash class."""
def __init__(self, debug=False, config_path=None):
"""Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: None"""
<|body_0|>
def remove_temp(self):
... | stack_v2_sparse_classes_36k_train_014484 | 5,064 | permissive | [
{
"docstring": "Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False, config_path=None)"
},
{
"docstring": "Remove temporary files generated ... | 4 | stack_v2_sparse_classes_30k_train_011175 | Implement the Python class `UpdateHash` described below.
Class description:
UpdateHash class.
Method signatures and docstrings:
- def __init__(self, debug=False, config_path=None): Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: N... | Implement the Python class `UpdateHash` described below.
Class description:
UpdateHash class.
Method signatures and docstrings:
- def __init__(self, debug=False, config_path=None): Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: N... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class UpdateHash:
"""UpdateHash class."""
def __init__(self, debug=False, config_path=None):
"""Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: None"""
<|body_0|>
def remove_temp(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateHash:
"""UpdateHash class."""
def __init__(self, debug=False, config_path=None):
"""Initialize UpdateHash. Args: debug (bool): Log on terminal or not config_path (str): Configuration JSON file path Raises: None Returns: None"""
self.logger = AntiVirusLogger(__name__, debug=debug)
... | the_stack_v2_python_sparse | securetea/lib/antivirus/update/update_hash.py | rejahrehim/SecureTea-Project | train | 1 |
f89ffd115911803ee89bec40a4baa1e853451cad | [
"from Queue import PriorityQueue\nself.st = PriorityQueue()\nself.bt = PriorityQueue()",
"self.st.put(-num)\nself.bt.put(-self.st.get())\nif self.bt.qsize() > self.st.qsize():\n self.st.put(-self.bt.get())",
"if self.st.qsize() > self.bt.qsize():\n return -self.st.queue[0]\nelse:\n return (-self.st.que... | <|body_start_0|>
from Queue import PriorityQueue
self.st = PriorityQueue()
self.bt = PriorityQueue()
<|end_body_0|>
<|body_start_1|>
self.st.put(-num)
self.bt.put(-self.st.get())
if self.bt.qsize() > self.st.qsize():
self.st.put(-self.bt.get())
<|end_body_1|>... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_014485 | 1,786 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | null | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | fe79161211cc08c269cde9e1fdcfed27de11f2cb | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
from Queue import PriorityQueue
self.st = PriorityQueue()
self.bt = PriorityQueue()
def addNum(self, num):
""":type num: int :rtype: void"""
self.st.put(-num)
self.bt.put(-... | the_stack_v2_python_sparse | MyLeetCode/python/Find Median from Data Stream.py | ihuei801/leetcode | train | 0 | |
e0ba47514b3cccba60ebcbaeca3639a3b21353e9 | [
"batch_node_features = np.vstack([graph.node_features for graph in graph_list])\nif graph_list[0].edge_features is not None:\n batch_edge_features: Optional[np.ndarray] = np.vstack([graph.edge_features for graph in graph_list])\nelse:\n batch_edge_features = None\nif graph_list[0].node_pos_features is not Non... | <|body_start_0|>
batch_node_features = np.vstack([graph.node_features for graph in graph_list])
if graph_list[0].edge_features is not None:
batch_edge_features: Optional[np.ndarray] = np.vstack([graph.edge_features for graph in graph_list])
else:
batch_edge_features = Non... | Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO format with shape [2, num_edges]. `num_edges... | BatchGraphData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO fo... | stack_v2_sparse_classes_36k_train_014486 | 22,111 | permissive | [
{
"docstring": "Parameters ---------- graph_list: Sequence[GraphData] List of GraphData",
"name": "__init__",
"signature": "def __init__(self, graph_list: Sequence[GraphData])"
},
{
"docstring": "A GraphData object can have user defined attributes but the attribute name of those are unknown sinc... | 3 | stack_v2_sparse_classes_30k_train_018517 | Implement the Python class `BatchGraphData` described below.
Class description:
Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Co... | Implement the Python class `BatchGraphData` described below.
Class description:
Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Co... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchGraphData:
"""Batch GraphData class Attributes ---------- node_features: np.ndarray Concatenated node feature matrix with shape [num_nodes, num_node_features]. `num_nodes` is total number of nodes in the batch graph. edge_index: np.ndarray, dtype int Concatenated graph connectivity in COO format with sha... | the_stack_v2_python_sparse | deepchem/feat/graph_data.py | deepchem/deepchem | train | 4,876 |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(StopVehicle, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._control = carla.VehicleControl()\nself._actor = actor\nself._brake_value = brake_value\nself._control.steering = 0",
"new_status = py_trees.common.Status.RUNNING\nif CarlaDataProvider.get_velocity(self._a... | <|body_start_0|>
super(StopVehicle, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._control = carla.VehicleControl()
self._actor = actor
self._brake_value = brake_value
self._control.steering = 0
<|end_body_0|>
<|body_start_1|>
... | This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop. | StopVehicle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
<|body_0|... | stack_v2_sparse_classes_36k_train_014487 | 25,380 | permissive | [
{
"docstring": "Setup _actor and maximum braking value",
"name": "__init__",
"signature": "def __init__(self, actor, brake_value, name='Stopping')"
},
{
"docstring": "Set brake to brake_value until reaching full stop",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020213 | Implement the Python class `StopVehicle` described below.
Class description:
This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop.
Method signatures and docstrings:
- def __init__(self, actor, brake_value, name='Stopping'): Se... | Implement the Python class `StopVehicle` described below.
Class description:
This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop.
Method signatures and docstrings:
- def __init__(self, actor, brake_value, name='Stopping'): Se... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StopVehicle:
"""This class contains an atomic stopping behavior. The controlled traffic participant will decelerate with _bake_value_ until reaching a full stop."""
def __init__(self, actor, brake_value, name='Stopping'):
"""Setup _actor and maximum braking value"""
super(StopVehicle, sel... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
76b3de3e7be38a939337bf3c0d93bc8c0dc61b70 | [
"ami = ec2AmiInstanceConfig.ami\ninstance = ec2AmiInstanceConfig.instance\nosh = ObjectStateHolder('amazon_ec2_config')\nosh.setStringAttribute('name', ami.getName())\nosh.setStringAttribute('ami_visibility', str(ami.getVisibility()))\nosh.setStringAttribute('description', ami.description)\nosh.setStringAttribute('... | <|body_start_0|>
ami = ec2AmiInstanceConfig.ami
instance = ec2AmiInstanceConfig.instance
osh = ObjectStateHolder('amazon_ec2_config')
osh.setStringAttribute('name', ami.getName())
osh.setStringAttribute('ami_visibility', str(ami.getVisibility()))
osh.setStringAttribute('d... | Builder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
<|body_0|>
def visitEc2AmiInstanceNode(self, ec2InstanceNode):
"""@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Publi... | stack_v2_sparse_classes_36k_train_014488 | 12,496 | no_license | [
{
"docstring": "@types: ec2.Ami.Instance -> ObjectStateHolder",
"name": "visitEc2AmiInstanceConfig",
"signature": "def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig)"
},
{
"docstring": "@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Public address is not speci... | 2 | stack_v2_sparse_classes_30k_train_009269 | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig): @types: ec2.Ami.Instance -> ObjectStateHolder
- def visitEc2AmiInstanceNode(self, ec2InstanceNode): @types: ec2.Builder.E... | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig): @types: ec2.Ami.Instance -> ObjectStateHolder
- def visitEc2AmiInstanceNode(self, ec2InstanceNode): @types: ec2.Builder.E... | 49aafa7081b861c5f6d0e1753b425e78948116d0 | <|skeleton|>
class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
<|body_0|>
def visitEc2AmiInstanceNode(self, ec2InstanceNode):
"""@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Publi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
ami = ec2AmiInstanceConfig.ami
instance = ec2AmiInstanceConfig.instance
osh = ObjectStateHolder('amazon_ec2_config')
osh.setStringAttribute('name', am... | the_stack_v2_python_sparse | UCMDBPython/src/ec2.py | kvt11/dd-git | train | 0 | |
dddbc0ac35641e9c513b49719b9cc79cbd454b68 | [
"differences = rewards.compute_squared_differences(WALKER_FEATURES, REFERENCE_FEATURES)\nfor key, difference in differences.items():\n self.assertEqual(difference, EXPECTED_DIFFERENCES[key])",
"differences = rewards.compute_squared_differences(WALKER_FEATURES, REFERENCE_FEATURES, exclude_keys=EXCLUDE_KEYS)\nfo... | <|body_start_0|>
differences = rewards.compute_squared_differences(WALKER_FEATURES, REFERENCE_FEATURES)
for key, difference in differences.items():
self.assertEqual(difference, EXPECTED_DIFFERENCES[key])
<|end_body_0|>
<|body_start_1|>
differences = rewards.compute_squared_differenc... | RewardsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardsTest:
def test_compute_squared_differences(self):
"""Basic usage."""
<|body_0|>
def test_compute_squared_differences_exclude_keys(self):
"""Test excluding some keys from squared difference computation."""
<|body_1|>
def test_compute_squared_differ... | stack_v2_sparse_classes_36k_train_014489 | 2,717 | permissive | [
{
"docstring": "Basic usage.",
"name": "test_compute_squared_differences",
"signature": "def test_compute_squared_differences(self)"
},
{
"docstring": "Test excluding some keys from squared difference computation.",
"name": "test_compute_squared_differences_exclude_keys",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_010408 | Implement the Python class `RewardsTest` described below.
Class description:
Implement the RewardsTest class.
Method signatures and docstrings:
- def test_compute_squared_differences(self): Basic usage.
- def test_compute_squared_differences_exclude_keys(self): Test excluding some keys from squared difference computa... | Implement the Python class `RewardsTest` described below.
Class description:
Implement the RewardsTest class.
Method signatures and docstrings:
- def test_compute_squared_differences(self): Basic usage.
- def test_compute_squared_differences_exclude_keys(self): Test excluding some keys from squared difference computa... | d6f9cb4e4a616d1e1d3bd8944bc89541434f1d49 | <|skeleton|>
class RewardsTest:
def test_compute_squared_differences(self):
"""Basic usage."""
<|body_0|>
def test_compute_squared_differences_exclude_keys(self):
"""Test excluding some keys from squared difference computation."""
<|body_1|>
def test_compute_squared_differ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RewardsTest:
def test_compute_squared_differences(self):
"""Basic usage."""
differences = rewards.compute_squared_differences(WALKER_FEATURES, REFERENCE_FEATURES)
for key, difference in differences.items():
self.assertEqual(difference, EXPECTED_DIFFERENCES[key])
def te... | the_stack_v2_python_sparse | dm_control/locomotion/tasks/reference_pose/rewards_test.py | wangsd01/dm_control | train | 0 | |
323f137b35fe341a868599f7a62c868edeebaf91 | [
"result = {'errcode': 0, 'msg': None}\nid = request.GET.get('id', None)\nqueryset = Menu.objects.only('id', 'title').all()\nrole = Role.objects.filter(id=id).first()\nper_list = []\nif role:\n role_menus = role.menu.only('id', 'title').all()\n menu_ids = [ru.id for ru in role_menus]\n for m in queryset:\n ... | <|body_start_0|>
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', None)
queryset = Menu.objects.only('id', 'title').all()
role = Role.objects.filter(id=id).first()
per_list = []
if role:
role_menus = role.menu.only('id', 'title').all()
... | GetRoleAllMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
<|body_0|>
def post(self, request, **kwargs):
"""修改 角色的用户信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', N... | stack_v2_sparse_classes_36k_train_014490 | 6,998 | no_license | [
{
"docstring": "获取当前角色的所有权限",
"name": "get",
"signature": "def get(self, request, **kwargs)"
},
{
"docstring": "修改 角色的用户信息",
"name": "post",
"signature": "def post(self, request, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021378 | Implement the Python class `GetRoleAllMenu` described below.
Class description:
Implement the GetRoleAllMenu class.
Method signatures and docstrings:
- def get(self, request, **kwargs): 获取当前角色的所有权限
- def post(self, request, **kwargs): 修改 角色的用户信息 | Implement the Python class `GetRoleAllMenu` described below.
Class description:
Implement the GetRoleAllMenu class.
Method signatures and docstrings:
- def get(self, request, **kwargs): 获取当前角色的所有权限
- def post(self, request, **kwargs): 修改 角色的用户信息
<|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs... | 9ceeecd85fdfd52fb90ebac7cc17092476877640 | <|skeleton|>
class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
<|body_0|>
def post(self, request, **kwargs):
"""修改 角色的用户信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetRoleAllMenu:
def get(self, request, **kwargs):
"""获取当前角色的所有权限"""
result = {'errcode': 0, 'msg': None}
id = request.GET.get('id', None)
queryset = Menu.objects.only('id', 'title').all()
role = Role.objects.filter(id=id).first()
per_list = []
if role:
... | the_stack_v2_python_sparse | user/api.py | vanwt/ttcmdb | train | 1 | |
20b7ba6876119169e2a6403e797dc43e9c1161ed | [
"super(RelPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1) * 2 - 1:\n if self.pe.dtype != x.dtype or self.pe.device != x.device:\n self.pe = self.pe.t... | <|body_start_0|>
super(RelPositionalEncoding, self).__init__()
self.d_model = d_model
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>
if self.pe is not None:
if self.pe.size(1) >= x.size(1) * 2 - 1:
... | Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. | RelPositionalEncoding | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length."""
def __init__(self, max_len, d_model):
"""Construct an PositionalEncoding object."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_014491 | 4,950 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, max_len, d_model)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
"docstring": "Add positional enco... | 3 | null | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, max_len, d_model): Cons... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, max_len, d_model): Cons... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length."""
def __init__(self, max_len, d_model):
"""Construct an PositionalEncoding object."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length."""
def __init__(self, max_len, d_model):
"""Construct an PositionalEncoding object."""
super(RelPositionalEnco... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/positional_encoding.py | microsoft/unilm | train | 15,313 |
ce98243afa4fc7e5ce7810748beff8c2a791c298 | [
"if surface is not None:\n self.t = surface.index\n assert np.all(self.t == profile.index.unique())\n self.surface = surface\nelse:\n self.t = profile.index.unique()\n self.surface = pd.DataFrame(index=self.t)\nself.z = profile['z'].unique()\nself.info = info\nself.N = len(self.z)\nself.info['levels'... | <|body_start_0|>
if surface is not None:
self.t = surface.index
assert np.all(self.t == profile.index.unique())
self.surface = surface
else:
self.t = profile.index.unique()
self.surface = pd.DataFrame(index=self.t)
self.z = profile['z']... | MMCdata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p... | stack_v2_sparse_classes_36k_train_014492 | 6,740 | no_license | [
{
"docstring": "Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFrame, optional Dataframe with datetime index and columns corresponding ... | 3 | stack_v2_sparse_classes_30k_train_009142 | Implement the Python class `MMCdata` described below.
Class description:
Implement the MMCdata class.
Method signatures and docstrings:
- def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor... | Implement the Python class `MMCdata` described below.
Class description:
Implement the MMCdata class.
Method signatures and docstrings:
- def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor... | c34afb2a13fc0075f95a43bac99219b25b3984a2 | <|skeleton|>
class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFram... | the_stack_v2_python_sparse | MMC/output_profile.py | ewquon/pylib | train | 2 | |
a8aad59557f6bd2a5436ff736fe9bbad0f0830e2 | [
"MAX = float('inf')\ndp = [0] + [MAX] * amount\nfor i in xrange(1, len(dp)):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1\nreturn [dp[amount], -1][dp[amount] == MAX]",
"if amount == 0:\n return 0\nvalue1 = [0]\nvalue2 = []\nnc = 0\nvisited = [False] * (amount + 1)\nvisited[0] = True\... | <|body_start_0|>
MAX = float('inf')
dp = [0] + [MAX] * amount
for i in xrange(1, len(dp)):
dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1
return [dp[amount], -1][dp[amount] == MAX]
<|end_body_0|>
<|body_start_1|>
if amount == 0:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_014493 | 1,469 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange2",
"signature": "def coinChange2(self, coins, amou... | 2 | stack_v2_sparse_classes_30k_train_007101 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
MAX = float('inf')
dp = [0] + [MAX] * amount
for i in xrange(1, len(dp)):
dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1
return [dp[... | the_stack_v2_python_sparse | prob322_coin_change.py | Hu-Wenchao/leetcode | train | 0 | |
1b092a95b449c370c424c99435276797fe30572d | [
"super(GradientAccumulationOptimizer, self).__init__(opt, name)\nif num_mini_batches < 1:\n raise ValueError('num_mini_batches must be a positive number.')\nself._num_mini_batches = num_mini_batches\nself._verify_usage = verify_usage",
"summed_grads_and_vars = []\nfor grad, var in grads_and_vars:\n if grad ... | <|body_start_0|>
super(GradientAccumulationOptimizer, self).__init__(opt, name)
if num_mini_batches < 1:
raise ValueError('num_mini_batches must be a positive number.')
self._num_mini_batches = num_mini_batches
self._verify_usage = verify_usage
<|end_body_0|>
<|body_start_1|... | An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural networks allows us to simulate bigger batch sizes. For exam... | GradientAccumulationOptimizer | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural ne... | stack_v2_sparse_classes_36k_train_014494 | 18,009 | permissive | [
{
"docstring": "Construct a Gradient Accumulation Optimizer. Args: opt: An existing `Optimizer` to encapsulate. num_mini_batches: Number of mini-batches the gradients will be accumulated for. verify_usage: The current gradient accumulation supports the `GradientDescentOptimizer` and `MomentumOptimizer` optimize... | 2 | stack_v2_sparse_classes_30k_train_008846 | Implement the Python class `GradientAccumulationOptimizer` described below.
Class description:
An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the w... | Implement the Python class `GradientAccumulationOptimizer` described below.
Class description:
An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the w... | 085b20a4b6287eff8c0b792425d52422ab8cbab3 | <|skeleton|>
class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientAccumulationOptimizer:
"""An optimizer where instead of performing the weight update for every batch, gradients across multiple batches are accumulated. After multiple batches have been processed, their accumulated gradients are used to compute the weight update. This feature of neural networks allows... | the_stack_v2_python_sparse | tensorflow/python/ipu/optimizers/gradient_accumulation_optimizer.py | graphcore/tensorflow | train | 84 |
c507992cb6ca25f4ca944f6988d0a8c37cb4ba84 | [
"self.size = size\nself.len = 0\nself.data = []",
"self.data.append(val)\nself.len += 1\nif self.len > self.size:\n del self.data[0]\n self.len -= 1\nprint(self.data)\nreturn 1.0 * sum(self.data) / self.len"
] | <|body_start_0|>
self.size = size
self.len = 0
self.data = []
<|end_body_0|>
<|body_start_1|>
self.data.append(val)
self.len += 1
if self.len > self.size:
del self.data[0]
self.len -= 1
print(self.data)
return 1.0 * sum(self.data) ... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.len = 0... | stack_v2_sparse_classes_36k_train_014495 | 999 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003835 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 24cf8d5f1831e838ea99f50ce4d8f048bd46c136 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.len = 0
self.data = []
def next(self, val):
""":type val: int :rtype: float"""
self.data.append(val)
self.len += 1
if s... | the_stack_v2_python_sparse | python/346_moving_average_from_data_stream.py | jixinfeng/leetcode-soln | train | 0 | |
9ca3adf43bd6d398de39d4cb662a00b5b7c5ed07 | [
"super().__init__(model, params)\nself._var_scope = 'decoder_d'\nself._n_classes = 0\nif 'n_classes' in params.keys():\n self._n_classes = params['n_classes']\nself._init_optimizer()",
"def layer(input, n_filters):\n convolution = tf.layers.conv3d(inputs=input, filters=n_filters, kernel_size=conv_kernel_siz... | <|body_start_0|>
super().__init__(model, params)
self._var_scope = 'decoder_d'
self._n_classes = 0
if 'n_classes' in params.keys():
self._n_classes = params['n_classes']
self._init_optimizer()
<|end_body_0|>
<|body_start_1|>
def layer(input, n_filters):
... | debug implementation | DecoderD | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderD:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward network."""
<|body_1|>
def _loss(self, _data):
"""p... | stack_v2_sparse_classes_36k_train_014496 | 9,168 | permissive | [
{
"docstring": "Args: model: parent model object. params: dict() of parameters.",
"name": "__init__",
"signature": "def __init__(self, model, params)"
},
{
"docstring": "forward network.",
"name": "_network",
"signature": "def _network(self, input)"
},
{
"docstring": "prepare the... | 3 | stack_v2_sparse_classes_30k_train_008650 | Implement the Python class `DecoderD` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward network.
- def _loss(self, _data): prepare the loss... | Implement the Python class `DecoderD` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward network.
- def _loss(self, _data): prepare the loss... | 9546d7a01c2b3e17131f34aa1e916e514c052ea8 | <|skeleton|>
class DecoderD:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward network."""
<|body_1|>
def _loss(self, _data):
"""p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderD:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
super().__init__(model, params)
self._var_scope = 'decoder_d'
self._n_classes = 0
if 'n_classes' in params.keys():
... | the_stack_v2_python_sparse | networks/network_aae_v_lite.py | cosmoplankton-studio/cellular-probabilistic | train | 0 |
08fcec3b980c9b2c8b6d3ae532e08c5a1fae18b2 | [
"self._api_token = api_token\nself._client = GraphQLClient(api_server_url)\nif api_token:\n self._client.inject_token('bearer ' + api_token)",
"result = self._client.execute(query)\ndata = json.loads(result)\nreturn data"
] | <|body_start_0|>
self._api_token = api_token
self._client = GraphQLClient(api_server_url)
if api_token:
self._client.inject_token('bearer ' + api_token)
<|end_body_0|>
<|body_start_1|>
result = self._client.execute(query)
data = json.loads(result)
return data... | GithubClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphq... | stack_v2_sparse_classes_36k_train_014497 | 987 | no_license | [
{
"docstring": "Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphql')",
"name": "__init__",
"signature": "def __init__(self, api_token, api_server_url='https://api... | 2 | stack_v2_sparse_classes_30k_train_000252 | Implement the Python class `GithubClient` described below.
Class description:
Implement the GithubClient class.
Method signatures and docstrings:
- def __init__(self, api_token, api_server_url='https://api.github.com/graphql'): Client to interact with github graphql API Parameters ---------- api_token : str Github AP... | Implement the Python class `GithubClient` described below.
Class description:
Implement the GithubClient class.
Method signatures and docstrings:
- def __init__(self, api_token, api_server_url='https://api.github.com/graphql'): Client to interact with github graphql API Parameters ---------- api_token : str Github AP... | 29d490ab1825594307097bdafa1a687bb9ddf80e | <|skeleton|>
class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphql')"""
... | the_stack_v2_python_sparse | findcrashedcodedeveloper/githubapi/client.py | karambir252/findcrashedcodedeveloper | train | 0 | |
a79b236c599dd279e73918862a4bc6bd08b56819 | [
"super().__init__(arg)\nself.headers = headers\nself.path = path\nself.path_params = path_params\nself.query_params = query_params\nself.accepted: bool = False\n'Whether the message was ever accepted by the server'\nself.close: Optional[Tuple[Sender, int]] = None\n'The sender who closed the connection, along with t... | <|body_start_0|>
super().__init__(arg)
self.headers = headers
self.path = path
self.path_params = path_params
self.query_params = query_params
self.accepted: bool = False
'Whether the message was ever accepted by the server'
self.close: Optional[Tuple[Send... | A transcript of a single websocket connection | RecordedWSTranscript | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordedWSTranscript:
"""A transcript of a single websocket connection"""
def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]):
"""Args: arg: forwarded to super (List) heade... | stack_v2_sparse_classes_36k_train_014498 | 20,254 | permissive | [
{
"docstring": "Args: arg: forwarded to super (List) headers: the headers of the connection path: the path of the connection request path_params: the path params of the connection request, as specified by the route's starlette rule string query_params: the query params of the connection request",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_012859 | Implement the Python class `RecordedWSTranscript` described below.
Class description:
A transcript of a single websocket connection
Method signatures and docstrings:
- def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str... | Implement the Python class `RecordedWSTranscript` described below.
Class description:
A transcript of a single websocket connection
Method signatures and docstrings:
- def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str... | 1914e42f33f8758d25cc985d672aaa3855ee9261 | <|skeleton|>
class RecordedWSTranscript:
"""A transcript of a single websocket connection"""
def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]):
"""Args: arg: forwarded to super (List) heade... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordedWSTranscript:
"""A transcript of a single websocket connection"""
def __init__(self, arg: Iterable[RecordedWSMessage], headers: Dict[bytes, List[bytes]], path: str, path_params: Dict[str, Any], query_params: Dict[str, List[str]]):
"""Args: arg: forwarded to super (List) headers: the heade... | the_stack_v2_python_sparse | yellowbox/extras/webserver/ws_request_capture.py | nx6110a5100/yellowbox | train | 0 |
a233d8307608f62c0fec85d80ac3d21cb07be425 | [
"super(Attention, self).__init__()\nself.attn_method = attn_method\nself.input_dim = input_dim\nself.nonlinear_func = nonlinear_func\nself.device = get_device(to_gpu, gpu_index)\nself.fdtype = config.get('fdtype', torch.float32)\nself.bidirectional_concat_flag = config.get('bidirectional_concat_flag', False)\nif se... | <|body_start_0|>
super(Attention, self).__init__()
self.attn_method = attn_method
self.input_dim = input_dim
self.nonlinear_func = nonlinear_func
self.device = get_device(to_gpu, gpu_index)
self.fdtype = config.get('fdtype', torch.float32)
self.bidirectional_conca... | Attention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0):
"""Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_dim: int, size of the input vector (i.e. sentence vector representation)"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_014499 | 24,409 | no_license | [
{
"docstring": "Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_dim: int, size of the input vector (i.e. sentence vector representation)",
"name": "__init__",
"signature": "def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0)"
},... | 2 | null | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0): Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_d... | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0): Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_d... | f4c08cca00eea9dea15341b4abde56542372277e | <|skeleton|>
class Attention:
def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0):
"""Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_dim: int, size of the input vector (i.e. sentence vector representation)"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
def __init__(self, attn_method, input_dim, nonlinear_func=torch.tanh, config={}, to_gpu=True, gpu_index=0):
"""Args: attn_method: string, {'additive', 'dot', 'dot_scaled'} input_dim: int, size of the input vector (i.e. sentence vector representation)"""
super(Attention, self).__init... | the_stack_v2_python_sparse | neural/model.py | 2018luyi/auto-discern | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.