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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b3b8aef461926e771e8748320838a3fa9e19765 | [
"class UrlsCls(UrlsMixin, InvenTreePlugin):\n\n def test():\n return 'ccc'\n URLS = [re_path('testpath', test, name='test')]\nself.mixin = UrlsCls()\n\nclass NoUrlsCls(UrlsMixin, InvenTreePlugin):\n pass\nself.mixin_nothing = NoUrlsCls()",
"plg_name = self.mixin.plugin_name()\ntarget_url = f'{PLUG... | <|body_start_0|>
class UrlsCls(UrlsMixin, InvenTreePlugin):
def test():
return 'ccc'
URLS = [re_path('testpath', test, name='test')]
self.mixin = UrlsCls()
class NoUrlsCls(UrlsMixin, InvenTreePlugin):
pass
self.mixin_nothing = NoUrlsC... | Tests for UrlsMixin. | UrlsMixinTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlsMixinTest:
"""Tests for UrlsMixin."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def test_function(self):
"""Test that the mixin functions."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
class UrlsCls(UrlsMixin, InvenTreePlugin)... | stack_v2_sparse_classes_36k_train_017800 | 14,946 | permissive | [
{
"docstring": "Setup for all tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the mixin functions.",
"name": "test_function",
"signature": "def test_function(self)"
}
] | 2 | null | Implement the Python class `UrlsMixinTest` described below.
Class description:
Tests for UrlsMixin.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def test_function(self): Test that the mixin functions. | Implement the Python class `UrlsMixinTest` described below.
Class description:
Tests for UrlsMixin.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def test_function(self): Test that the mixin functions.
<|skeleton|>
class UrlsMixinTest:
"""Tests for UrlsMixin."""
def setUp(self)... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class UrlsMixinTest:
"""Tests for UrlsMixin."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def test_function(self):
"""Test that the mixin functions."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UrlsMixinTest:
"""Tests for UrlsMixin."""
def setUp(self):
"""Setup for all tests."""
class UrlsCls(UrlsMixin, InvenTreePlugin):
def test():
return 'ccc'
URLS = [re_path('testpath', test, name='test')]
self.mixin = UrlsCls()
class ... | the_stack_v2_python_sparse | InvenTree/plugin/base/integration/test_mixins.py | inventree/InvenTree | train | 3,077 |
781fbb510cb879dfc1d1b592600753ccc8f5e717 | [
"context = super(ScenarioView, self).get_context_data(**kwargs)\ncontext['scenario_objects'] = scenario.objects.filter(Q(created_by=self.request.user) | Q(is_public=True)).order_by('-id')\ncontext['can_post_public'] = additionalUserInfo.objects.get(user_id=self.request.user.id).post_public\nreturn context",
"if r... | <|body_start_0|>
context = super(ScenarioView, self).get_context_data(**kwargs)
context['scenario_objects'] = scenario.objects.filter(Q(created_by=self.request.user) | Q(is_public=True)).order_by('-id')
context['can_post_public'] = additionalUserInfo.objects.get(user_id=self.request.user.id).pos... | ScenarioView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScenarioView:
def get_context_data(self, **kwargs):
"""Returns context-specific variables to be used in rendering the template."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Handles the general view (when non-ajax) or gets information about a particular s... | stack_v2_sparse_classes_36k_train_017801 | 15,384 | no_license | [
{
"docstring": "Returns context-specific variables to be used in rendering the template.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Handles the general view (when non-ajax) or gets information about a particular scenario (when ajax)",
... | 2 | stack_v2_sparse_classes_30k_train_006041 | Implement the Python class `ScenarioView` described below.
Class description:
Implement the ScenarioView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Returns context-specific variables to be used in rendering the template.
- def get(self, request, *args, **kwargs): Handles the gene... | Implement the Python class `ScenarioView` described below.
Class description:
Implement the ScenarioView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Returns context-specific variables to be used in rendering the template.
- def get(self, request, *args, **kwargs): Handles the gene... | eb49d85915d37804d0370bcd5d4db4f8949736aa | <|skeleton|>
class ScenarioView:
def get_context_data(self, **kwargs):
"""Returns context-specific variables to be used in rendering the template."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Handles the general view (when non-ajax) or gets information about a particular s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScenarioView:
def get_context_data(self, **kwargs):
"""Returns context-specific variables to be used in rendering the template."""
context = super(ScenarioView, self).get_context_data(**kwargs)
context['scenario_objects'] = scenario.objects.filter(Q(created_by=self.request.user) | Q(is... | the_stack_v2_python_sparse | frontend/views/scenarioViews.py | SwissTPH/openmalaria.web-portal | train | 0 | |
a45d4cbc14a34a8be713dea9c7350189f090ba84 | [
"self.type = feature_type\nself.feature_data = {}\nself.feature_data_xyz = {}",
"for name, data in self.feature_data.items():\n ds = []\n for key, value in data.items():\n if len(key) == 3:\n feat = '{:>4}{:>10}{:>10}'.format(key[0], key[1], key[2])\n elif len(key) == 4:\n ... | <|body_start_0|>
self.type = feature_type
self.feature_data = {}
self.feature_data_xyz = {}
<|end_body_0|>
<|body_start_1|>
for name, data in self.feature_data.items():
ds = []
for key, value in data.items():
if len(key) == 3:
... | FeatureClass | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureClass:
def __init__(self, feature_type):
"""Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each subclass must compute: - self.feature_data: dictionary of features in human readable format, e.g. - fo... | stack_v2_sparse_classes_36k_train_017802 | 5,768 | permissive | [
{
"docstring": "Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each subclass must compute: - self.feature_data: dictionary of features in human readable format, e.g. - for atomic features: - {'coulomb': data_dict_clb, 'vdwaals': ... | 4 | stack_v2_sparse_classes_30k_train_020748 | Implement the Python class `FeatureClass` described below.
Class description:
Implement the FeatureClass class.
Method signatures and docstrings:
- def __init__(self, feature_type): Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each s... | Implement the Python class `FeatureClass` described below.
Class description:
Implement the FeatureClass class.
Method signatures and docstrings:
- def __init__(self, feature_type): Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each s... | 6bc8d7e4893fc06f952d6e2b1edfc4e1c19bc671 | <|skeleton|>
class FeatureClass:
def __init__(self, feature_type):
"""Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each subclass must compute: - self.feature_data: dictionary of features in human readable format, e.g. - fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureClass:
def __init__(self, feature_type):
"""Master class from which all the other feature classes should be derived. Arguments feature_type(str): 'Atomic' or 'Residue' Note: Each subclass must compute: - self.feature_data: dictionary of features in human readable format, e.g. - for atomic featu... | the_stack_v2_python_sparse | deeprank/features/FeatureClass.py | DeepRank/deeprank | train | 140 | |
74769ddb370198b69f3b0b9aa950255f0798fd88 | [
"self._num_participants = num_participants\nself._counter = 0\nself._flag = False\nself._local_sense = threading.local()\nself._lock = threading.Lock()\nself._condition = threading.Condition()",
"self._local_sense.value = not self._flag\nwith self._lock:\n self._counter += 1\n if self._counter == self._num_... | <|body_start_0|>
self._num_participants = num_participants
self._counter = 0
self._flag = False
self._local_sense = threading.local()
self._lock = threading.Lock()
self._condition = threading.Condition()
<|end_body_0|>
<|body_start_1|>
self._local_sense.value = n... | A reusable barrier class for worker synchronization. | _Barrier | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_017803 | 34,550 | permissive | [
{
"docstring": "Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier.",
"name": "__init__",
"signature": "def __init__(self, num_participants)"
},
{
"docstring": "Waits until all other callers reach the sa... | 2 | stack_v2_sparse_classes_30k_train_008288 | Implement the Python class `_Barrier` described below.
Class description:
A reusable barrier class for worker synchronization.
Method signatures and docstrings:
- def __init__(self, num_participants): Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pa... | Implement the Python class `_Barrier` described below.
Class description:
A reusable barrier class for worker synchronization.
Method signatures and docstrings:
- def __init__(self, num_participants): Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pa... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
self._num_participants = num_pa... | the_stack_v2_python_sparse | tensorflow/python/distribute/distribute_coordinator.py | tensorflow/tensorflow | train | 208,740 |
1d4bf16cede0f8688702ef4f98dc7ea51d318dc6 | [
"if root is None:\n return 0\nleft_height = self.maxDepth(root.left)\nright_height = self.maxDepth(root.right)\nreturn max(left_height, right_height) + 1",
"stack = []\nif root is not None:\n stack.append((1, root))\ndepth = 0\nwhile stack != []:\n current_depth, root = stack.pop()\n if root is not No... | <|body_start_0|>
if root is None:
return 0
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
<|end_body_0|>
<|body_start_1|>
stack = []
if root is not None:
stack.append((1, r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归实现 DFS"""
<|body_0|>
def maxDepth2(self, root: TreeNode) -> int:
"""栈实现 DFS 76 ms 14.9 MB"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
left_he... | stack_v2_sparse_classes_36k_train_017804 | 1,790 | no_license | [
{
"docstring": "递归实现 DFS",
"name": "maxDepth",
"signature": "def maxDepth(self, root: TreeNode) -> int"
},
{
"docstring": "栈实现 DFS 76 ms 14.9 MB",
"name": "maxDepth2",
"signature": "def maxDepth2(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_006264 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: TreeNode) -> int: 递归实现 DFS
- def maxDepth2(self, root: TreeNode) -> int: 栈实现 DFS 76 ms 14.9 MB | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: TreeNode) -> int: 递归实现 DFS
- def maxDepth2(self, root: TreeNode) -> int: 栈实现 DFS 76 ms 14.9 MB
<|skeleton|>
class Solution:
def maxDepth(self, root... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归实现 DFS"""
<|body_0|>
def maxDepth2(self, root: TreeNode) -> int:
"""栈实现 DFS 76 ms 14.9 MB"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root: TreeNode) -> int:
"""递归实现 DFS"""
if root is None:
return 0
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
def maxDepth2(self, root: TreeNode) -... | the_stack_v2_python_sparse | 算法/maxDepth.py | 1oser5/LeetCode | train | 0 | |
f43c24c0071dc7d63c308c06a9e4bf8dacfe2494 | [
"actual = a1.swap_k([], 2)\nexpected = []\nself.assertEqual(expected, actual)",
"actual = a1.swap_k([1], 5)\nexpected = [1]\nself.assertEqual(expected, actual)",
"actual = a1.swap_k([1, 2], 1)\nexpected = [2, 1]\nself.assertEqual(expected, actual)",
"actual = a1.swap_k([1, 2], 2)\nexpected = [1, 2]\nself.asse... | <|body_start_0|>
actual = a1.swap_k([], 2)
expected = []
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
actual = a1.swap_k([1], 5)
expected = [1]
self.assertEqual(expected, actual)
<|end_body_1|>
<|body_start_2|>
actual = a1.swap_k([1, 2], 1)... | Test class for function a1.swap_k. | TestSwapK | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_example_1(self):
"""Test nswap_k with [] and 2."""
<|body_0|>
def test_swap_k_example_2(self):
"""Test nswap_k with [1] and 5."""
<|body_1|>
def test_swap_k_example_3(self):
... | stack_v2_sparse_classes_36k_train_017805 | 1,440 | permissive | [
{
"docstring": "Test nswap_k with [] and 2.",
"name": "test_swap_k_example_1",
"signature": "def test_swap_k_example_1(self)"
},
{
"docstring": "Test nswap_k with [1] and 5.",
"name": "test_swap_k_example_2",
"signature": "def test_swap_k_example_2(self)"
},
{
"docstring": "Test ... | 6 | null | Implement the Python class `TestSwapK` described below.
Class description:
Test class for function a1.swap_k.
Method signatures and docstrings:
- def test_swap_k_example_1(self): Test nswap_k with [] and 2.
- def test_swap_k_example_2(self): Test nswap_k with [1] and 5.
- def test_swap_k_example_3(self): Test nswap_k... | Implement the Python class `TestSwapK` described below.
Class description:
Test class for function a1.swap_k.
Method signatures and docstrings:
- def test_swap_k_example_1(self): Test nswap_k with [] and 2.
- def test_swap_k_example_2(self): Test nswap_k with [1] and 5.
- def test_swap_k_example_3(self): Test nswap_k... | fa566235d6b9751f73c69d0d46351a14fcdeb585 | <|skeleton|>
class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_example_1(self):
"""Test nswap_k with [] and 2."""
<|body_0|>
def test_swap_k_example_2(self):
"""Test nswap_k with [1] and 5."""
<|body_1|>
def test_swap_k_example_3(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_example_1(self):
"""Test nswap_k with [] and 2."""
actual = a1.swap_k([], 2)
expected = []
self.assertEqual(expected, actual)
def test_swap_k_example_2(self):
"""Test nswap_k with [1] and 5.""... | the_stack_v2_python_sparse | University-of-Toronto-Crafting-Quality-Code/pset1_unittest_test_cases/test_swap_k.py | Mudasirrr/Courses- | train | 2 |
c1e30ed339ffdc2b8b089ffd3d15881610c31a28 | [
"self.m_Cap = capacity\nself.m_Cnt = 0\nself.m_Info = OrderedDict()",
"if key in self.m_Info:\n val = self.m_Info[key]\n del self.m_Info[key]\n self.m_Info[key] = val\n return val\nreturn -1",
"if key in self.m_Info:\n del self.m_Info[key]\n self.m_Info[key] = value\n return\nself.m_Cnt += ... | <|body_start_0|>
self.m_Cap = capacity
self.m_Cnt = 0
self.m_Info = OrderedDict()
<|end_body_0|>
<|body_start_1|>
if key in self.m_Info:
val = self.m_Info[key]
del self.m_Info[key]
self.m_Info[key] = val
return val
return -1
<|end_... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_017806 | 1,172 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_003755 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 818833ca87e8dbf964c0743d8381408964d37c71 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.m_Cap = capacity
self.m_Cnt = 0
self.m_Info = OrderedDict()
def get(self, key):
""":type key: int :rtype: int"""
if key in self.m_Info:
val = self.m_Info[key]
del... | the_stack_v2_python_sparse | 100-199/146-lru-cache.py | lamborghini1993/LeetCode | train | 0 | |
9a6a4715c618d8ca04ed8790b77e3ca623c601de | [
"self.cause_var = cause_var\nself.effect_var = effect_var\nself.cause_states = cause_states\nself.effect_states = effect_states\nself.cause_cprob = cause_cprob\nself.effect_cprob = effect_cprob\nself.grid = grid",
"g = self.grid\nquery_nodes = []\nfor vname in disc_bn.V:\n query_name = \"'\" + self.effect_var ... | <|body_start_0|>
self.cause_var = cause_var
self.effect_var = effect_var
self.cause_states = cause_states
self.effect_states = effect_states
self.cause_cprob = cause_cprob
self.effect_cprob = effect_cprob
self.grid = grid
<|end_body_0|>
<|body_start_1|>
g... | This type or rule creates a grid and group by the center of the cell. | GridRule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridRule:
"""This type or rule creates a grid and group by the center of the cell."""
def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid):
"""Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect vari... | stack_v2_sparse_classes_36k_train_017807 | 3,558 | no_license | [
{
"docstring": "Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) ----> TRIGGER. :param cause_states: possible states of the cause variable (str[]) :param effect_states: possible states of the effect variable (str[]) :param cause_cprob: Conditional Probability ... | 2 | stack_v2_sparse_classes_30k_train_000047 | Implement the Python class `GridRule` described below.
Class description:
This type or rule creates a grid and group by the center of the cell.
Method signatures and docstrings:
- def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid): Construct. :param cause_var: caus... | Implement the Python class `GridRule` described below.
Class description:
This type or rule creates a grid and group by the center of the cell.
Method signatures and docstrings:
- def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid): Construct. :param cause_var: caus... | 961a7102f0be273bb962eba211a7144535753c2d | <|skeleton|>
class GridRule:
"""This type or rule creates a grid and group by the center of the cell."""
def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid):
"""Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect vari... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridRule:
"""This type or rule creates a grid and group by the center of the cell."""
def __init__(self, cause_var, effect_var, cause_states, effect_states, cause_cprob, effect_cprob, grid):
"""Construct. :param cause_var: cause variable or parent (str) :param effect_var: effect variable (str) --... | the_stack_v2_python_sparse | inference-engine/infengine/rules/GridRule.py | verlab/perceptive-turtles | train | 0 |
c50665eaba2bea1a104d7e7cb27c2909f1c9cb61 | [
"if self is self.STREAMING:\n return 'StreamEncoder'\nif self is self.MEMORY:\n return 'MemoryEncoder'\nraise ValueError('Unknown encoder type')",
"if self is self.STREAMING:\n return 'StreamEncoder'\nif self is self.MEMORY:\n return 'MemoryEncoder'\nraise ValueError('Unknown encoder type')"
] | <|body_start_0|>
if self is self.STREAMING:
return 'StreamEncoder'
if self is self.MEMORY:
return 'MemoryEncoder'
raise ValueError('Unknown encoder type')
<|end_body_0|>
<|body_start_1|>
if self is self.STREAMING:
return 'StreamEncoder'
if sel... | EncoderType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_0|>
def codegen_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017808 | 24,939 | permissive | [
{
"docstring": "Returns the base class used by this encoder type.",
"name": "base_class_name",
"signature": "def base_class_name(self) -> str"
},
{
"docstring": "Returns the base class used by this encoder type.",
"name": "codegen_class_name",
"signature": "def codegen_class_name(self) -... | 2 | stack_v2_sparse_classes_30k_train_020166 | Implement the Python class `EncoderType` described below.
Class description:
Implement the EncoderType class.
Method signatures and docstrings:
- def base_class_name(self) -> str: Returns the base class used by this encoder type.
- def codegen_class_name(self) -> str: Returns the base class used by this encoder type. | Implement the Python class `EncoderType` described below.
Class description:
Implement the EncoderType class.
Method signatures and docstrings:
- def base_class_name(self) -> str: Returns the base class used by this encoder type.
- def codegen_class_name(self) -> str: Returns the base class used by this encoder type.... | 7f3590b58e8398aad68c1e59702c459d2f8ca38e | <|skeleton|>
class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_0|>
def codegen_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderType:
def base_class_name(self) -> str:
"""Returns the base class used by this encoder type."""
if self is self.STREAMING:
return 'StreamEncoder'
if self is self.MEMORY:
return 'MemoryEncoder'
raise ValueError('Unknown encoder type')
def code... | the_stack_v2_python_sparse | pw_protobuf/py/pw_protobuf/codegen_pwpb.py | waelbarakat/pigweed | train | 0 | |
d818a017cc45b4bb3155697ac0730247818726aa | [
"validate_certificate = True if verify else False\nurl_with_params = '{url}?{params}'.format(url=url, params=urllib.urlencode(params))\nnewheaders = copy.deepcopy(headers)\nnewheaders['User-Agent'] = _get_user_agent_header()\ntry:\n result = urlfetch.fetch(url=url_with_params, method=method, headers=newheaders, ... | <|body_start_0|>
validate_certificate = True if verify else False
url_with_params = '{url}?{params}'.format(url=url, params=urllib.urlencode(params))
newheaders = copy.deepcopy(headers)
newheaders['User-Agent'] = _get_user_agent_header()
try:
result = urlfetch.fetch(u... | HTTP client based on Google App Engine `urlfetch` module. | URLFetchClient | [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLFetchClient:
"""HTTP client based on Google App Engine `urlfetch` module."""
def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries):
"""Wrapper around `urlfetch.fetch` method. TO IMPLEMENT: * `max_retries`"""
<|body_0|>
def raise_o... | stack_v2_sparse_classes_36k_train_017809 | 6,465 | permissive | [
{
"docstring": "Wrapper around `urlfetch.fetch` method. TO IMPLEMENT: * `max_retries`",
"name": "request",
"signature": "def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries)"
},
{
"docstring": "Raise on HTTP status code errors.",
"name": "raise_on_statu... | 2 | stack_v2_sparse_classes_30k_train_008355 | Implement the Python class `URLFetchClient` described below.
Class description:
HTTP client based on Google App Engine `urlfetch` module.
Method signatures and docstrings:
- def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries): Wrapper around `urlfetch.fetch` method. TO IMPLEMEN... | Implement the Python class `URLFetchClient` described below.
Class description:
HTTP client based on Google App Engine `urlfetch` module.
Method signatures and docstrings:
- def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries): Wrapper around `urlfetch.fetch` method. TO IMPLEMEN... | 11a38d0c8d6b156758e7500500d706b7159d18ed | <|skeleton|>
class URLFetchClient:
"""HTTP client based on Google App Engine `urlfetch` module."""
def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries):
"""Wrapper around `urlfetch.fetch` method. TO IMPLEMENT: * `max_retries`"""
<|body_0|>
def raise_o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URLFetchClient:
"""HTTP client based on Google App Engine `urlfetch` module."""
def request(cls, method, url, headers, params, data, timeout, proxies, verify, max_retries):
"""Wrapper around `urlfetch.fetch` method. TO IMPLEMENT: * `max_retries`"""
validate_certificate = True if verify el... | the_stack_v2_python_sparse | datadog/api/http_client.py | DataDog/datadogpy | train | 602 |
81d908f7c54c24e20bd364b396613cd8862d8403 | [
"resource = f'/luban-glxx-user/auth/info'\nresponse = item_fixture.request('GET', resource)\nreturn response",
"resource = f'/luban-glxx-user/auth/jsgl_redirect_login'\nquery_params = {'jsgl_token': jsgl_token}\nresponse = item_fixture.request('GET', resource, params=query_params)\nreturn response",
"resource =... | <|body_start_0|>
resource = f'/luban-glxx-user/auth/info'
response = item_fixture.request('GET', resource)
return response
<|end_body_0|>
<|body_start_1|>
resource = f'/luban-glxx-user/auth/jsgl_redirect_login'
query_params = {'jsgl_token': jsgl_token}
response = item_fi... | 鉴权模块 | Auth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
<|body_0|>
def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"... | stack_v2_sparse_classes_36k_train_017810 | 1,514 | no_license | [
{
"docstring": "登录信息查询接口 :param item_fixture: item fixture,",
"name": "getUserInfoUsingGET",
"signature": "def getUserInfoUsingGET(self, item_fixture)"
},
{
"docstring": "建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token",
"name": "loginFromJsglUsingGET",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_013769 | Implement the Python class `Auth` described below.
Class description:
鉴权模块
Method signatures and docstrings:
- def getUserInfoUsingGET(self, item_fixture): 登录信息查询接口 :param item_fixture: item fixture,
- def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None): 建管跳转登录接口 :param item_fixture: item fixture, :param j... | Implement the Python class `Auth` described below.
Class description:
鉴权模块
Method signatures and docstrings:
- def getUserInfoUsingGET(self, item_fixture): 登录信息查询接口 :param item_fixture: item fixture,
- def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None): 建管跳转登录接口 :param item_fixture: item fixture, :param j... | f875de62f7f505c596ea5567e1fc2c8a64010f87 | <|skeleton|>
class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
<|body_0|>
def loginFromJsglUsingGET(self, item_fixture, jsgl_token=None):
"""建管跳转登录接口 :param item_fixture: item fixture, :param jsgl_token: 建管系统token"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Auth:
"""鉴权模块"""
def getUserInfoUsingGET(self, item_fixture):
"""登录信息查询接口 :param item_fixture: item fixture,"""
resource = f'/luban-glxx-user/auth/info'
response = item_fixture.request('GET', resource)
return response
def loginFromJsglUsingGET(self, item_fixture, jsgl... | the_stack_v2_python_sparse | swagger/api/luban_glxx_user/auth.py | zhangjingwen198817/pytest-api-allure | train | 1 |
fec7700de7b07f68226f7ef00f1f1845d569f3d9 | [
"key_name = 'The Mark'\nthe_mark = db.get(datastore_types.Key.from_path(cls.kind(), key_name))\nif the_mark is None:\n next_start = now() - datetime.timedelta(seconds=60)\n the_mark = PollingMarker(key_name=key_name, next_start=next_start, current_key=None)\nreturn the_mark",
"now_time = now()\nif self.next... | <|body_start_0|>
key_name = 'The Mark'
the_mark = db.get(datastore_types.Key.from_path(cls.kind(), key_name))
if the_mark is None:
next_start = now() - datetime.timedelta(seconds=60)
the_mark = PollingMarker(key_name=key_name, next_start=next_start, current_key=None)
... | Keeps track of the current position in the bootstrap polling process. | PollingMarker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PollingMarker:
"""Keeps track of the current position in the bootstrap polling process."""
def get(cls, now=datetime.datetime.utcnow):
"""Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns the current time as a UTC datetime."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_017811 | 30,847 | no_license | [
{
"docstring": "Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns the current time as a UTC datetime.",
"name": "get",
"signature": "def get(cls, now=datetime.datetime.utcnow)"
},
{
"docstring": "Returns True if the bootstrap polling should progress. May modi... | 2 | stack_v2_sparse_classes_30k_train_020866 | Implement the Python class `PollingMarker` described below.
Class description:
Keeps track of the current position in the bootstrap polling process.
Method signatures and docstrings:
- def get(cls, now=datetime.datetime.utcnow): Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns th... | Implement the Python class `PollingMarker` described below.
Class description:
Keeps track of the current position in the bootstrap polling process.
Method signatures and docstrings:
- def get(cls, now=datetime.datetime.utcnow): Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns th... | e28ffc2c685a7ee92b0686462e61bb06255a65ac | <|skeleton|>
class PollingMarker:
"""Keeps track of the current position in the bootstrap polling process."""
def get(cls, now=datetime.datetime.utcnow):
"""Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns the current time as a UTC datetime."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PollingMarker:
"""Keeps track of the current position in the bootstrap polling process."""
def get(cls, now=datetime.datetime.utcnow):
"""Returns the current PollingMarker, creating it if it doesn't exist. Args: now: Returns the current time as a UTC datetime."""
key_name = 'The Mark'
... | the_stack_v2_python_sparse | hub/hubmodel.py | PaulKinlan/Amplifriend | train | 3 |
a60d8b6a0bb5ec7f98f890765c8f0d8cead01036 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Person()",
"from .entity import Entity\nfrom .location import Location\nfrom .person_type import PersonType\nfrom .phone import Phone\nfrom .scored_email_address import ScoredEmailAddress\nfrom .website import Website\nfrom .entity imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Person()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .location import Location
from .person_type import PersonType
from .phone import Phone
fr... | Person | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Person:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Person"""
... | stack_v2_sparse_classes_36k_train_017812 | 7,196 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Person",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_... | 3 | null | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Person: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Person: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Person:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Person:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Person"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Person:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Person:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Person"""
if not p... | the_stack_v2_python_sparse | msgraph/generated/models/person.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0bb2edf63a3c57dc8528f395bba0e90f4b97945d | [
"super(GraphAggregation, self).__init__()\nself.scale = scale\nself.patchsize = patchsize\nself.stride = stride\nself.k = k\nself.padding = padding",
"m = idx_k.shape[1]\nb, n, f = yd.shape\nk = self.k\nyd = yd.permute(0, 2, 1).contiguous()\nyd_e = yd.view(b, 1, f, n).expand(b, m, f, n)\nidx_k_e = idx_k.view(b, m... | <|body_start_0|>
super(GraphAggregation, self).__init__()
self.scale = scale
self.patchsize = patchsize
self.stride = stride
self.k = k
self.padding = padding
<|end_body_0|>
<|body_start_1|>
m = idx_k.shape[1]
b, n, f = yd.shape
k = self.k
... | Graph Aggregation | GraphAggregation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphAggregation:
"""Graph Aggregation"""
def __init__(self, scale, k, patchsize, stride, padding=None):
""":param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patches are extracted"""
<|body_0|>
def aggregati... | stack_v2_sparse_classes_36k_train_017813 | 11,701 | permissive | [
{
"docstring": ":param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patches are extracted",
"name": "__init__",
"signature": "def __init__(self, scale, k, patchsize, stride, padding=None)"
},
{
"docstring": ":param yd: database items,... | 3 | stack_v2_sparse_classes_30k_val_000155 | Implement the Python class `GraphAggregation` described below.
Class description:
Graph Aggregation
Method signatures and docstrings:
- def __init__(self, scale, k, patchsize, stride, padding=None): :param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patch... | Implement the Python class `GraphAggregation` described below.
Class description:
Graph Aggregation
Method signatures and docstrings:
- def __init__(self, scale, k, patchsize, stride, padding=None): :param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patch... | 32bfa7114cfa220b90a710855e56ebdadd84dd29 | <|skeleton|>
class GraphAggregation:
"""Graph Aggregation"""
def __init__(self, scale, k, patchsize, stride, padding=None):
""":param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patches are extracted"""
<|body_0|>
def aggregati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphAggregation:
"""Graph Aggregation"""
def __init__(self, scale, k, patchsize, stride, padding=None):
""":param k: number of neighbors :param patchsize: size of patches that are matched :param stride: stride with which patches are extracted"""
super(GraphAggregation, self).__init__()
... | the_stack_v2_python_sparse | models/graph_agg.py | cocowy1/IGNN | train | 0 |
aa7b06d4c33494cafd7a746fa40b3329c1105c38 | [
"nn.Module.__init__(self)\nself.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}\nself.num_inputs = num_inputs\nif b_values is None:\n self.a_... | <|body_start_0|>
nn.Module.__init__(self)
self.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}
self.num_inputs = num_inputs
... | MLP which uses Fourier features as a preprocessing step. | FourierFeatureMLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: torch.Tensor, b_values: torch.Tensor, layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number of dimensions in the inpu... | stack_v2_sparse_classes_36k_train_017814 | 17,353 | no_license | [
{
"docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output a_values (torch.Tensor): a values for encoding b_values (torch.Tensor): b values for encoding num_layers (int): Number of layers in the MLP layer_channels (List[int]): Num... | 3 | null | Implement the Python class `FourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: torch.Tensor, b_values: torch.Tensor, layer_channels: List[int]): Constructor.... | Implement the Python class `FourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: torch.Tensor, b_values: torch.Tensor, layer_channels: List[int]): Constructor.... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class FourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: torch.Tensor, b_values: torch.Tensor, layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number of dimensions in the inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: torch.Tensor, b_values: torch.Tensor, layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs... | the_stack_v2_python_sparse | generated/test_matajoh_fourier_feature_nets.py | jansel/pytorch-jit-paritybench | train | 35 |
31b553c5b2974bcc10b05798119d3f925969d73f | [
"PowerSpectrumSeries.__init__(self, *args, **kwargs)\nif not isinstance(self.overlay, fslmelimage.MelodicImage):\n raise ValueError('Overlay is not a MelodicImage')\nself.varNorm = False\nself.disableProperty('varNorm')",
"display = self.displayCtx.getDisplay(self.overlay)\nopts = display.opts\ncomponent = opt... | <|body_start_0|>
PowerSpectrumSeries.__init__(self, *args, **kwargs)
if not isinstance(self.overlay, fslmelimage.MelodicImage):
raise ValueError('Overlay is not a MelodicImage')
self.varNorm = False
self.disableProperty('varNorm')
<|end_body_0|>
<|body_start_1|>
disp... | The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property. | MelodicPowerSpectrumSeries | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MelodicPowerSpectrumSeries:
"""The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property."""
def __init__(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_017815 | 8,639 | permissive | [
{
"docstring": "Create a ``MelodicPowerSpectrumSeries``. All arguments are passed through to the :meth:`PowerSpectrumSeries.__init__` method.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Returns a label that can be used for this ``MelodicPowerSpectr... | 3 | stack_v2_sparse_classes_30k_train_018751 | Implement the Python class `MelodicPowerSpectrumSeries` described below.
Class description:
The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property.
Method signat... | Implement the Python class `MelodicPowerSpectrumSeries` described below.
Class description:
The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property.
Method signat... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class MelodicPowerSpectrumSeries:
"""The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property."""
def __init__(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MelodicPowerSpectrumSeries:
"""The ``MelodicPowerSpectrumSeries`` class encapsulates the power spectrum of the time course for a single component of a :class:`.MelodicImage`. The component is dictated by the :attr:`.NiftiOpts.volume` property."""
def __init__(self, *args, **kwargs):
"""Create a `... | the_stack_v2_python_sparse | fsleyes/plotting/powerspectrumseries.py | sanjayankur31/fsleyes | train | 1 |
01e1b78e35d225292003f3a8260951a1151ddcc6 | [
"super().__init__()\nstart = time.time()\nlogger.info('Reading 7segment dataset ...')\ninputs, labels = SevenSegmentData._read_data(config.seven_segment_data)\ntrain_inputs, train_labels, test_inputs, test_labels = Dataset._split_data(inputs, labels, config.seven_segment_split)\nassert len(train_labels) == len(trai... | <|body_start_0|>
super().__init__()
start = time.time()
logger.info('Reading 7segment dataset ...')
inputs, labels = SevenSegmentData._read_data(config.seven_segment_data)
train_inputs, train_labels, test_inputs, test_labels = Dataset._split_data(inputs, labels, config.seven_segm... | An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass) | SevenSegmentData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SevenSegmentData:
"""An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass)"""
def __init__(self):
"""Read the 7segment dataset from file. Args: Returns:"""
<|body_0|>
def _read_data(filename):
"""Reading the dataset ... | stack_v2_sparse_classes_36k_train_017816 | 7,004 | permissive | [
{
"docstring": "Read the 7segment dataset from file. Args: Returns:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Reading the dataset from file into a list of binary vectors and a list of corresponding labels. Args: filename: Path and name of the file that contains t... | 4 | stack_v2_sparse_classes_30k_train_013255 | Implement the Python class `SevenSegmentData` described below.
Class description:
An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass)
Method signatures and docstrings:
- def __init__(self): Read the 7segment dataset from file. Args: Returns:
- def _read_data(filename):... | Implement the Python class `SevenSegmentData` described below.
Class description:
An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass)
Method signatures and docstrings:
- def __init__(self): Read the 7segment dataset from file. Args: Returns:
- def _read_data(filename):... | 3ee4037a4568c393378eaec74483696d5281f376 | <|skeleton|>
class SevenSegmentData:
"""An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass)"""
def __init__(self):
"""Read the 7segment dataset from file. Args: Returns:"""
<|body_0|>
def _read_data(filename):
"""Reading the dataset ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SevenSegmentData:
"""An instance of the class shall represent the 7segment dataset. Attributes: (additional to baseclass)"""
def __init__(self):
"""Read the 7segment dataset from file. Args: Returns:"""
super().__init__()
start = time.time()
logger.info('Reading 7segment d... | the_stack_v2_python_sparse | src/data/seven_segment_data.py | xiuxiuzhang1995/snn_global_pattern_induction | train | 0 |
b8b5162c54707bf94e61ba9396e4091258b18695 | [
"if positive_fraction < 0 or positive_fraction > 1:\n raise ValueError('positive_fraction should be in range [0,1]. Received: %s.' % positive_fraction)\nself._positive_fraction = positive_fraction",
"if len(indicator.get_shape().as_list()) != 1:\n raise ValueError('indicator must be 1 dimensional, got a ten... | <|body_start_0|>
if positive_fraction < 0 or positive_fraction > 1:
raise ValueError('positive_fraction should be in range [0,1]. Received: %s.' % positive_fraction)
self._positive_fraction = positive_fraction
<|end_body_0|>
<|body_start_1|>
if len(indicator.get_shape().as_list()) !... | Subsamples minibatches to a desired balance of positives and negatives. | BalancedPositiveNegativeSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BalancedPositiveNegativeSampler:
"""Subsamples minibatches to a desired balance of positives and negatives."""
def __init__(self, positive_fraction=0.5):
"""Constructs a minibatch sampler. Args: positive_fraction: desired fraction of positive examples (scalar in [0,1]) in the batch. ... | stack_v2_sparse_classes_36k_train_017817 | 4,434 | permissive | [
{
"docstring": "Constructs a minibatch sampler. Args: positive_fraction: desired fraction of positive examples (scalar in [0,1]) in the batch. Raises: ValueError: if positive_fraction < 0, or positive_fraction > 1",
"name": "__init__",
"signature": "def __init__(self, positive_fraction=0.5)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_004463 | Implement the Python class `BalancedPositiveNegativeSampler` described below.
Class description:
Subsamples minibatches to a desired balance of positives and negatives.
Method signatures and docstrings:
- def __init__(self, positive_fraction=0.5): Constructs a minibatch sampler. Args: positive_fraction: desired fract... | Implement the Python class `BalancedPositiveNegativeSampler` described below.
Class description:
Subsamples minibatches to a desired balance of positives and negatives.
Method signatures and docstrings:
- def __init__(self, positive_fraction=0.5): Constructs a minibatch sampler. Args: positive_fraction: desired fract... | 39272caea30ab01faa3795156af76a08aaf1455f | <|skeleton|>
class BalancedPositiveNegativeSampler:
"""Subsamples minibatches to a desired balance of positives and negatives."""
def __init__(self, positive_fraction=0.5):
"""Constructs a minibatch sampler. Args: positive_fraction: desired fraction of positive examples (scalar in [0,1]) in the batch. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BalancedPositiveNegativeSampler:
"""Subsamples minibatches to a desired balance of positives and negatives."""
def __init__(self, positive_fraction=0.5):
"""Constructs a minibatch sampler. Args: positive_fraction: desired fraction of positive examples (scalar in [0,1]) in the batch. Raises: Value... | the_stack_v2_python_sparse | core/balanced_positive_negative_sampler.py | ambakick/Person-Detection-and-Tracking | train | 262 |
91af205d2efc48706814ad7b117cac9296d4b24b | [
"self.d, self.cache, self.len, index = ({}, {}, len(words), 0)\nfor w in words:\n if w in self.d:\n self.d[w].append(index)\n else:\n self.d[w] = [index]\n index += 1",
"if (word1, word2) in self.cache:\n return self.cache[word1, word2]\nif (word2, word1) in self.cache:\n return self.... | <|body_start_0|>
self.d, self.cache, self.len, index = ({}, {}, len(words), 0)
for w in words:
if w in self.d:
self.d[w].append(index)
else:
self.d[w] = [index]
index += 1
<|end_body_0|>
<|body_start_1|>
if (word1, word2) in se... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_017818 | 1,334 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 3873502679a5def6af4be03028542f07d059d1a9 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.d, self.cache, self.len, index = ({}, {}, len(words), 0)
for w in words:
if w in self.d:
self.d[w].append(index)
else:
... | the_stack_v2_python_sparse | Python-Algorithms-DataStructure/src/leet/244_ShortestWordDistanceII.py | coremedy/Python-Algorithms-DataStructure | train | 0 | |
014369d96796501711af32a6e8bfc9cb542c3ad8 | [
"g = nx.Graph()\ng.add_path(['A', 'B', 'Z', 'C', 'A'])\nset_unit_weights(g)\npaths = edge_disjoint_shortest_pair(g, 'A', 'Z')\nexp_paths = [['A', 'B', 'Z'], ['A', 'C', 'Z']]\ncompare_path_lists(self, paths, exp_paths)",
"g = graph_fig_3_13_a\npaths = edge_disjoint_shortest_pair(g, 'A', 'Z')\nexp_paths = [[i for i... | <|body_start_0|>
g = nx.Graph()
g.add_path(['A', 'B', 'Z', 'C', 'A'])
set_unit_weights(g)
paths = edge_disjoint_shortest_pair(g, 'A', 'Z')
exp_paths = [['A', 'B', 'Z'], ['A', 'C', 'Z']]
compare_path_lists(self, paths, exp_paths)
<|end_body_0|>
<|body_start_1|>
g ... | TestEdgeDisjointShortestPair | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEdgeDisjointShortestPair:
def test_diamond(self):
"""Simple diamond graph w/two equal paths."""
<|body_0|>
def test_example_3_13_a(self):
"""Example 3.13a on pg 65."""
<|body_1|>
def test_example_3_14(self):
"""Example 3.14 on pg 76."""
... | stack_v2_sparse_classes_36k_train_017819 | 9,557 | no_license | [
{
"docstring": "Simple diamond graph w/two equal paths.",
"name": "test_diamond",
"signature": "def test_diamond(self)"
},
{
"docstring": "Example 3.13a on pg 65.",
"name": "test_example_3_13_a",
"signature": "def test_example_3_13_a(self)"
},
{
"docstring": "Example 3.14 on pg 7... | 4 | stack_v2_sparse_classes_30k_train_009591 | Implement the Python class `TestEdgeDisjointShortestPair` described below.
Class description:
Implement the TestEdgeDisjointShortestPair class.
Method signatures and docstrings:
- def test_diamond(self): Simple diamond graph w/two equal paths.
- def test_example_3_13_a(self): Example 3.13a on pg 65.
- def test_exampl... | Implement the Python class `TestEdgeDisjointShortestPair` described below.
Class description:
Implement the TestEdgeDisjointShortestPair class.
Method signatures and docstrings:
- def test_diamond(self): Simple diamond graph w/two equal paths.
- def test_example_3_13_a(self): Example 3.13a on pg 65.
- def test_exampl... | c2f44c01df4a1ac220218f0a89b433a1ca76058a | <|skeleton|>
class TestEdgeDisjointShortestPair:
def test_diamond(self):
"""Simple diamond graph w/two equal paths."""
<|body_0|>
def test_example_3_13_a(self):
"""Example 3.13a on pg 65."""
<|body_1|>
def test_example_3_14(self):
"""Example 3.14 on pg 76."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestEdgeDisjointShortestPair:
def test_diamond(self):
"""Simple diamond graph w/two equal paths."""
g = nx.Graph()
g.add_path(['A', 'B', 'Z', 'C', 'A'])
set_unit_weights(g)
paths = edge_disjoint_shortest_pair(g, 'A', 'Z')
exp_paths = [['A', 'B', 'Z'], ['A', 'C',... | the_stack_v2_python_sparse | src/test_paths.py | weichenzhao/cpp | train | 0 | |
54441ebaa1b7b7caf498f6fd48f9b6e911cc9963 | [
"self.cmd_fds = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\nself.stdout = buffered_non_blocking_reader(self.cmd_fds.stdout)\npickle.dump(parameter, self.cmd_fds.stdin)",
"data = self.stdout.readline(timeout).rstrip()\nif data != 'ok':\n return False\nreturn... | <|body_start_0|>
self.cmd_fds = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
self.stdout = buffered_non_blocking_reader(self.cmd_fds.stdout)
pickle.dump(parameter, self.cmd_fds.stdin)
<|end_body_0|>
<|body_start_1|>
data = self.stdout.... | ParentProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParentProcess:
def __init__(self, command, parameter):
"""command is formated for Popen; ["cmd", "param"] parameter is one variable, but can be complex (array, dictionary, etc)"""
<|body_0|>
def is_ok(self, timeout=0.1):
"""returns true if ok; 1 to 1 correspondence w... | stack_v2_sparse_classes_36k_train_017820 | 4,627 | no_license | [
{
"docstring": "command is formated for Popen; [\"cmd\", \"param\"] parameter is one variable, but can be complex (array, dictionary, etc)",
"name": "__init__",
"signature": "def __init__(self, command, parameter)"
},
{
"docstring": "returns true if ok; 1 to 1 correspondence with ChildProcess.se... | 3 | null | Implement the Python class `ParentProcess` described below.
Class description:
Implement the ParentProcess class.
Method signatures and docstrings:
- def __init__(self, command, parameter): command is formated for Popen; ["cmd", "param"] parameter is one variable, but can be complex (array, dictionary, etc)
- def is_... | Implement the Python class `ParentProcess` described below.
Class description:
Implement the ParentProcess class.
Method signatures and docstrings:
- def __init__(self, command, parameter): command is formated for Popen; ["cmd", "param"] parameter is one variable, but can be complex (array, dictionary, etc)
- def is_... | 4822b4e9c9d165e4be151948d3c8a800fe1b814e | <|skeleton|>
class ParentProcess:
def __init__(self, command, parameter):
"""command is formated for Popen; ["cmd", "param"] parameter is one variable, but can be complex (array, dictionary, etc)"""
<|body_0|>
def is_ok(self, timeout=0.1):
"""returns true if ok; 1 to 1 correspondence w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParentProcess:
def __init__(self, command, parameter):
"""command is formated for Popen; ["cmd", "param"] parameter is one variable, but can be complex (array, dictionary, etc)"""
self.cmd_fds = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
... | the_stack_v2_python_sparse | socialscan/independentsubprocess/independentsubprocess.py | F3DS/f3ds | train | 1 | |
ef074558a61195c8c2324a9d92e9b6a8fb52a9cb | [
"result = {'total_progress': params['total_progress'], 'task_state': params['task_state'], 'destination_share_server_id': params['destination_share_server_id']}\nself.update_versioned_resource_dict(request, result, params)\nreturn result",
"requested_capabilities = {'writable': params['writable'], 'nondisruptive'... | <|body_start_0|>
result = {'total_progress': params['total_progress'], 'task_state': params['task_state'], 'destination_share_server_id': params['destination_share_server_id']}
self.update_versioned_resource_dict(request, result, params)
return result
<|end_body_0|>
<|body_start_1|>
req... | Model share server migration view data response as a python dictionary. | ViewBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewBuilder:
"""Model share server migration view data response as a python dictionary."""
def get_progress(self, request, params):
"""View of share server migration job progress."""
<|body_0|>
def build_check_migration(self, request, params, result):
"""View of ... | stack_v2_sparse_classes_36k_train_017821 | 2,884 | permissive | [
{
"docstring": "View of share server migration job progress.",
"name": "get_progress",
"signature": "def get_progress(self, request, params)"
},
{
"docstring": "View of share server migration check.",
"name": "build_check_migration",
"signature": "def build_check_migration(self, request,... | 3 | null | Implement the Python class `ViewBuilder` described below.
Class description:
Model share server migration view data response as a python dictionary.
Method signatures and docstrings:
- def get_progress(self, request, params): View of share server migration job progress.
- def build_check_migration(self, request, para... | Implement the Python class `ViewBuilder` described below.
Class description:
Model share server migration view data response as a python dictionary.
Method signatures and docstrings:
- def get_progress(self, request, params): View of share server migration job progress.
- def build_check_migration(self, request, para... | a93a844398a11a8a85f204782fb9456f7caccdbe | <|skeleton|>
class ViewBuilder:
"""Model share server migration view data response as a python dictionary."""
def get_progress(self, request, params):
"""View of share server migration job progress."""
<|body_0|>
def build_check_migration(self, request, params, result):
"""View of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewBuilder:
"""Model share server migration view data response as a python dictionary."""
def get_progress(self, request, params):
"""View of share server migration job progress."""
result = {'total_progress': params['total_progress'], 'task_state': params['task_state'], 'destination_sha... | the_stack_v2_python_sparse | manila/api/views/share_server_migration.py | openstack/manila | train | 178 |
f96136f3452fb139fa3d6071624bce3d2108591b | [
"super(JointMRSModelling, self).__init__(nlay, mrs[0].K, mrs[0].z, mrs[0].t, verbose)\nself.mrs = mrs\nfor mrsi in mrs:\n mrsi.createFOP(nlay)",
"response = pg.RVector()\nfor mrs in self.mrs:\n response = pg.cat(response, mrs.f(model))"
] | <|body_start_0|>
super(JointMRSModelling, self).__init__(nlay, mrs[0].K, mrs[0].z, mrs[0].t, verbose)
self.mrs = mrs
for mrsi in mrs:
mrsi.createFOP(nlay)
<|end_body_0|>
<|body_start_1|>
response = pg.RVector()
for mrs in self.mrs:
response = pg.cat(respo... | MRS Laterally constrained modelling based on BlockMatrices. | JointMRSModelling | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointMRSModelling:
"""MRS Laterally constrained modelling based on BlockMatrices."""
def __init__(self, mrs, nlay=2, verbose=False):
"""Parameters: FDEM data class and number of layers"""
<|body_0|>
def response(self, model):
"""response function (all responses t... | stack_v2_sparse_classes_36k_train_017822 | 17,204 | permissive | [
{
"docstring": "Parameters: FDEM data class and number of layers",
"name": "__init__",
"signature": "def __init__(self, mrs, nlay=2, verbose=False)"
},
{
"docstring": "response function (all responses together)",
"name": "response",
"signature": "def response(self, model)"
}
] | 2 | null | Implement the Python class `JointMRSModelling` described below.
Class description:
MRS Laterally constrained modelling based on BlockMatrices.
Method signatures and docstrings:
- def __init__(self, mrs, nlay=2, verbose=False): Parameters: FDEM data class and number of layers
- def response(self, model): response func... | Implement the Python class `JointMRSModelling` described below.
Class description:
MRS Laterally constrained modelling based on BlockMatrices.
Method signatures and docstrings:
- def __init__(self, mrs, nlay=2, verbose=False): Parameters: FDEM data class and number of layers
- def response(self, model): response func... | 9962fe882fad284e52858ba3aa5e87b2395d791d | <|skeleton|>
class JointMRSModelling:
"""MRS Laterally constrained modelling based on BlockMatrices."""
def __init__(self, mrs, nlay=2, verbose=False):
"""Parameters: FDEM data class and number of layers"""
<|body_0|>
def response(self, model):
"""response function (all responses t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JointMRSModelling:
"""MRS Laterally constrained modelling based on BlockMatrices."""
def __init__(self, mrs, nlay=2, verbose=False):
"""Parameters: FDEM data class and number of layers"""
super(JointMRSModelling, self).__init__(nlay, mrs[0].K, mrs[0].z, mrs[0].t, verbose)
self.mrs... | the_stack_v2_python_sparse | python/pygimli/physics/sNMR/mrsprofile.py | Geophysics-OpenSource/gimli | train | 0 |
558c1c264612c535f25993edf63cc3542566fd48 | [
"self.routing_number = routing_number\nself.real_account_number = real_account_number\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nrouting_number = dictionary.get('routingNumber')\nreal_account_number = dictionary.get('realAccountNumber')\nfor key in cls._names.v... | <|body_start_0|>
self.routing_number = routing_number
self.real_account_number = real_account_number
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
routing_number = dictionary.get('routingNumber')... | Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_account_number (string): The account number for initiating ACH transfers for this ... | ACHDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACHDetails:
"""Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_account_number (string): The account number ... | stack_v2_sparse_classes_36k_train_017823 | 2,184 | permissive | [
{
"docstring": "Constructor for the ACHDetails class",
"name": "__init__",
"signature": "def __init__(self, routing_number=None, real_account_number=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary... | 2 | stack_v2_sparse_classes_30k_train_006914 | Implement the Python class `ACHDetails` described below.
Class description:
Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_accou... | Implement the Python class `ACHDetails` described below.
Class description:
Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_accou... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class ACHDetails:
"""Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_account_number (string): The account number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ACHDetails:
"""Implementation of the 'ACH Details' model. The routing and account number information to initiate ACH transfers Attributes: routing_number (string): The routing number of the financial institution for this specific customers account real_account_number (string): The account number for initiatin... | the_stack_v2_python_sparse | finicityapi/models/ach_details.py | monarchmoney/finicity-python | train | 0 |
628b6d41a6c01b18d29a71ac0e0d7e6b780e8323 | [
"super(BiLSTM, self).__init__()\nself.h_dim = h_dim\nself.o_dim = o_dim\nself.d_dim = d_dim\nself.r_dim = r_dim\nself.d_prob = d_prob\nself.num_layers = num_layers\nself.with_self_att = with_self_att\nself.embeddings = embeddings\nself.task = task\nself.replace_embeddings(concept_vocab_field, ref_vocab_field)\nself... | <|body_start_0|>
super(BiLSTM, self).__init__()
self.h_dim = h_dim
self.o_dim = o_dim
self.d_dim = d_dim
self.r_dim = r_dim
self.d_prob = d_prob
self.num_layers = num_layers
self.with_self_att = with_self_att
self.embeddings = embeddings
se... | Bidirectional LSTM with optional self attention. | BiLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTM:
"""Bidirectional LSTM with optional self attention."""
def __init__(self, h_dim, o_dim, d_prob, with_self_att, d_dim, r_dim, num_layers, embeddings, concept_vocab_field=None, ref_vocab_field=None, task=''):
"""@param h_dim (int): hidden dimension of LSTM @param o_dim (int): d... | stack_v2_sparse_classes_36k_train_017824 | 7,167 | no_license | [
{
"docstring": "@param h_dim (int): hidden dimension of LSTM @param o_dim (int): dimension of the outputted language representation @param d_prob (float): probability that an output value should be dropped out @param with_self_att (bool): whether to utilize self attention or not @param d_dim (int): d_dim for se... | 3 | stack_v2_sparse_classes_30k_test_000200 | Implement the Python class `BiLSTM` described below.
Class description:
Bidirectional LSTM with optional self attention.
Method signatures and docstrings:
- def __init__(self, h_dim, o_dim, d_prob, with_self_att, d_dim, r_dim, num_layers, embeddings, concept_vocab_field=None, ref_vocab_field=None, task=''): @param h_... | Implement the Python class `BiLSTM` described below.
Class description:
Bidirectional LSTM with optional self attention.
Method signatures and docstrings:
- def __init__(self, h_dim, o_dim, d_prob, with_self_att, d_dim, r_dim, num_layers, embeddings, concept_vocab_field=None, ref_vocab_field=None, task=''): @param h_... | 2dca3ba909078739b49468ea8b772f346710d60b | <|skeleton|>
class BiLSTM:
"""Bidirectional LSTM with optional self attention."""
def __init__(self, h_dim, o_dim, d_prob, with_self_att, d_dim, r_dim, num_layers, embeddings, concept_vocab_field=None, ref_vocab_field=None, task=''):
"""@param h_dim (int): hidden dimension of LSTM @param o_dim (int): d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLSTM:
"""Bidirectional LSTM with optional self attention."""
def __init__(self, h_dim, o_dim, d_prob, with_self_att, d_dim, r_dim, num_layers, embeddings, concept_vocab_field=None, ref_vocab_field=None, task=''):
"""@param h_dim (int): hidden dimension of LSTM @param o_dim (int): dimension of t... | the_stack_v2_python_sparse | models/student/lfl/language/bi_lstm.py | cocolab-projects/concept-captioning | train | 0 |
41e7948a5d4acfeffa0075528b818ee458353a07 | [
"self._nums = nums\nself.tree = [0 for _ in range(len(nums) + 1)]\nfor i in range(len(nums)):\n val = nums[i]\n i += 1\n while i < len(self.tree):\n self.tree[i] += val\n i += i & -i\nprint(self.tree)",
"val1 = self._nums[i]\nindex = i\ni = i + 1\nwhile i < len(self.tree):\n self.tree[i]... | <|body_start_0|>
self._nums = nums
self.tree = [0 for _ in range(len(nums) + 1)]
for i in range(len(nums)):
val = nums[i]
i += 1
while i < len(self.tree):
self.tree[i] += val
i += i & -i
print(self.tree)
<|end_body_0|>
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_017825 | 1,364 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_001945 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | a6d0e392134afe19d1aed2dfe7914b674e05ecc6 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self._nums = nums
self.tree = [0 for _ in range(len(nums) + 1)]
for i in range(len(nums)):
val = nums[i]
i += 1
while i < len(self.tree):
self.tree[i] += val
... | the_stack_v2_python_sparse | 307RangeSumQuery.py | Ting007/leetcodePractice | train | 0 | |
66f6568b7fb0f33aec67a0146b9243e9a4e58247 | [
"self.reponame = os.environ['reponame']\nself.model = os.environ['model']\nself.qa_model_name = os.environ['qa_yaml_name']\nself.rd_model_name = os.environ['rd_yaml_path']\nself.log_dir = 'logs'\nself.log_name = 'train_prim_single.log'\nself.log_path = os.path.join(os.getcwd(), self.log_dir, self.reponame, self.qa_... | <|body_start_0|>
self.reponame = os.environ['reponame']
self.model = os.environ['model']
self.qa_model_name = os.environ['qa_yaml_name']
self.rd_model_name = os.environ['rd_yaml_path']
self.log_dir = 'logs'
self.log_name = 'train_prim_single.log'
self.log_path = o... | case执行结束后 | PaddleSeg_End | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleSeg_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
<|body_0|>
def get_loss(self, log_path):
"""获取loss值"""
<|body_1|>
def draw_curve(self):
"""绘制曲线"""
<|body_2|>
def build_end(self):
"""执行准备过程"""
<|body_3... | stack_v2_sparse_classes_36k_train_017826 | 3,788 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "获取loss值",
"name": "get_loss",
"signature": "def get_loss(self, log_path)"
},
{
"docstring": "绘制曲线",
"name": "draw_curve",
"signature": "def draw_curve(self)"
},
{
"docst... | 4 | null | Implement the Python class `PaddleSeg_End` described below.
Class description:
case执行结束后
Method signatures and docstrings:
- def __init__(self): 初始化
- def get_loss(self, log_path): 获取loss值
- def draw_curve(self): 绘制曲线
- def build_end(self): 执行准备过程 | Implement the Python class `PaddleSeg_End` described below.
Class description:
case执行结束后
Method signatures and docstrings:
- def __init__(self): 初始化
- def get_loss(self, log_path): 获取loss值
- def draw_curve(self): 绘制曲线
- def build_end(self): 执行准备过程
<|skeleton|>
class PaddleSeg_End:
"""case执行结束后"""
def __init... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class PaddleSeg_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
<|body_0|>
def get_loss(self, log_path):
"""获取loss值"""
<|body_1|>
def draw_curve(self):
"""绘制曲线"""
<|body_2|>
def build_end(self):
"""执行准备过程"""
<|body_3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaddleSeg_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
self.reponame = os.environ['reponame']
self.model = os.environ['model']
self.qa_model_name = os.environ['qa_yaml_name']
self.rd_model_name = os.environ['rd_yaml_path']
self.log_dir = 'logs'
... | the_stack_v2_python_sparse | models_restruct/PaddleSeg/tools/end.py | PaddlePaddle/PaddleTest | train | 42 |
00b8125069afa3993f2d751ffb70e0f748ae1cdd | [
"super(MonitoringChannel, self).__init__(txrx, channel_ini)\nself._reg_monitor_settings = UARTRegister(self._addr_settings_monitoring)\nself._reg_monitor_settings.initialize_map(settings)\nself._log.debug('Monitor Settings Map: %s', self._reg_monitor_settings.fields)",
"self._log.debug('get_value (\"%s\")', self.... | <|body_start_0|>
super(MonitoringChannel, self).__init__(txrx, channel_ini)
self._reg_monitor_settings = UARTRegister(self._addr_settings_monitoring)
self._reg_monitor_settings.initialize_map(settings)
self._log.debug('Monitor Settings Map: %s', self._reg_monitor_settings.fields)
<|end_b... | Represent a specific monitoring channel on any of the control boards. | MonitoringChannel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitoringChannel:
"""Represent a specific monitoring channel on any of the control boards."""
def __init__(self, txrx, channel_ini, settings):
"""MonitoringChannel constructor. Create a monitoring channel Keeps a reference to the txrx communication object and initialises itself base... | stack_v2_sparse_classes_36k_train_017827 | 13,646 | no_license | [
{
"docstring": "MonitoringChannel constructor. Create a monitoring channel Keeps a reference to the txrx communication object and initialises itself based on the parameters in channel_ini. Provides the get_value method in addition to the general channel methods :param txrx: Percival communication context :type ... | 2 | stack_v2_sparse_classes_30k_train_020354 | Implement the Python class `MonitoringChannel` described below.
Class description:
Represent a specific monitoring channel on any of the control boards.
Method signatures and docstrings:
- def __init__(self, txrx, channel_ini, settings): MonitoringChannel constructor. Create a monitoring channel Keeps a reference to ... | Implement the Python class `MonitoringChannel` described below.
Class description:
Represent a specific monitoring channel on any of the control boards.
Method signatures and docstrings:
- def __init__(self, txrx, channel_ini, settings): MonitoringChannel constructor. Create a monitoring channel Keeps a reference to ... | 134aa85a6ec4b9ea0360784b7bfab6945ae6811a | <|skeleton|>
class MonitoringChannel:
"""Represent a specific monitoring channel on any of the control boards."""
def __init__(self, txrx, channel_ini, settings):
"""MonitoringChannel constructor. Create a monitoring channel Keeps a reference to the txrx communication object and initialises itself base... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonitoringChannel:
"""Represent a specific monitoring channel on any of the control boards."""
def __init__(self, txrx, channel_ini, settings):
"""MonitoringChannel constructor. Create a monitoring channel Keeps a reference to the txrx communication object and initialises itself based on the para... | the_stack_v2_python_sparse | percival_detector/carrier/channels.py | percival-detector/percivalui | train | 0 |
b9f5d9813e43dd7de3606aeac778cdfa6395723c | [
"event_id = request.GET.get('event_id')\ntry:\n event = Event.objects.get(id=event_id)\nexcept:\n logger.log_error(f'Invalid event id {event_id} entered for getting presigned url')\n return api_error_response(message='Event is not valid', status=400)\nimage_name = event.images\nbucket = BUCKET\nobject_name... | <|body_start_0|>
event_id = request.GET.get('event_id')
try:
event = Event.objects.get(id=event_id)
except:
logger.log_error(f'Invalid event id {event_id} entered for getting presigned url')
return api_error_response(message='Event is not valid', status=400)
... | Api for presigned url created here | PresignedUrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
event_id = request.GET.... | stack_v2_sparse_classes_36k_train_017828 | 2,040 | no_license | [
{
"docstring": ":param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": ":param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006145 | Implement the Python class `PresignedUrl` described below.
Class description:
Api for presigned url created here
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return: | Implement the Python class `PresignedUrl` described below.
Class description:
Api for presigned url created here
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return:
<|skeleton|>
class PresignedUrl:
"""Api for presigned url creat... | b76de21b3318ab24e1add18a9aa4f437ed02e10e | <|skeleton|>
class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
event_id = request.GET.get('event_id')
try:
event = Event.objects.get(id=event_id)
except:
logger.log_error(f'Invalid event id {event_id} e... | the_stack_v2_python_sparse | core/presigned_url.py | ameyk20/eon-backend | train | 0 |
00e8a9a223e1f509baa13aba713aa7357cadc767 | [
"if len(train_val_test_ratio) != 3:\n raise ValueError('len(train_val_test_ratio) != 3')\nself.ratios = np.array(list(train_val_test_ratio), dtype=np.float32)\nself.ratios /= sum(self.ratios)",
"poj104 = super(TrainValTestSplitter, self).Split(db)\nwith db.Session() as session:\n total_count = session.query... | <|body_start_0|>
if len(train_val_test_ratio) != 3:
raise ValueError('len(train_val_test_ratio) != 3')
self.ratios = np.array(list(train_val_test_ratio), dtype=np.float32)
self.ratios /= sum(self.ratios)
<|end_body_0|>
<|body_start_1|>
poj104 = super(TrainValTestSplitter, se... | A generator train/val/test splits. | TrainValTestSplitter | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1),... | stack_v2_sparse_classes_36k_train_017829 | 8,051 | permissive | [
{
"docstring": "Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1), the training set will be 3/5 of the dataset, and the validation and test sets will each by 1/5 of the dataset.",
"name": "__init__",
"signature": "de... | 2 | null | Implement the Python class `TrainValTestSplitter` described below.
Class description:
A generator train/val/test splits.
Method signatures and docstrings:
- def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)): Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, va... | Implement the Python class `TrainValTestSplitter` described below.
Class description:
A generator train/val/test splits.
Method signatures and docstrings:
- def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)): Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, va... | cd99d2c5362acd0b24ee224492bb3e8c4d4736fb | <|skeleton|>
class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1),... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1), the training... | the_stack_v2_python_sparse | deeplearning/ml4pl/ir/split.py | Zacharias030/ProGraML | train | 0 |
70575e90209056f60b646a741c6b80a84238500e | [
"super().__init__()\nresnet_backbones = {'resnet18': resnet18, 'resnet34': resnet34, 'resnet50': resnet50}\nresnet_model = resnet_backbones[args['backbone']](pretrained=False)\nconv1_new = nn.Conv2d(args['input_channels'], 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\nmodules = list(resnet_mod... | <|body_start_0|>
super().__init__()
resnet_backbones = {'resnet18': resnet18, 'resnet34': resnet34, 'resnet50': resnet50}
resnet_model = resnet_backbones[args['backbone']](pretrained=False)
conv1_new = nn.Conv2d(args['input_channels'], 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3... | RasterEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterEncoder:
def __init__(self, args: Dict):
"""CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use (resnet18, resnet34 or resnet50) 'input_channels': int Size of scene features at each grid cell 'use_... | stack_v2_sparse_classes_36k_train_017830 | 4,175 | permissive | [
{
"docstring": "CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use (resnet18, resnet34 or resnet50) 'input_channels': int Size of scene features at each grid cell 'use_positional_encoding: bool Whether or not to add positional... | 2 | stack_v2_sparse_classes_30k_train_017136 | Implement the Python class `RasterEncoder` described below.
Class description:
Implement the RasterEncoder class.
Method signatures and docstrings:
- def __init__(self, args: Dict): CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use... | Implement the Python class `RasterEncoder` described below.
Class description:
Implement the RasterEncoder class.
Method signatures and docstrings:
- def __init__(self, args: Dict): CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use... | 6419894aa040adb9570b14493952a98c0a52f803 | <|skeleton|>
class RasterEncoder:
def __init__(self, args: Dict):
"""CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use (resnet18, resnet34 or resnet50) 'input_channels': int Size of scene features at each grid cell 'use_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasterEncoder:
def __init__(self, args: Dict):
"""CNN encoder for raster representation of HD maps and surrounding agent trajectories. args to include 'backbone': str CNN backbone to use (resnet18, resnet34 or resnet50) 'input_channels': int Size of scene features at each grid cell 'use_positional_enc... | the_stack_v2_python_sparse | models/encoders/raster_encoder.py | sancarlim/Explainable-MP | train | 17 | |
20fefe8cf543fee8525213e4cfc0a527aa7beb3c | [
"decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)\npaginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))\ntry:\n\n def outputFunction(itemObj):\n return itemObj.ge... | <|body_start_0|>
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))
try:
def outputFunct... | APIKeysInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
<|body_0|>
def post(self, tenant):
"""Create APIKey"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWT... | stack_v2_sparse_classes_36k_train_017831 | 9,554 | permissive | [
{
"docstring": "Get list of ticket types",
"name": "get",
"signature": "def get(self, tenant)"
},
{
"docstring": "Create APIKey",
"name": "post",
"signature": "def post(self, tenant)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000173 | Implement the Python class `APIKeysInfo` described below.
Class description:
Implement the APIKeysInfo class.
Method signatures and docstrings:
- def get(self, tenant): Get list of ticket types
- def post(self, tenant): Create APIKey | Implement the Python class `APIKeysInfo` described below.
Class description:
Implement the APIKeysInfo class.
Method signatures and docstrings:
- def get(self, tenant): Get list of ticket types
- def post(self, tenant): Create APIKey
<|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ... | d3908c46614fb1b638553282cd72ba3634277495 | <|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
<|body_0|>
def post(self, tenant):
"""Create APIKey"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPagi... | the_stack_v2_python_sparse | services/src/APIlogin_APIKeys.py | rmetcalf9/saas_user_management_system | train | 1 | |
479d0214f21743e2a54c6911973ff741c527be30 | [
"super().__init__()\nself.__bit_size = 8\nself.__block_size = 2\nself._cipher_name = 'RSA'",
"_p = generate_random_prime(self.__bit_size)\nwhile True:\n _q = generate_random_prime(self.__bit_size)\n if _p != _q:\n break\n_n = _p * _q\nphi = (_p - 1) * (_q - 1)\nwhile True:\n _e = randint(3, phi - ... | <|body_start_0|>
super().__init__()
self.__bit_size = 8
self.__block_size = 2
self._cipher_name = 'RSA'
<|end_body_0|>
<|body_start_1|>
_p = generate_random_prime(self.__bit_size)
while True:
_q = generate_random_prime(self.__bit_size)
if _p != _q... | RSA class | RSA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSA:
"""RSA class"""
def __init__(self):
"""Initialize RSA"""
<|body_0|>
def generate_keys(self):
"""Generate RSA keys. :return: (n, e), (n, d)"""
<|body_1|>
def encode(self, key: int, plain_message: str):
"""Encode the message with RSA encry... | stack_v2_sparse_classes_36k_train_017832 | 2,195 | no_license | [
{
"docstring": "Initialize RSA",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generate RSA keys. :return: (n, e), (n, d)",
"name": "generate_keys",
"signature": "def generate_keys(self)"
},
{
"docstring": "Encode the message with RSA encryption. :param... | 4 | stack_v2_sparse_classes_30k_train_013366 | Implement the Python class `RSA` described below.
Class description:
RSA class
Method signatures and docstrings:
- def __init__(self): Initialize RSA
- def generate_keys(self): Generate RSA keys. :return: (n, e), (n, d)
- def encode(self, key: int, plain_message: str): Encode the message with RSA encryption. :param k... | Implement the Python class `RSA` described below.
Class description:
RSA class
Method signatures and docstrings:
- def __init__(self): Initialize RSA
- def generate_keys(self): Generate RSA keys. :return: (n, e), (n, d)
- def encode(self, key: int, plain_message: str): Encode the message with RSA encryption. :param k... | 825bac514b0a6674850020cd06874b281233e5ce | <|skeleton|>
class RSA:
"""RSA class"""
def __init__(self):
"""Initialize RSA"""
<|body_0|>
def generate_keys(self):
"""Generate RSA keys. :return: (n, e), (n, d)"""
<|body_1|>
def encode(self, key: int, plain_message: str):
"""Encode the message with RSA encry... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSA:
"""RSA class"""
def __init__(self):
"""Initialize RSA"""
super().__init__()
self.__bit_size = 8
self.__block_size = 2
self._cipher_name = 'RSA'
def generate_keys(self):
"""Generate RSA keys. :return: (n, e), (n, d)"""
_p = generate_random_... | the_stack_v2_python_sparse | project_3 encryption/cipher/cipher_rsa.py | simenkristoff/tdt4113_datateknologi | train | 0 |
537927878216fa09d64725047b44e10f96292fbb | [
"if norm:\n arr = normalize(arr, norm=norm, axis=axis)\nelse:\n if np.issubdtype(arr.dtype, np.integer):\n arr = arr.astype(float)\n min_all = arr.min(axis=axis)\n max_all = arr.max(axis=axis)\n range_all = max_all - min_all\n if axis is not None:\n pos = range_all == 0\n rang... | <|body_start_0|>
if norm:
arr = normalize(arr, norm=norm, axis=axis)
else:
if np.issubdtype(arr.dtype, np.integer):
arr = arr.astype(float)
min_all = arr.min(axis=axis)
max_all = arr.max(axis=axis)
range_all = max_all - min_all
... | Base class of clustering methods | ClusteringMethods | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusteringMethods:
"""Base class of clustering methods"""
def _normalize_values(arr, norm=None, axis=None):
"""Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape (n samples, with m features) norm : str Normalization met... | stack_v2_sparse_classes_36k_train_017833 | 1,933 | permissive | [
{
"docstring": "Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape (n samples, with m features) norm : str Normalization method to use (see sklearn.preprocessing.normalize) if None range normalize axis : int Axis to normalize along Returns -------... | 2 | null | Implement the Python class `ClusteringMethods` described below.
Class description:
Base class of clustering methods
Method signatures and docstrings:
- def _normalize_values(arr, norm=None, axis=None): Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape ... | Implement the Python class `ClusteringMethods` described below.
Class description:
Base class of clustering methods
Method signatures and docstrings:
- def _normalize_values(arr, norm=None, axis=None): Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape ... | 2dd05402c9c05ca0bf7f0e5bc2849ede0d0bc3cb | <|skeleton|>
class ClusteringMethods:
"""Base class of clustering methods"""
def _normalize_values(arr, norm=None, axis=None):
"""Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape (n samples, with m features) norm : str Normalization met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusteringMethods:
"""Base class of clustering methods"""
def _normalize_values(arr, norm=None, axis=None):
"""Normalize values in array by column Parameters ---------- arr : ndarray ndarray of values extracted from meta shape (n samples, with m features) norm : str Normalization method to use (s... | the_stack_v2_python_sparse | reVX/utilities/cluster_methods.py | NREL/reVX | train | 10 |
8822bbcf1facb80731cc9c3f5bf5605c995ba5e4 | [
"self._implementations = []\nmisc.log(3, 'Start loading document reference resolver entry points ...')\nfor ep in pkg_resources.iter_entry_points(group=self.ADAPTER_ENTRY_POINT_GROUP):\n impl_cls = ep.load()\n regexp = re.compile(impl_cls.match_expression)\n misc.log(3, \" Loaded '%s' with priority %d\" %... | <|body_start_0|>
self._implementations = []
misc.log(3, 'Start loading document reference resolver entry points ...')
for ep in pkg_resources.iter_entry_points(group=self.ADAPTER_ENTRY_POINT_GROUP):
impl_cls = ep.load()
regexp = re.compile(impl_cls.match_expression)
... | _RegistryClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are ex... | stack_v2_sparse_classes_36k_train_017834 | 3,532 | no_license | [
{
"docstring": "Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are expected to have a class attribute 'priority', th... | 2 | stack_v2_sparse_classes_30k_train_016701 | Implement the Python class `_RegistryClass` described below.
Class description:
Implement the _RegistryClass class.
Method signatures and docstrings:
- def __init__(self): Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regula... | Implement the Python class `_RegistryClass` described below.
Class description:
Implement the _RegistryClass class.
Method signatures and docstrings:
- def __init__(self): Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regula... | 6bc932c67bc8d93b873838ae6d9fb8d33c72234d | <|skeleton|>
class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RegistryClass:
def __init__(self):
"""Load all the defined entry points for resolver implementations, and store them in a list of pairs. The entry point names are interpreted as regular expressions, and matched against a documents 'erzeug_system' attribute. Implementation classes are expected to have... | the_stack_v2_python_sparse | site-packages/cs.documents-15.2.3.7-py2.7.egg/cs/documents/docref_resolver_registry.py | prachipainuly-rbei/devops-poc | train | 0 | |
4af76edc472e5a9d297e4282a38f5c5782d8d3d0 | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n return False\nreturn True",
"device_data = self.target\ncommand_name = 'Abort'\ndevice_data.event_track_time.set()\ncmd_ended_cb = CommandCallBack(self.logger).cmd_ended_cb\ntry:\n this_server = TangoServerHelper.get_in... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:
return False
return True
<|end_body_0|>
<|body_start_1|>
device_data = self.target
command_name = 'Abort'
device_data.event_track_time.set()
cmd_ended_cb = ... | A class for DishLeafNode's Abort command. | Abort | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
<|body_0|>
def do(sel... | stack_v2_sparse_classes_36k_train_017835 | 2,704 | permissive | [
{
"docstring": "Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean",
"name": "check_allowed",
"signature": "def check_allowed(self)"
},
{
"docstring": "Invokes TrackStop command on th... | 2 | stack_v2_sparse_classes_30k_train_005549 | Implement the Python class `Abort` described below.
Class description:
A class for DishLeafNode's Abort command.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device st... | Implement the Python class `Abort` described below.
Class description:
A class for DishLeafNode's Abort command.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device st... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
<|body_0|>
def do(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
if self.state_model.op_state in [DevSta... | the_stack_v2_python_sparse | temp_src/ska_tmc_dishleafnode_mid/abort_command.py | ska-telescope/tmc-prototype | train | 4 |
7bf94723357d75790a5614d990d0a1c7e3b1b865 | [
"kwargs['default'] = default\nkwargs['types'] = (Color, str, tuple, list)\nsuper().__init__(**kwargs)",
"if isinstance(value, Color):\n return value\nvalue = super().parse(value)\nif value is UNDEF or value is None:\n return value\nif callable(value):\n return value\nreturn Color.create(value)"
] | <|body_start_0|>
kwargs['default'] = default
kwargs['types'] = (Color, str, tuple, list)
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, Color):
return value
value = super().parse(value)
if value is UNDEF or value is None:
... | Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name. | ColorProperty | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorProperty:
"""Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name."""
def __init__(self, default=UNDEF,... | stack_v2_sparse_classes_36k_train_017836 | 4,576 | permissive | [
{
"docstring": "Initializes a new instance of ColorProperty.",
"name": "__init__",
"signature": "def __init__(self, default=UNDEF, **kwargs)"
},
{
"docstring": "Validates and converts given value.",
"name": "parse",
"signature": "def parse(self, value)"
}
] | 2 | null | Implement the Python class `ColorProperty` described below.
Class description:
Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name.
M... | Implement the Python class `ColorProperty` described below.
Class description:
Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name.
M... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class ColorProperty:
"""Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name."""
def __init__(self, default=UNDEF,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorProperty:
"""Defines a color property, which simplifies a color definition by automatically creating a pero.Color instance from various input options such as an RGB(A) channels (0-255 each), hex string (including leading '#' sign) or registered name."""
def __init__(self, default=UNDEF, **kwargs):
... | the_stack_v2_python_sparse | pero/properties/special.py | xxao/pero | train | 31 |
8e88e0729f8383cb1a5f0fd45a625656aa9442f2 | [
"self._trie = _TrieNode()\nfor word in lexicon:\n self._trie.insert(word)",
"current_row = range(len(word) + 1)\nresults = []\nfor letter in self._trie.children:\n self._searchRecursive(self._trie.children[letter], letter, word, current_row, results, max_cost)\nreturn results",
"columns = len(word) + 1\nc... | <|body_start_0|>
self._trie = _TrieNode()
for word in lexicon:
self._trie.insert(word)
<|end_body_0|>
<|body_start_1|>
current_row = range(len(word) + 1)
results = []
for letter in self._trie.children:
self._searchRecursive(self._trie.children[letter], le... | An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon | EditDistTrie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditDistTrie:
"""An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon"""
def __init__(self, lexicon):
"""Initalize using the lexicon"""
<|body_0|>
def search_matches(self, word, max_cost=2):
"""The search function returns a lis... | stack_v2_sparse_classes_36k_train_017837 | 3,359 | no_license | [
{
"docstring": "Initalize using the lexicon",
"name": "__init__",
"signature": "def __init__(self, lexicon)"
},
{
"docstring": "The search function returns a list of all words that are less than the given maximum distance from the target word",
"name": "search_matches",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_007157 | Implement the Python class `EditDistTrie` described below.
Class description:
An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon
Method signatures and docstrings:
- def __init__(self, lexicon): Initalize using the lexicon
- def search_matches(self, word, max_cost=2): The search f... | Implement the Python class `EditDistTrie` described below.
Class description:
An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon
Method signatures and docstrings:
- def __init__(self, lexicon): Initalize using the lexicon
- def search_matches(self, word, max_cost=2): The search f... | 94034c654e218ae3aa460857760e220f7f56eb1b | <|skeleton|>
class EditDistTrie:
"""An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon"""
def __init__(self, lexicon):
"""Initalize using the lexicon"""
<|body_0|>
def search_matches(self, word, max_cost=2):
"""The search function returns a lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditDistTrie:
"""An EditDistTrie a fast way to lookup all matches with edit_dist <= max_cost in a lexicon"""
def __init__(self, lexicon):
"""Initalize using the lexicon"""
self._trie = _TrieNode()
for word in lexicon:
self._trie.insert(word)
def search_matches(sel... | the_stack_v2_python_sparse | psynlp/spelling/editdisttrie.py | vmenger/psynlp | train | 3 |
1b5f333114edadec602a92655c82ab722e932254 | [
"if not twistedSingleton.__instance:\n twistedSingleton()\ntwistedSingleton.evenCalls = not twistedSingleton.evenCalls\nreturn twistedSingleton.__instance[int(not twistedSingleton.evenCalls)]",
"if twistedSingleton.__instance:\n raise Exception('This class is a singleton!')\nelse:\n if not value:\n ... | <|body_start_0|>
if not twistedSingleton.__instance:
twistedSingleton()
twistedSingleton.evenCalls = not twistedSingleton.evenCalls
return twistedSingleton.__instance[int(not twistedSingleton.evenCalls)]
<|end_body_0|>
<|body_start_1|>
if twistedSingleton.__instance:
... | A singleton pattern with a twist. | twistedSingleton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class twistedSingleton:
"""A singleton pattern with a twist."""
def getInstance():
"""Define a static access method."""
<|body_0|>
def __init__(self, value=None):
"""Define a virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017838 | 1,600 | no_license | [
{
"docstring": "Define a static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Define a virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self, value=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015411 | Implement the Python class `twistedSingleton` described below.
Class description:
A singleton pattern with a twist.
Method signatures and docstrings:
- def getInstance(): Define a static access method.
- def __init__(self, value=None): Define a virtually private constructor. | Implement the Python class `twistedSingleton` described below.
Class description:
A singleton pattern with a twist.
Method signatures and docstrings:
- def getInstance(): Define a static access method.
- def __init__(self, value=None): Define a virtually private constructor.
<|skeleton|>
class twistedSingleton:
... | 97eae3ee806756f4d646d600f434b1e68164ad34 | <|skeleton|>
class twistedSingleton:
"""A singleton pattern with a twist."""
def getInstance():
"""Define a static access method."""
<|body_0|>
def __init__(self, value=None):
"""Define a virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class twistedSingleton:
"""A singleton pattern with a twist."""
def getInstance():
"""Define a static access method."""
if not twistedSingleton.__instance:
twistedSingleton()
twistedSingleton.evenCalls = not twistedSingleton.evenCalls
return twistedSingleton.__instan... | the_stack_v2_python_sparse | Python/2019_05_15_Problem_120_Twisted_Singleton.py | BaoCaiH/Daily_Coding_Problem | train | 0 |
4764af698b0cc084e3709ed4e28c7ad411db79e5 | [
"ImageProcessor.__init__(self, **kwargs)\nif pattern is None:\n pattern = '{SITEID}{TELID}-{INSTRUME}-{DAY-OBS|date:}-{FRAMENUM|string:04d}-{IMAGETYP|type}01.fits'\nself._formatter = FilenameFormatter(pattern)",
"img = image.copy()\nimg.format_filename(self._formatter)\nreturn img"
] | <|body_start_0|>
ImageProcessor.__init__(self, **kwargs)
if pattern is None:
pattern = '{SITEID}{TELID}-{INSTRUME}-{DAY-OBS|date:}-{FRAMENUM|string:04d}-{IMAGETYP|type}01.fits'
self._formatter = FilenameFormatter(pattern)
<|end_body_0|>
<|body_start_1|>
img = image.copy()
... | Formats the filename for an image and stores it in FNAME. | CreateFilename | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateFilename:
"""Formats the filename for an image and stores it in FNAME."""
def __init__(self, pattern: str, **kwargs: Any):
"""Init an image processor that adds a filename to an image. Args: pattern: Filename pattern."""
<|body_0|>
async def __call__(self, image: Im... | stack_v2_sparse_classes_36k_train_017839 | 1,208 | permissive | [
{
"docstring": "Init an image processor that adds a filename to an image. Args: pattern: Filename pattern.",
"name": "__init__",
"signature": "def __init__(self, pattern: str, **kwargs: Any)"
},
{
"docstring": "Add filename to image. Args: image: Image to add filename to. Returns: Image with fil... | 2 | null | Implement the Python class `CreateFilename` described below.
Class description:
Formats the filename for an image and stores it in FNAME.
Method signatures and docstrings:
- def __init__(self, pattern: str, **kwargs: Any): Init an image processor that adds a filename to an image. Args: pattern: Filename pattern.
- as... | Implement the Python class `CreateFilename` described below.
Class description:
Formats the filename for an image and stores it in FNAME.
Method signatures and docstrings:
- def __init__(self, pattern: str, **kwargs: Any): Init an image processor that adds a filename to an image. Args: pattern: Filename pattern.
- as... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class CreateFilename:
"""Formats the filename for an image and stores it in FNAME."""
def __init__(self, pattern: str, **kwargs: Any):
"""Init an image processor that adds a filename to an image. Args: pattern: Filename pattern."""
<|body_0|>
async def __call__(self, image: Im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateFilename:
"""Formats the filename for an image and stores it in FNAME."""
def __init__(self, pattern: str, **kwargs: Any):
"""Init an image processor that adds a filename to an image. Args: pattern: Filename pattern."""
ImageProcessor.__init__(self, **kwargs)
if pattern is N... | the_stack_v2_python_sparse | pyobs/images/processors/misc/createfilename.py | pyobs/pyobs-core | train | 9 |
6544b630174ec46621b87b7fff5e3fddeef21266 | [
"url = self.trimUrlPrefix(urlTrait.url)\nif url and self.isTnsStyle(url):\n EMPTY = OracleTnsRecordParser.EMPTY\n obj = OracleTnsRecordParser().parse(url)\n uniqueHostCount = self._countUniqueHosts(obj)\n description = self._getDescription(obj)\n serviceName = description.connect_data.service_name\n ... | <|body_start_0|>
url = self.trimUrlPrefix(urlTrait.url)
if url and self.isTnsStyle(url):
EMPTY = OracleTnsRecordParser.EMPTY
obj = OracleTnsRecordParser().parse(url)
uniqueHostCount = self._countUniqueHosts(obj)
description = self._getDescription(obj)
... | Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host. | OracleThinRacCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OracleThinRacCase:
"""Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host."""
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
<|body_0|>
def parse(self, url):
""... | stack_v2_sparse_classes_36k_train_017840 | 40,819 | no_license | [
{
"docstring": "@types: jdbc_url_parser.Trait -> bool",
"name": "isApplicableUrlTrait",
"signature": "def isApplicableUrlTrait(self, urlTrait)"
},
{
"docstring": "@types: str -> tuple[db.DatabaseServer]",
"name": "parse",
"signature": "def parse(self, url)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003403 | Implement the Python class `OracleThinRacCase` described below.
Class description:
Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host.
Method signatures and docstrings:
- def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool
- ... | Implement the Python class `OracleThinRacCase` described below.
Class description:
Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host.
Method signatures and docstrings:
- def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool
- ... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class OracleThinRacCase:
"""Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host."""
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
<|body_0|>
def parse(self, url):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OracleThinRacCase:
"""Parses tns-like record that represents oracle rac The url should contain service name and more then one unique host."""
def isApplicableUrlTrait(self, urlTrait):
"""@types: jdbc_url_parser.Trait -> bool"""
url = self.trimUrlPrefix(urlTrait.url)
if url and sel... | the_stack_v2_python_sparse | reference/ucmdb/discovery/jdbc_url_parser.py | madmonkyang/cda-record | train | 0 |
c157136efb139f9fc714f2424c90790ed365bda6 | [
"data = super().get_html()\nif data != '':\n return data\nelse:\n course_updates = self.order_updates(self.items)\n context = {'visible_updates': course_updates[:3], 'hidden_updates': course_updates[3:]}\n return self.system.render_template(f'{self.TEMPLATE_DIR}/course_updates.html', context)",
"sorte... | <|body_start_0|>
data = super().get_html()
if data != '':
return data
else:
course_updates = self.order_updates(self.items)
context = {'visible_updates': course_updates[:3], 'hidden_updates': course_updates[3:]}
return self.system.render_template(f... | These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones | CourseInfoBlock | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseInfoBlock:
"""These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones"""
def get_html(self):
"""Returns html required for rendering XModule."""
<|body_0|>
def order_updat... | stack_v2_sparse_classes_36k_train_017841 | 18,983 | permissive | [
{
"docstring": "Returns html required for rendering XModule.",
"name": "get_html",
"signature": "def get_html(self)"
},
{
"docstring": "Returns any course updates in reverse chronological order.",
"name": "order_updates",
"signature": "def order_updates(self, updates)"
},
{
"docs... | 3 | null | Implement the Python class `CourseInfoBlock` described below.
Class description:
These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones
Method signatures and docstrings:
- def get_html(self): Returns html required for rend... | Implement the Python class `CourseInfoBlock` described below.
Class description:
These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones
Method signatures and docstrings:
- def get_html(self): Returns html required for rend... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CourseInfoBlock:
"""These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones"""
def get_html(self):
"""Returns html required for rendering XModule."""
<|body_0|>
def order_updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseInfoBlock:
"""These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located in order to be able to create new ones"""
def get_html(self):
"""Returns html required for rendering XModule."""
data = super().get_html()
if data !=... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/html_module.py | luque/better-ways-of-thinking-about-software | train | 3 |
3f2cca56794fe17efa76cdd3da8d4159e7d5408c | [
"self = real_self.magic\nrezensent_string = getFormatter(' ')(self.reviewAuthors[0]['firstname'], self.reviewAuthors[0]['lastname'])\nif rezensent_string:\n rezensent_string = '(%s)' % real_self.directTranslate(Message(u'presented_by', 'recensio', mapping={u'review_authors': rezensent_string}))\nfull_citation = ... | <|body_start_0|>
self = real_self.magic
rezensent_string = getFormatter(' ')(self.reviewAuthors[0]['firstname'], self.reviewAuthors[0]['lastname'])
if rezensent_string:
rezensent_string = '(%s)' % real_self.directTranslate(Message(u'presented_by', 'recensio', mapping={u'review_author... | PresentationMonographNoMagic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresentationMonographNoMagic:
def getDecoratedTitle(real_self):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle = "Plone 4.0. Das Benutzerhandbuch" >>> at_mock.... | stack_v2_sparse_classes_36k_train_017842 | 16,623 | no_license | [
{
"docstring": ">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: \"Patrick Gerken / Alexander Pilz\" >>> at_mock.punctuated_title_and_subtitle = \"Plone 4.0. Das Benutzerhandbuch\" >>> at_mock.reviewAuthors = [{'firstname' : 'Cillian', 'lastname' : 'de Roiste'}] >... | 2 | stack_v2_sparse_classes_30k_train_018596 | Implement the Python class `PresentationMonographNoMagic` described below.
Class description:
Implement the PresentationMonographNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self): >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: "Patric... | Implement the Python class `PresentationMonographNoMagic` described below.
Class description:
Implement the PresentationMonographNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self): >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: "Patric... | acf6ca3c962bfcf50600739087973de3ba7ad124 | <|skeleton|>
class PresentationMonographNoMagic:
def getDecoratedTitle(real_self):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle = "Plone 4.0. Das Benutzerhandbuch" >>> at_mock.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PresentationMonographNoMagic:
def getDecoratedTitle(real_self):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle = "Plone 4.0. Das Benutzerhandbuch" >>> at_mock.reviewAuthors ... | the_stack_v2_python_sparse | recensio/contenttypes/content/presentationmonograph.py | syslabcom/recensio.contenttypes | train | 0 | |
6718f31ac4f3a60952497035881addfe049e3a4b | [
"Dialog.__init__(self, text, font, screen, False)\nself.scriptEngine = scriptEngine\nself.choices = choices\nmaxWidth = max(map(self.font.calcWidth, self.choices))\nsize = (maxWidth + BORDER * 2 + self.sideCursor.get_width(), (self.font.height + LINEBUFFER) * len(self.choices) - LINEBUFFER + BORDER * 2)\nself.choic... | <|body_start_0|>
Dialog.__init__(self, text, font, screen, False)
self.scriptEngine = scriptEngine
self.choices = choices
maxWidth = max(map(self.font.calcWidth, self.choices))
size = (maxWidth + BORDER * 2 + self.sideCursor.get_width(), (self.font.height + LINEBUFFER) * len(self... | Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable. | ChoiceDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, font, screen, scriptEngine, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dial... | stack_v2_sparse_classes_36k_train_017843 | 7,526 | no_license | [
{
"docstring": "Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font with which to write the text. screen - the surface to draw the dialog onto. scriptEngine - the engine to return the option chosen to. choices - the possible options to choose from... | 3 | stack_v2_sparse_classes_30k_train_021456 | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, font, screen, scriptEngine, choices): Initialize the dialog and create the cho... | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, font, screen, scriptEngine, choices): Initialize the dialog and create the cho... | 35f58b9c931bd2bef7fd2002cadd468523ffbb5d | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, font, screen, scriptEngine, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, font, screen, scriptEngine, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - th... | the_stack_v2_python_sparse | dialog.py | wollywatson/DittoEngine | train | 0 |
d67b74109768d9e365b61646f3162ea5ebbd4307 | [
"initial = []\nfor prefix in result:\n description, objects = result[prefix]\n initial += [{'prefix': prefix, 'description': description, 'objects': ', '.join(objects)}]\nAddAddressFormSet = formset_factory(self.AddAddressForm, extra=0, can_delete=True)\nformset = AddAddressFormSet(initial=initial)\nreturn se... | <|body_start_0|>
initial = []
for prefix in result:
description, objects = result[prefix]
initial += [{'prefix': prefix, 'description': description, 'objects': ', '.join(objects)}]
AddAddressFormSet = formset_factory(self.AddAddressForm, extra=0, can_delete=True)
... | Route import application | RouteImportAppplication | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouteImportAppplication:
"""Route import application"""
def render_result(self, request, result):
"""Display form with imported data :param request: :param result: :return:"""
<|body_0|>
def view_submit(self, request):
"""Submit imported data :param request: :ret... | stack_v2_sparse_classes_36k_train_017844 | 5,449 | permissive | [
{
"docstring": "Display form with imported data :param request: :param result: :return:",
"name": "render_result",
"signature": "def render_result(self, request, result)"
},
{
"docstring": "Submit imported data :param request: :return:",
"name": "view_submit",
"signature": "def view_subm... | 2 | stack_v2_sparse_classes_30k_train_002687 | Implement the Python class `RouteImportAppplication` described below.
Class description:
Route import application
Method signatures and docstrings:
- def render_result(self, request, result): Display form with imported data :param request: :param result: :return:
- def view_submit(self, request): Submit imported data... | Implement the Python class `RouteImportAppplication` described below.
Class description:
Route import application
Method signatures and docstrings:
- def render_result(self, request, result): Display form with imported data :param request: :param result: :return:
- def view_submit(self, request): Submit imported data... | 2ab0ab7718bb7116da2c3953efd466757e11d9ce | <|skeleton|>
class RouteImportAppplication:
"""Route import application"""
def render_result(self, request, result):
"""Display form with imported data :param request: :param result: :return:"""
<|body_0|>
def view_submit(self, request):
"""Submit imported data :param request: :ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RouteImportAppplication:
"""Route import application"""
def render_result(self, request, result):
"""Display form with imported data :param request: :param result: :return:"""
initial = []
for prefix in result:
description, objects = result[prefix]
initial ... | the_stack_v2_python_sparse | ip/apps/routeimport/views.py | DreamerDDL/noc | train | 0 |
949d3ca8c71477069db6cb231627b103d362a305 | [
"self._to_produce: DefaultDict[ChemicalName, int] = defaultdict(int)\nself._reactions = reactions if reactions else dict()\nself.ore: int = 0",
"reactions = dict()\nfor line in data.strip().split('\\n'):\n ins_str, out_str = line.split(' => ')\n out = ChemicalRecipe.from_str(out_str)\n ins = [ChemicalRec... | <|body_start_0|>
self._to_produce: DefaultDict[ChemicalName, int] = defaultdict(int)
self._reactions = reactions if reactions else dict()
self.ore: int = 0
<|end_body_0|>
<|body_start_1|>
reactions = dict()
for line in data.strip().split('\n'):
ins_str, out_str = lin... | FUEL factory. | Factory | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Factory:
"""FUEL factory."""
def __init__(self, reactions: Reactions | None=None):
"""Create factory from reactions dictionary."""
<|body_0|>
def from_raw_data(cls, data: str) -> Factory:
"""Create chemical factory from the raw data."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_017845 | 3,031 | permissive | [
{
"docstring": "Create factory from reactions dictionary.",
"name": "__init__",
"signature": "def __init__(self, reactions: Reactions | None=None)"
},
{
"docstring": "Create chemical factory from the raw data.",
"name": "from_raw_data",
"signature": "def from_raw_data(cls, data: str) -> ... | 4 | stack_v2_sparse_classes_30k_train_008112 | Implement the Python class `Factory` described below.
Class description:
FUEL factory.
Method signatures and docstrings:
- def __init__(self, reactions: Reactions | None=None): Create factory from reactions dictionary.
- def from_raw_data(cls, data: str) -> Factory: Create chemical factory from the raw data.
- def ad... | Implement the Python class `Factory` described below.
Class description:
FUEL factory.
Method signatures and docstrings:
- def __init__(self, reactions: Reactions | None=None): Create factory from reactions dictionary.
- def from_raw_data(cls, data: str) -> Factory: Create chemical factory from the raw data.
- def ad... | 4b8ac6a97859b1320f77ba0ee91168b58db28cdb | <|skeleton|>
class Factory:
"""FUEL factory."""
def __init__(self, reactions: Reactions | None=None):
"""Create factory from reactions dictionary."""
<|body_0|>
def from_raw_data(cls, data: str) -> Factory:
"""Create chemical factory from the raw data."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Factory:
"""FUEL factory."""
def __init__(self, reactions: Reactions | None=None):
"""Create factory from reactions dictionary."""
self._to_produce: DefaultDict[ChemicalName, int] = defaultdict(int)
self._reactions = reactions if reactions else dict()
self.ore: int = 0
... | the_stack_v2_python_sparse | src/year2019/day14a.py | lancelote/advent_of_code | train | 11 |
d3dd3e9d81a272cc260f24b85d9208c0e4713211 | [
"super().__init__(3, parent, fitness_name)\nself.__inner_population_size = inner_population_size\nself.__number_of_inner_evaluations = number_of_inner_evaluations\nself.__optimization_algorithm = inner_optimization_algorithm",
"self._evals += 1\ndata = self._parent.get_data()\nfs_algo = self._float_to_instance(x[... | <|body_start_0|>
super().__init__(3, parent, fitness_name)
self.__inner_population_size = inner_population_size
self.__number_of_inner_evaluations = number_of_inner_evaluations
self.__optimization_algorithm = inner_optimization_algorithm
<|end_body_0|>
<|body_start_1|>
self._eva... | NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of maximum inner evaluations. __optimization_algorithm (str): Name of the optimization algorithm t... | _PipelineOptimizerProblemV2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PipelineOptimizerProblemV2:
"""NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of maximum inner evaluations. __optimizatio... | stack_v2_sparse_classes_36k_train_017846 | 21,156 | permissive | [
{
"docstring": "Initialize pipeline optimizer problem. Arguments: parent (PipelineOptimizer): Parent instance of PipelineOptimizer. fitness_name (str): Name of the fitness class to use as a function. inner_population_size (uint): Number of individuals in the hiperparameter optimization process. number_of_inner_... | 2 | stack_v2_sparse_classes_30k_train_005203 | Implement the Python class `_PipelineOptimizerProblemV2` described below.
Class description:
NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of m... | Implement the Python class `_PipelineOptimizerProblemV2` described below.
Class description:
NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of m... | 12feffb97985b2180ee7a74b28b91336c60b301f | <|skeleton|>
class _PipelineOptimizerProblemV2:
"""NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of maximum inner evaluations. __optimizatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _PipelineOptimizerProblemV2:
"""NiaPy Problem class implementation. Date: 2020 Author: Luka Pečnik Attributes: __inner_population_size (uint): Number of individuals in the hiperparameter optimization process. __number_of_inner_evaluations (uint): Number of maximum inner evaluations. __optimization_algorithm (... | the_stack_v2_python_sparse | niaaml/pipeline_optimizer.py | lukapecnik/NiaAML | train | 26 |
bf0d84f204b3936db47a4eed12a5a9f24a8d7ed9 | [
"fileInfo, hduInfoList = self.parse.getInfo(infile)\ncalibType = self.parse.getCalibType(infile)\nif calibType not in self.register.config.tables:\n self.log.warn(str(\"Skipped adding %s of observation type '%s' to registry (must be one of %s)\" % (infile, calibType, ', '.join(self.register.config.tables))))\n ... | <|body_start_0|>
fileInfo, hduInfoList = self.parse.getInfo(infile)
calibType = self.parse.getCalibType(infile)
if calibType not in self.register.config.tables:
self.log.warn(str("Skipped adding %s of observation type '%s' to registry (must be one of %s)" % (infile, calibType, ', '.j... | PfsIngestCalibsTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PfsIngestCalibsTask:
def runFile(self, infile, registry, args):
"""Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite3.Connection` Registry database connection. args : `argparse.Namespace` Parsed command-line arguments. Retur... | stack_v2_sparse_classes_36k_train_017847 | 39,514 | no_license | [
{
"docstring": "Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite3.Connection` Registry database connection. args : `argparse.Namespace` Parsed command-line arguments. Returns ------- calibType : `str` Calibration type (e.g., bias, dark, flat), or ... | 2 | stack_v2_sparse_classes_30k_train_008660 | Implement the Python class `PfsIngestCalibsTask` described below.
Class description:
Implement the PfsIngestCalibsTask class.
Method signatures and docstrings:
- def runFile(self, infile, registry, args): Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite... | Implement the Python class `PfsIngestCalibsTask` described below.
Class description:
Implement the PfsIngestCalibsTask class.
Method signatures and docstrings:
- def runFile(self, infile, registry, args): Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite... | d3b59dd73a68da6da3471c12abe203019c6a3cbe | <|skeleton|>
class PfsIngestCalibsTask:
def runFile(self, infile, registry, args):
"""Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite3.Connection` Registry database connection. args : `argparse.Namespace` Parsed command-line arguments. Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PfsIngestCalibsTask:
def runFile(self, infile, registry, args):
"""Examine and ingest a single file Parameters ---------- infile : `str` Name of file to process. registry : `sqlite3.Connection` Registry database connection. args : `argparse.Namespace` Parsed command-line arguments. Returns ------- cal... | the_stack_v2_python_sparse | python/lsst/obs/pfs/ingest.py | Subaru-PFS/obs_pfs | train | 1 | |
ebf9cec73261dd686fbb9add612c13d312c723c1 | [
"self.azimuth = INITIAL_AZ\nself.altitude = INITIAL_ALT\nself.parked = True\nself.ser = Serial(port, baud)",
"steps_alt = round((alt - self.altitude) * STEPS_PER_ALT_DEG)\nsteps_azi = round((azi - self.azimuth) * STEPS_PER_AZ_DEG)\nself.azimuth = azi\nself.altitude = alt\nself.ser.write('{},{}'.format(steps_alt, ... | <|body_start_0|>
self.azimuth = INITIAL_AZ
self.altitude = INITIAL_ALT
self.parked = True
self.ser = Serial(port, baud)
<|end_body_0|>
<|body_start_1|>
steps_alt = round((alt - self.altitude) * STEPS_PER_ALT_DEG)
steps_azi = round((azi - self.azimuth) * STEPS_PER_AZ_DEG)... | A class for writing to the antenna serial port to position the antenna. | Antenna | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Antenna:
"""A class for writing to the antenna serial port to position the antenna."""
def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD):
"""Initialize with the unparsed sentence."""
<|body_0|>
def set_position(self, azi: float, alt: float) -> None:
... | stack_v2_sparse_classes_36k_train_017848 | 2,243 | no_license | [
{
"docstring": "Initialize with the unparsed sentence.",
"name": "__init__",
"signature": "def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD)"
},
{
"docstring": "Convert azimuth and altitude angles to steps and write to the antenna serial port.",
"name": "set_position",
"sign... | 4 | stack_v2_sparse_classes_30k_train_003502 | Implement the Python class `Antenna` described below.
Class description:
A class for writing to the antenna serial port to position the antenna.
Method signatures and docstrings:
- def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD): Initialize with the unparsed sentence.
- def set_position(self, azi: floa... | Implement the Python class `Antenna` described below.
Class description:
A class for writing to the antenna serial port to position the antenna.
Method signatures and docstrings:
- def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD): Initialize with the unparsed sentence.
- def set_position(self, azi: floa... | 480d96309746be125c28f3795d78c84931181c00 | <|skeleton|>
class Antenna:
"""A class for writing to the antenna serial port to position the antenna."""
def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD):
"""Initialize with the unparsed sentence."""
<|body_0|>
def set_position(self, azi: float, alt: float) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Antenna:
"""A class for writing to the antenna serial port to position the antenna."""
def __init__(self, port: str=MOUNT_PORT, baud: int=MOUNT_BAUD):
"""Initialize with the unparsed sentence."""
self.azimuth = INITIAL_AZ
self.altitude = INITIAL_ALT
self.parked = True
... | the_stack_v2_python_sparse | Golden TRTL/antenna.py | mkpjnx/MEO_Sat_Tracking | train | 0 |
23e8e77721e40adfef3a68dd3f75ff88cd5a04a8 | [
"import sys\nself.assertNotIn('maya.standalone', sys.modules)\nself.assertNotIn('AL', sys.modules)\nself.assertNotIn('AL.usdmaya', sys.modules)\nimport AL.usdmaya\nself.assertIn('AL', sys.modules)\nself.assertIn('AL.usdmaya', sys.modules)",
"import AL.usdmaya\nself.assertTrue(hasattr(AL.usdmaya, 'ExportFlag'))\ns... | <|body_start_0|>
import sys
self.assertNotIn('maya.standalone', sys.modules)
self.assertNotIn('AL', sys.modules)
self.assertNotIn('AL.usdmaya', sys.modules)
import AL.usdmaya
self.assertIn('AL', sys.modules)
self.assertIn('AL.usdmaya', sys.modules)
<|end_body_0|>
... | TestPythonModule | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPythonModule:
def testImport(self):
"""Test that we can import the AL.usdmaya module, and that it links correctly"""
<|body_0|>
def test_ExportFlag(self):
"""Test ExportFlag enum."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import sys
... | stack_v2_sparse_classes_36k_train_017849 | 2,362 | permissive | [
{
"docstring": "Test that we can import the AL.usdmaya module, and that it links correctly",
"name": "testImport",
"signature": "def testImport(self)"
},
{
"docstring": "Test ExportFlag enum.",
"name": "test_ExportFlag",
"signature": "def test_ExportFlag(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019033 | Implement the Python class `TestPythonModule` described below.
Class description:
Implement the TestPythonModule class.
Method signatures and docstrings:
- def testImport(self): Test that we can import the AL.usdmaya module, and that it links correctly
- def test_ExportFlag(self): Test ExportFlag enum. | Implement the Python class `TestPythonModule` described below.
Class description:
Implement the TestPythonModule class.
Method signatures and docstrings:
- def testImport(self): Test that we can import the AL.usdmaya module, and that it links correctly
- def test_ExportFlag(self): Test ExportFlag enum.
<|skeleton|>
... | dc1c13a3f8012b2a99a45e46fb30250fd4b82487 | <|skeleton|>
class TestPythonModule:
def testImport(self):
"""Test that we can import the AL.usdmaya module, and that it links correctly"""
<|body_0|>
def test_ExportFlag(self):
"""Test ExportFlag enum."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPythonModule:
def testImport(self):
"""Test that we can import the AL.usdmaya module, and that it links correctly"""
import sys
self.assertNotIn('maya.standalone', sys.modules)
self.assertNotIn('AL', sys.modules)
self.assertNotIn('AL.usdmaya', sys.modules)
i... | the_stack_v2_python_sparse | plugin/al/plugin/AL_USDMayaTestPlugin/py/testUSDMayaPythonModuleOnly.py | Autodesk/maya-usd | train | 692 | |
5f35675176be57dcdab55b546f372315a571762a | [
"super().__init__()\nutils.check_file_readable(model_file)\nself.model = None\nwith open(model_file, 'rb') as icstream:\n try:\n self.model = pickle.load(icstream)\n except Exception as e:\n raise CaughtException('Exception encountered when loading the classifier: {}'.format(e))\nself.name = typ... | <|body_start_0|>
super().__init__()
utils.check_file_readable(model_file)
self.model = None
with open(model_file, 'rb') as icstream:
try:
self.model = pickle.load(icstream)
except Exception as e:
raise CaughtException('Exception enc... | Class used to load classification models and to predict class and class-probability for new documents. | LoadClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
<|body_0|>
def classify_doc(self, feat):
"""Test the classifi... | stack_v2_sparse_classes_36k_train_017850 | 3,842 | permissive | [
{
"docstring": "Load classifier model from binary file",
"name": "__init__",
"signature": "def __init__(self, model_file)"
},
{
"docstring": "Test the classifier on a new document",
"name": "classify_doc",
"signature": "def classify_doc(self, feat)"
},
{
"docstring": "Test the cl... | 4 | stack_v2_sparse_classes_30k_train_013303 | Implement the Python class `LoadClassifier` described below.
Class description:
Class used to load classification models and to predict class and class-probability for new documents.
Method signatures and docstrings:
- def __init__(self, model_file): Load classifier model from binary file
- def classify_doc(self, fea... | Implement the Python class `LoadClassifier` described below.
Class description:
Class used to load classification models and to predict class and class-probability for new documents.
Method signatures and docstrings:
- def __init__(self, model_file): Load classifier model from binary file
- def classify_doc(self, fea... | 38dc998e0cf4ef7572d542aafe80f8b95865c464 | <|skeleton|>
class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
<|body_0|>
def classify_doc(self, feat):
"""Test the classifi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadClassifier:
"""Class used to load classification models and to predict class and class-probability for new documents."""
def __init__(self, model_file):
"""Load classifier model from binary file"""
super().__init__()
utils.check_file_readable(model_file)
self.model = N... | the_stack_v2_python_sparse | python/lib/xi/ml/classify/load_classifier.py | lorosanu/xi-ml-topicdiscovery | train | 0 |
8c7441f70d8eb3c35ad779e9ed4a6200ab0f95e6 | [
"with open(pkl_path, 'rb') as f:\n dd = pickle.load(f)\nself.v_template = tf.Variable(undo_chumpy(dd['v_template']), name='v_template', dtype=dtype, trainable=False)\nself.size = [self.v_template.shape[0].value, 3]\nself.num_betas = dd['shapedirs'].shape[-1]\nshapedir = np.reshape(undo_chumpy(dd['shapedirs']), [... | <|body_start_0|>
with open(pkl_path, 'rb') as f:
dd = pickle.load(f)
self.v_template = tf.Variable(undo_chumpy(dd['v_template']), name='v_template', dtype=dtype, trainable=False)
self.size = [self.v_template.shape[0].value, 3]
self.num_betas = dd['shapedirs'].shape[-1]
... | SMPL_v1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMPL_v1:
def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32):
"""pkl_path is the path to a SMPL model"""
<|body_0|>
def __call__(self, beta, theta, get_skin=False, name=None):
"""Obtain SMPL with shape (beta) & pose (theta) inputs. Theta includes th... | stack_v2_sparse_classes_36k_train_017851 | 24,275 | permissive | [
{
"docstring": "pkl_path is the path to a SMPL model",
"name": "__init__",
"signature": "def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32)"
},
{
"docstring": "Obtain SMPL with shape (beta) & pose (theta) inputs. Theta includes the global rotation. Args: beta: N x 10 theta: N ... | 2 | stack_v2_sparse_classes_30k_train_011833 | Implement the Python class `SMPL_v1` described below.
Class description:
Implement the SMPL_v1 class.
Method signatures and docstrings:
- def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32): pkl_path is the path to a SMPL model
- def __call__(self, beta, theta, get_skin=False, name=None): Obtain SMP... | Implement the Python class `SMPL_v1` described below.
Class description:
Implement the SMPL_v1 class.
Method signatures and docstrings:
- def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32): pkl_path is the path to a SMPL model
- def __call__(self, beta, theta, get_skin=False, name=None): Obtain SMP... | d1dcf81d72c11e1f502f2c494cd86425f384d9cc | <|skeleton|>
class SMPL_v1:
def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32):
"""pkl_path is the path to a SMPL model"""
<|body_0|>
def __call__(self, beta, theta, get_skin=False, name=None):
"""Obtain SMPL with shape (beta) & pose (theta) inputs. Theta includes th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMPL_v1:
def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32):
"""pkl_path is the path to a SMPL model"""
with open(pkl_path, 'rb') as f:
dd = pickle.load(f)
self.v_template = tf.Variable(undo_chumpy(dd['v_template']), name='v_template', dtype=dtype, traina... | the_stack_v2_python_sparse | src/tf_smpl/batch_smpl.py | ccj5351/hmr_rgbd | train | 0 | |
c476f770732c82395a8befbb0a4b9d91574dbed6 | [
"self.X0 = X0\nself.Xf = Xf\nself.tf = tf",
"tau = T / self.tf\nYf = tau ** 2 * (3 - 2 * tau)\nY0 = 1 - Yf\nreturn self.X0 * Y0 + self.Xf * Yf",
"tau = T / self.tf\ndYf_dtau = 6 * tau * (1 - tau)\ndY0_dtau = -dYf_dtau\nreturn self.X0 * dY0_dtau + self.Xf * dYf_dtau"
] | <|body_start_0|>
self.X0 = X0
self.Xf = Xf
self.tf = tf
<|end_body_0|>
<|body_start_1|>
tau = T / self.tf
Yf = tau ** 2 * (3 - 2 * tau)
Y0 = 1 - Yf
return self.X0 * Y0 + self.Xf * Yf
<|end_body_1|>
<|body_start_2|>
tau = T / self.tf
dYf_dtau = 6 ... | 3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be called to return spline states at an array of times. Attributes: X0: ndarray (1, n... | SplineOrd3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplineOrd3:
"""3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be called to return spline states at an array o... | stack_v2_sparse_classes_36k_train_017852 | 1,656 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, X0, Xf, tf)"
},
{
"docstring": "Return the splined states. Args: T : ndarray An (m, 1) array of times. Returns: X : ndarray An (m, n) array of states.",
"name": "X",
"signature": "def X(self, T)"
},
{
"docst... | 3 | null | Implement the Python class `SplineOrd3` described below.
Class description:
3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be calle... | Implement the Python class `SplineOrd3` described below.
Class description:
3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be calle... | 366a3727f32b4a7fadb7bed0b7201f46ac8aa4bd | <|skeleton|>
class SplineOrd3:
"""3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be called to return spline states at an array o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplineOrd3:
"""3rd order spline that matches initial and final position and velocity. Given an initial and final state, generates a cubic spline that matches the provided initial and final states and state velocities across the time frame given. Can be called to return spline states at an array of times. Attr... | the_stack_v2_python_sparse | utilities/spline_ord3.py | nibudd/orbital_elements | train | 1 |
95f66c00376d87fab66cceee2a492c4392e1b4be | [
"self.cluster = cluster\nself.container = container\nself.name = name\nself.mtype = mtype",
"if dictionary is None:\n return None\ncluster = cohesity_management_sdk.models.elastifile_cluster.ElastifileCluster.from_dictionary(dictionary.get('cluster')) if dictionary.get('cluster') else None\ncontainer = cohesit... | <|body_start_0|>
self.cluster = cluster
self.container = container
self.name = name
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
cluster = cohesity_management_sdk.models.elastifile_cluster.ElastifileCluster.from_dictio... | Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the entity type is 'kCluster'. container (ElastifileContainer): Specifies a container in an Elast... | ElastifileProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElastifileProtectionSource:
"""Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the entity type is 'kCluster'. container (E... | stack_v2_sparse_classes_36k_train_017853 | 2,766 | permissive | [
{
"docstring": "Constructor for the ElastifileProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, cluster=None, container=None, name=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary rep... | 2 | null | Implement the Python class `ElastifileProtectionSource` described below.
Class description:
Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the ... | Implement the Python class `ElastifileProtectionSource` described below.
Class description:
Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ElastifileProtectionSource:
"""Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the entity type is 'kCluster'. container (E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElastifileProtectionSource:
"""Implementation of the 'ElastifileProtectionSource' model. Specifies a Protection Source in Elastifile environment. Attributes: cluster (ElastifileCluster): Specifies information of Elastifile Cluster. This is set only when the entity type is 'kCluster'. container (ElastifileCont... | the_stack_v2_python_sparse | cohesity_management_sdk/models/elastifile_protection_source.py | cohesity/management-sdk-python | train | 24 |
cee6863466c6a3567b47f0e8e23aa00c9e2e06f5 | [
"pos_inds = torch.nonzero(assign_result.labels[:, 0] > 0, as_tuple=False)\nif pos_inds.numel() != 0:\n pos_inds = pos_inds.squeeze(1)\nif pos_inds.numel() <= num_expected:\n return pos_inds\nelse:\n return self.random_choice(pos_inds, num_expected)",
"neg_inds = torch.nonzero(assign_result.labels[:, 0] =... | <|body_start_0|>
pos_inds = torch.nonzero(assign_result.labels[:, 0] > 0, as_tuple=False)
if pos_inds.numel() != 0:
pos_inds = pos_inds.squeeze(1)
if pos_inds.numel() <= num_expected:
return pos_inds
else:
return self.random_choice(pos_inds, num_expect... | Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replaced by `MultiInsRandomSampler` | MultiInsRandomSampler | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiInsRandomSampler:
"""Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replaced by `MultiInsRandomSampler`"""
d... | stack_v2_sparse_classes_36k_train_017854 | 5,250 | permissive | [
{
"docstring": "Randomly sample some positive samples. Args: assign_result (:obj:`AssignResult`): Bbox assigning results. num_expected (int): The number of expected positive samples Returns: Tensor or ndarray: sampled indices.",
"name": "_sample_pos",
"signature": "def _sample_pos(self, assign_result: A... | 3 | null | Implement the Python class `MultiInsRandomSampler` described below.
Class description:
Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replac... | Implement the Python class `MultiInsRandomSampler` described below.
Class description:
Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replac... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class MultiInsRandomSampler:
"""Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replaced by `MultiInsRandomSampler`"""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiInsRandomSampler:
"""Random sampler for multi instance. Note: Multi-instance means to predict multiple detection boxes with one proposal box. `AssignResult` may assign multiple gt boxes to each proposal box, in this case `RandomSampler` should be replaced by `MultiInsRandomSampler`"""
def _sample_po... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/task_modules/samplers/multi_instance_random_sampler.py | alldatacenter/alldata | train | 774 |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)\nserializer = LibraryBundleLinkUpdateSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\napi.update_bundle_link(key, link_id, version=serialize... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)
serializer = LibraryBundleLinkUpdateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
api.up... | View to update/delete an existing library link | LibraryLinkDetailView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest p... | stack_v2_sparse_classes_36k_train_017855 | 42,120 | permissive | [
{
"docstring": "Update the specified link to point to a different version of its target bundle. Pass e.g. {\"version\": 40} or pass {\"version\": None} to update to the latest published version.",
"name": "patch",
"signature": "def patch(self, request, lib_key_str, link_id)"
},
{
"docstring": "D... | 2 | null | Implement the Python class `LibraryLinkDetailView` described below.
Class description:
View to update/delete an existing library link
Method signatures and docstrings:
- def patch(self, request, lib_key_str, link_id): Update the specified link to point to a different version of its target bundle. Pass e.g. {"version"... | Implement the Python class `LibraryLinkDetailView` described below.
Class description:
View to update/delete an existing library link
Method signatures and docstrings:
- def patch(self, request, lib_key_str, link_id): Update the specified link to point to a different version of its target bundle. Pass e.g. {"version"... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest published vers... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"locations = get_list_or_404(Location)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(locations, request)\n serializer = LocationSerializer(results, ... | <|body_start_0|>
locations = get_list_or_404(Location)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
if pagination == 'true':
paginator = AdministratorPagination()
results = paginator.paginate_queryset(locations, requ... | LocationList | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
... | stack_v2_sparse_classes_36k_train_017856 | 30,608 | permissive | [
{
"docstring": "List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: false type: string paramType: query",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create new location --- ser... | 2 | stack_v2_sparse_classes_30k_train_000131 | Implement the Python class `LocationList` described below.
Class description:
Implement the LocationList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: fal... | Implement the Python class `LocationList` described below.
Class description:
Implement the LocationList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: fal... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class LocationList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.LocationSerializer parameters: - name: pagination required: false type: string paramType: query"""
locations = get_list_or_404(Location)
if request.GET.get('pagin... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
b2ff012c9c3ffe7e9e62a04c8fbbaecffde68af2 | [
"super().__init__(device=device)\nself.n_components = n_components\nif kernel is None:\n kernel = GaussianRBF()\nself.kernel = kernel\nself.nystroem = _Nystroem(self.kernel, self.n_components)\nself.nu = nu",
"scores = self.score(x)\nif not torch.jit.is_scripting():\n self.check_threshold_inferred()\npreds ... | <|body_start_0|>
super().__init__(device=device)
self.n_components = n_components
if kernel is None:
kernel = GaussianRBF()
self.kernel = kernel
self.nystroem = _Nystroem(self.kernel, self.n_components)
self.nu = nu
<|end_body_0|>
<|body_start_1|>
sco... | SVMTorch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVMTorch:
def __init__(self, nu: float, kernel: 'torch.nn.Module'=None, n_components: Optional[int]=None, device: TorchDeviceType=None):
"""Pytorch backend for the Support Vector Machine (SVM) outlier detector. Parameters ---------- nu The proportion of the training data that should be c... | stack_v2_sparse_classes_36k_train_017857 | 15,906 | permissive | [
{
"docstring": "Pytorch backend for the Support Vector Machine (SVM) outlier detector. Parameters ---------- nu The proportion of the training data that should be considered outliers. Note that this does not necessarily correspond to the false positive rate on test data, which is still defined when calling the ... | 2 | null | Implement the Python class `SVMTorch` described below.
Class description:
Implement the SVMTorch class.
Method signatures and docstrings:
- def __init__(self, nu: float, kernel: 'torch.nn.Module'=None, n_components: Optional[int]=None, device: TorchDeviceType=None): Pytorch backend for the Support Vector Machine (SVM... | Implement the Python class `SVMTorch` described below.
Class description:
Implement the SVMTorch class.
Method signatures and docstrings:
- def __init__(self, nu: float, kernel: 'torch.nn.Module'=None, n_components: Optional[int]=None, device: TorchDeviceType=None): Pytorch backend for the Support Vector Machine (SVM... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class SVMTorch:
def __init__(self, nu: float, kernel: 'torch.nn.Module'=None, n_components: Optional[int]=None, device: TorchDeviceType=None):
"""Pytorch backend for the Support Vector Machine (SVM) outlier detector. Parameters ---------- nu The proportion of the training data that should be c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVMTorch:
def __init__(self, nu: float, kernel: 'torch.nn.Module'=None, n_components: Optional[int]=None, device: TorchDeviceType=None):
"""Pytorch backend for the Support Vector Machine (SVM) outlier detector. Parameters ---------- nu The proportion of the training data that should be considered outl... | the_stack_v2_python_sparse | alibi_detect/od/pytorch/svm.py | SeldonIO/alibi-detect | train | 1,922 | |
9a62c8220a71ace2ef5f4aa7f780662ce705e478 | [
"required_amps = power / self.voltage / self.inverter_efficiency * time_scale\nif self.status >= required_amps:\n self.status -= required_amps\n return True\nreturn False",
"total_coulombs = current * time_scale\nif self.status + total_coulombs <= self.capacity:\n self.status += total_coulombs\n retur... | <|body_start_0|>
required_amps = power / self.voltage / self.inverter_efficiency * time_scale
if self.status >= required_amps:
self.status -= required_amps
return True
return False
<|end_body_0|>
<|body_start_1|>
total_coulombs = current * time_scale
if s... | Base class for battery-like classes | EnergyBuffer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnergyBuffer:
"""Base class for battery-like classes"""
def erogate(self, power, time_scale):
"""Erogate power from energy buffer"""
<|body_0|>
def charge(self, current, time_scale):
"""Charge energy buffer from current"""
<|body_1|>
def update_state... | stack_v2_sparse_classes_36k_train_017858 | 15,585 | permissive | [
{
"docstring": "Erogate power from energy buffer",
"name": "erogate",
"signature": "def erogate(self, power, time_scale)"
},
{
"docstring": "Charge energy buffer from current",
"name": "charge",
"signature": "def charge(self, current, time_scale)"
},
{
"docstring": "Update energy... | 3 | stack_v2_sparse_classes_30k_train_002252 | Implement the Python class `EnergyBuffer` described below.
Class description:
Base class for battery-like classes
Method signatures and docstrings:
- def erogate(self, power, time_scale): Erogate power from energy buffer
- def charge(self, current, time_scale): Charge energy buffer from current
- def update_state(sel... | Implement the Python class `EnergyBuffer` described below.
Class description:
Base class for battery-like classes
Method signatures and docstrings:
- def erogate(self, power, time_scale): Erogate power from energy buffer
- def charge(self, current, time_scale): Charge energy buffer from current
- def update_state(sel... | 2d16c1bc8efb65d71040d1b8d61d9cece6f008d6 | <|skeleton|>
class EnergyBuffer:
"""Base class for battery-like classes"""
def erogate(self, power, time_scale):
"""Erogate power from energy buffer"""
<|body_0|>
def charge(self, current, time_scale):
"""Charge energy buffer from current"""
<|body_1|>
def update_state... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnergyBuffer:
"""Base class for battery-like classes"""
def erogate(self, power, time_scale):
"""Erogate power from energy buffer"""
required_amps = power / self.voltage / self.inverter_efficiency * time_scale
if self.status >= required_amps:
self.status -= required_am... | the_stack_v2_python_sparse | src/main/python/aries/core/grid/agent.py | comnetstud/ARIES | train | 0 |
fbab0e6cadc63d0d5dcc295debc8583291404c5d | [
"self.args = args\nself.work_dir = work_dir\nself.result_file = None\nself.args_ns = args_ns",
"full_file_name = os.path.join(self.work_dir, _TEST_RESULT_NAME)\ntry:\n self.result_file = open(full_file_name, 'w')\nexcept IOError:\n logging.error('Cannot open file %s', full_file_name)\nreturn self.result_fil... | <|body_start_0|>
self.args = args
self.work_dir = work_dir
self.result_file = None
self.args_ns = args_ns
<|end_body_0|>
<|body_start_1|>
full_file_name = os.path.join(self.work_dir, _TEST_RESULT_NAME)
try:
self.result_file = open(full_file_name, 'w')
... | Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTest", "test_runner": { "AtestTradefedTestRunner": { "hello_world_test": { "FAILED": [ ... | AtestExecutionInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtestExecutionInfo:
"""Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTest", "test_runner": { "AtestTradefedTes... | stack_v2_sparse_classes_36k_train_017859 | 14,396 | no_license | [
{
"docstring": "Initialise an AtestExecutionInfo instance. Args: args: Command line parameters. work_dir: The directory for saving information. args_ns: An argspace.Namespace class instance holding parsed args. Returns: A json format string.",
"name": "__init__",
"signature": "def __init__(self, args, w... | 5 | null | Implement the Python class `AtestExecutionInfo` described below.
Class description:
Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTe... | Implement the Python class `AtestExecutionInfo` described below.
Class description:
Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTe... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class AtestExecutionInfo:
"""Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTest", "test_runner": { "AtestTradefedTes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AtestExecutionInfo:
"""Class that stores the whole test progress information in JSON format. ---- For example, running command atest hello_world_test HelloWorldTest will result in storing the execution detail in JSON: { "args": "hello_world_test HelloWorldTest", "test_runner": { "AtestTradefedTestRunner": { "... | the_stack_v2_python_sparse | tools/asuite/atest/atest_execution_info.py | ZYHGOD-1/Aosp11 | train | 0 |
b638f9510d8fec65c1800631f8faabb96ab26b38 | [
"super().__init__()\nif cin % config.num_attention_heads != 0:\n raise ValueError(f'cin ({cin}) is not a multiple of the number of attention heads ({config.num_attention_heads})')\nself.num_attention_heads = config.num_attention_heads\nself.attention_head_size = int(cin / config.num_attention_heads)\nself.all_he... | <|body_start_0|>
super().__init__()
if cin % config.num_attention_heads != 0:
raise ValueError(f'cin ({cin}) is not a multiple of the number of attention heads ({config.num_attention_heads})')
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = in... | SqueezeBertSelfAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqueezeBertSelfAttention:
def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1):
"""config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers"""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_017860 | 45,093 | permissive | [
{
"docstring": "config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers",
"name": "__init__",
"signature": "def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1)"
},
{
"docstrin... | 5 | null | Implement the Python class `SqueezeBertSelfAttention` described below.
Class description:
Implement the SqueezeBertSelfAttention class.
Method signatures and docstrings:
- def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1): config = used for some things; ignored for others (work in progress...) cin =... | Implement the Python class `SqueezeBertSelfAttention` described below.
Class description:
Implement the SqueezeBertSelfAttention class.
Method signatures and docstrings:
- def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1): config = used for some things; ignored for others (work in progress...) cin =... | 4fa0aff21ee083d0197a898cdf17ff476fae2ac3 | <|skeleton|>
class SqueezeBertSelfAttention:
def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1):
"""config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers"""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqueezeBertSelfAttention:
def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1):
"""config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers"""
super().__init__()
if ci... | the_stack_v2_python_sparse | src/transformers/models/squeezebert/modeling_squeezebert.py | huggingface/transformers | train | 102,193 | |
6ad64fc2d17225d944cf6a9469a42d19b12161b0 | [
"dummy = ListNode(-1)\ndummy.next = head\nnext = dummy\nwhile next != None and next.next != None:\n if next.next.val == val:\n next.next = next.next.next\n else:\n next = next.next\nreturn dummy.next",
"out = prev = ListNode(-1)\nprev.next = head\ncurr = head\nwhile curr:\n if curr.val == v... | <|body_start_0|>
dummy = ListNode(-1)
dummy.next = head
next = dummy
while next != None and next.next != None:
if next.next.val == val:
next.next = next.next.next
else:
next = next.next
return dummy.next
<|end_body_0|>
<|bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_017861 | 865 | no_license | [
{
"docstring": ":type head: ListNode :type val: int :rtype: ListNode",
"name": "removeElements",
"signature": "def removeElements(self, head, val)"
},
{
"docstring": ":type head: ListNode :type val: int :rtype: ListNode",
"name": "removeElements",
"signature": "def removeElements(self, h... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode
- def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListN... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|skeleton|>
class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_0|>
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElements(self, head, val):
""":type head: ListNode :type val: int :rtype: ListNode"""
dummy = ListNode(-1)
dummy.next = head
next = dummy
while next != None and next.next != None:
if next.next.val == val:
next.next = next.... | the_stack_v2_python_sparse | leetcode3/removeElements.py | lizyang95/leetcode | train | 0 | |
41cbcd356e023e3b87e5ea368aab2176b78ce1ff | [
"self.set_status(200)\nself.set_header('Content-Type', 'application/x-mplane+json')\nself.write(mplane.model.unparse_json(msg))\nself.finish()",
"self.set_status(code)\nif text is not None:\n self.set_header('Content-Type', 'text/plain')\n self.write(text)\nself.finish()",
"self.set_status(code)\nif text ... | <|body_start_0|>
self.set_status(200)
self.set_header('Content-Type', 'application/x-mplane+json')
self.write(mplane.model.unparse_json(msg))
self.finish()
<|end_body_0|>
<|body_start_1|>
self.set_status(code)
if text is not None:
self.set_header('Content-Typ... | Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message. | MPlaneHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPlaneHandler:
"""Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message."""
def _respond_message(self, msg):
"""Returns an HTTP response containing a JSON message"""
<|body_0|>
def _respond_plain_text(self, code, text=None):
"""R... | stack_v2_sparse_classes_36k_train_017862 | 37,893 | no_license | [
{
"docstring": "Returns an HTTP response containing a JSON message",
"name": "_respond_message",
"signature": "def _respond_message(self, msg)"
},
{
"docstring": "Returns an HTTP response containing a plain text message",
"name": "_respond_plain_text",
"signature": "def _respond_plain_te... | 3 | stack_v2_sparse_classes_30k_train_010920 | Implement the Python class `MPlaneHandler` described below.
Class description:
Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message.
Method signatures and docstrings:
- def _respond_message(self, msg): Returns an HTTP response containing a JSON message
- def _respond_plain_text(self... | Implement the Python class `MPlaneHandler` described below.
Class description:
Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message.
Method signatures and docstrings:
- def _respond_message(self, msg): Returns an HTTP response containing a JSON message
- def _respond_plain_text(self... | 25f11a1bb6c0fc6eb95935be2a2afc2fa3be9beb | <|skeleton|>
class MPlaneHandler:
"""Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message."""
def _respond_message(self, msg):
"""Returns an HTTP response containing a JSON message"""
<|body_0|>
def _respond_plain_text(self, code, text=None):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPlaneHandler:
"""Abstract tornado RequestHandler that allows a handler to respond with an mPlane Message."""
def _respond_message(self, msg):
"""Returns an HTTP response containing a JSON message"""
self.set_status(200)
self.set_header('Content-Type', 'application/x-mplane+json')... | the_stack_v2_python_sparse | mplane/client.py | mami-project/mplane-sdk | train | 1 |
82d5c2a41a0f626df3341e8d0fa2b5d2afbc6233 | [
"for i in range(1, len(nums)):\n nums[i] = max(nums[i - 1] + nums[i], nums[i])\nreturn max(nums)",
"dp = [0] * len(nums)\ndp[0] = nums[0]\nfor i in range(1, len(nums)):\n dp[i] = max(dp[i - 1] + nums[i], nums[i])\nreturn max(dp)"
] | <|body_start_0|>
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nums)
<|end_body_0|>
<|body_start_1|>
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_36k_train_017863 | 1,087 | no_license | [
{
"docstring": "Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums: list) -> int"
},
{
"docstring": "动态规划",
"name": "maxSubArray2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_003046 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums: list) -> int: Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。
- def max... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
<|body_0|>
def maxSubArray2(self, nums: list) -> int:
"""动态规划"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray1(self, nums: list) -> int:
"""Kadane算法:https://zh.wikipedia.org/wiki/%E6%9C%80%E5%A4%A7%E5%AD%90%E6%95%B0%E5%88%97%E9%97%AE%E9%A2%98 每个nums[i]存储的都是子问题的最优解。"""
for i in range(1, len(nums)):
nums[i] = max(nums[i - 1] + nums[i], nums[i])
return max(nu... | the_stack_v2_python_sparse | 053_maximum-subarray.py | helloocc/algorithm | train | 1 | |
948dee33117e79e2d2b7edc4d7b881cf8cb3c53b | [
"next_task = 0\nself._next_task_per_op = {}\nfor op in ps_ops:\n self._next_task_per_op[op] = next_task\n next_task = (next_task + 1) % num_tasks if num_tasks else 0\nself._num_tasks = num_tasks",
"if op.type not in self._next_task_per_op:\n raise ValueError(\"Unknown op type '%s' for placement:\" % op.t... | <|body_start_0|>
next_task = 0
self._next_task_per_op = {}
for op in ps_ops:
self._next_task_per_op[op] = next_task
next_task = (next_task + 1) % num_tasks if num_tasks else 0
self._num_tasks = num_tasks
<|end_body_0|>
<|body_start_1|>
if op.type not in s... | Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost. | _OpRoundRobinStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _OpRoundRobinStrategy:
"""Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost."""
def __init__(self, ps_ops, num_tasks):
"""Create ... | stack_v2_sparse_classes_36k_train_017864 | 44,404 | permissive | [
{
"docstring": "Create a new `_RoundRobinStrategy`. Args: ps_ops: List of Op types to place on PS. num_tasks: Number of ps tasks to cycle among.",
"name": "__init__",
"signature": "def __init__(self, ps_ops, num_tasks)"
},
{
"docstring": "Choose a ps task index for the given `Operation`. Args: o... | 2 | null | Implement the Python class `_OpRoundRobinStrategy` described below.
Class description:
Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost.
Method signatures and doc... | Implement the Python class `_OpRoundRobinStrategy` described below.
Class description:
Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost.
Method signatures and doc... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class _OpRoundRobinStrategy:
"""Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost."""
def __init__(self, ps_ops, num_tasks):
"""Create ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _OpRoundRobinStrategy:
"""Returns the next ps task index for placement via per-Op round-robin order. This strategy works slightly better for the GBDT graph because of using custom resources which vary significantly in compute cost."""
def __init__(self, ps_ops, num_tasks):
"""Create a new `_Round... | the_stack_v2_python_sparse | Keras_tensorflow_nightly/source2.7/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py | ryfeus/lambda-packs | train | 1,283 |
878c394dd3151d43e1ad4daec379caa83549e92f | [
"self.bg_fn = bg_fn\nself.ref_fn = ref_fn\nself.vcf_fn = vcf_fn\nself.m_ref = bgsdk.Reference(ref_fn)\nself.vcf_file = vcf.Reader(filename=vcf_fn)\nself.out_file = out\nself.threads = threads\nself.min_insert = min_insert\nself.max_insert = max_insert\nself.sample = sample\nself.gt_replace = gt_replace\nself.region... | <|body_start_0|>
self.bg_fn = bg_fn
self.ref_fn = ref_fn
self.vcf_fn = vcf_fn
self.m_ref = bgsdk.Reference(ref_fn)
self.vcf_file = vcf.Reader(filename=vcf_fn)
self.out_file = out
self.threads = threads
self.min_insert = min_insert
self.max_insert =... | Wrapper around the entire pcmp program | Pcmp | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pcmp:
"""Wrapper around the entire pcmp program"""
def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False):
"""Hold the variables"""
<|body_0|>
def __parse_regions(self, region):
... | stack_v2_sparse_classes_36k_train_017865 | 21,838 | permissive | [
{
"docstring": "Hold the variables",
"name": "__init__",
"signature": "def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False)"
},
{
"docstring": "Create the individual regions over which this run is going t... | 4 | stack_v2_sparse_classes_30k_train_010220 | Implement the Python class `Pcmp` described below.
Class description:
Wrapper around the entire pcmp program
Method signatures and docstrings:
- def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False): Hold the variables
- def __... | Implement the Python class `Pcmp` described below.
Class description:
Wrapper around the entire pcmp program
Method signatures and docstrings:
- def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False): Hold the variables
- def __... | 5f40198e95b0626ae143e021ec97884de634e61d | <|skeleton|>
class Pcmp:
"""Wrapper around the entire pcmp program"""
def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False):
"""Hold the variables"""
<|body_0|>
def __parse_regions(self, region):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pcmp:
"""Wrapper around the entire pcmp program"""
def __init__(self, bg_fn, ref_fn, vcf_fn, threads=1, out='out.vcf', min_insert=200, max_insert=1000, sample=None, region=None, gt_replace=False):
"""Hold the variables"""
self.bg_fn = bg_fn
self.ref_fn = ref_fn
self.vcf_fn... | the_stack_v2_python_sparse | python/biograph/internal/vPCMP.py | spiralgenetics/biograph | train | 21 |
2edbfe93cd887435e6a7492ad4ca83d25afbb749 | [
"cls = self.__class__\nif any((self.value == e.value for e in cls)):\n raise ValueError('Duplicates not allowed in enumerated set of values {}'.format(cls))\nif not isinstance(self.value, str):\n raise ValueError('All values of enum {} must be strings'.format(cls))",
"if name is None:\n return None\nif a... | <|body_start_0|>
cls = self.__class__
if any((self.value == e.value for e in cls)):
raise ValueError('Duplicates not allowed in enumerated set of values {}'.format(cls))
if not isinstance(self.value, str):
raise ValueError('All values of enum {} must be strings'.format(cl... | Enumeration class that can convert between enumerations and associated values. | BaseEnumeration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEnumeration:
"""Enumeration class that can convert between enumerations and associated values."""
def __init__(self, *args):
"""Ensure that there are no duplicates in the enumeration."""
<|body_0|>
def get_value(cls, name):
"""Return a valid value associated ... | stack_v2_sparse_classes_36k_train_017866 | 1,716 | permissive | [
{
"docstring": "Ensure that there are no duplicates in the enumeration.",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "Return a valid value associated with name. If name is equal to one of the enum members, or to the value associated with an enum member, then r... | 3 | stack_v2_sparse_classes_30k_train_001334 | Implement the Python class `BaseEnumeration` described below.
Class description:
Enumeration class that can convert between enumerations and associated values.
Method signatures and docstrings:
- def __init__(self, *args): Ensure that there are no duplicates in the enumeration.
- def get_value(cls, name): Return a va... | Implement the Python class `BaseEnumeration` described below.
Class description:
Enumeration class that can convert between enumerations and associated values.
Method signatures and docstrings:
- def __init__(self, *args): Ensure that there are no duplicates in the enumeration.
- def get_value(cls, name): Return a va... | 1f98fb471060bbba312b86474a5bf6818f317fe1 | <|skeleton|>
class BaseEnumeration:
"""Enumeration class that can convert between enumerations and associated values."""
def __init__(self, *args):
"""Ensure that there are no duplicates in the enumeration."""
<|body_0|>
def get_value(cls, name):
"""Return a valid value associated ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseEnumeration:
"""Enumeration class that can convert between enumerations and associated values."""
def __init__(self, *args):
"""Ensure that there are no duplicates in the enumeration."""
cls = self.__class__
if any((self.value == e.value for e in cls)):
raise Value... | the_stack_v2_python_sparse | gemd/enumeration/base_enumeration.py | lkubie/gemd-python | train | 0 |
c2c6ed0bf8ef3fc9d26c2d1e64b93963b5263c9f | [
"post_nodes = response.css('#archive > div.floated-thumb .post-thumb > a')\nfor post_node in post_nodes:\n image_url = post_node.css('img::attr(src)').extract_first('')\n post_url = post_node.css('::attr(href)').extract_first('')\n yield Request(url=parse.urljoin(response.url, post_url), meta={'front_img_u... | <|body_start_0|>
post_nodes = response.css('#archive > div.floated-thumb .post-thumb > a')
for post_node in post_nodes:
image_url = post_node.css('img::attr(src)').extract_first('')
post_url = post_node.css('::attr(href)').extract_first('')
yield Request(url=parse.url... | ArticleSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleSpider:
def parse(self, response):
"""1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:"""
<|body_0|>
def parse_detail(self, response):
"""解析目标页面的内容 :param response: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_017867 | 4,414 | no_license | [
{
"docstring": "1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "解析目标页面的内容 :param response: :return:",
"name": "parse_detail",
"signature": "def parse_detail(s... | 2 | stack_v2_sparse_classes_30k_train_020789 | Implement the Python class `ArticleSpider` described below.
Class description:
Implement the ArticleSpider class.
Method signatures and docstrings:
- def parse(self, response): 1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:
- def parse_detail(self, response): 解析目标页面... | Implement the Python class `ArticleSpider` described below.
Class description:
Implement the ArticleSpider class.
Method signatures and docstrings:
- def parse(self, response): 1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:
- def parse_detail(self, response): 解析目标页面... | df30bc43f2b99ff70c380bbadeec4bcc285d481b | <|skeleton|>
class ArticleSpider:
def parse(self, response):
"""1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:"""
<|body_0|>
def parse_detail(self, response):
"""解析目标页面的内容 :param response: :return:"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleSpider:
def parse(self, response):
"""1. 获取文章列表页中的文章url并交给解析函数进行具体字段的解析 2. 获取下一页的url并交给scrapy进行下载,下载完成后交给parse :param response: :return:"""
post_nodes = response.css('#archive > div.floated-thumb .post-thumb > a')
for post_node in post_nodes:
image_url = post_node.cs... | the_stack_v2_python_sparse | scrapy_templates/12-information/jobbole/jobbole/spiders/article.py | QuincyLi/happy-spiders | train | 0 | |
0c39f494f433581204a4332e0c75c1b0d76975f7 | [
"if db_field.name == 'name':\n kwargs['widget'] = VerboseNameShowTextWidget()\nreturn super(ResourceReqAdminInline, self).formfield_for_dbfield(db_field, **kwargs)",
"ro_fields = super(ResourceReqAdminInline, self).get_readonly_fields(request, obj=obj)\nif 'name' in ro_fields:\n ro_fields.remove('name')\nre... | <|body_start_0|>
if db_field.name == 'name':
kwargs['widget'] = VerboseNameShowTextWidget()
return super(ResourceReqAdminInline, self).formfield_for_dbfield(db_field, **kwargs)
<|end_body_0|>
<|body_start_1|>
ro_fields = super(ResourceReqAdminInline, self).get_readonly_fields(reques... | ResourceReqAdminInline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceReqAdminInline:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Readonly resource name but form input still hidden"""
<|body_0|>
def get_readonly_fields(self, request, obj=None):
"""Remove 'name' from readonly fields because its value is required to c... | stack_v2_sparse_classes_36k_train_017868 | 2,533 | no_license | [
{
"docstring": "Readonly resource name but form input still hidden",
"name": "formfield_for_dbfield",
"signature": "def formfield_for_dbfield(self, db_field, **kwargs)"
},
{
"docstring": "Remove 'name' from readonly fields because its value is required to call properly Resource.get ResourceReqFo... | 2 | null | Implement the Python class `ResourceReqAdminInline` described below.
Class description:
Implement the ResourceReqAdminInline class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Readonly resource name but form input still hidden
- def get_readonly_fields(self, request, obj=N... | Implement the Python class `ResourceReqAdminInline` described below.
Class description:
Implement the ResourceReqAdminInline class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Readonly resource name but form input still hidden
- def get_readonly_fields(self, request, obj=N... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class ResourceReqAdminInline:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Readonly resource name but form input still hidden"""
<|body_0|>
def get_readonly_fields(self, request, obj=None):
"""Remove 'name' from readonly fields because its value is required to c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceReqAdminInline:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Readonly resource name but form input still hidden"""
if db_field.name == 'name':
kwargs['widget'] = VerboseNameShowTextWidget()
return super(ResourceReqAdminInline, self).formfield_for_dbfield(... | the_stack_v2_python_sparse | controller/apps/resources/admin.py | m00dy/vct-controller | train | 2 | |
8e43b38f3de0f04edfb7c836634d04ff97584180 | [
"result = 0\nfor i in range(len(points)):\n group = collections.defaultdict(int)\n for j in range(len(points)):\n if j == i:\n continue\n dx, dy = (points[i][0] - points[j][0], points[i][1] - points[j][1])\n group[dx ** 2 + dy ** 2] += 1\n for _, v in group.items():\n ... | <|body_start_0|>
result = 0
for i in range(len(points)):
group = collections.defaultdict(int)
for j in range(len(points)):
if j == i:
continue
dx, dy = (points[i][0] - points[j][0], points[i][1] - points[j][1])
g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def numberOfBoomerangs2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 0... | stack_v2_sparse_classes_36k_train_017869 | 4,025 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "numberOfBoomerangs",
"signature": "def numberOfBoomerangs(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "numberOfBoomerangs2",
"signature": "def numberOfBoomerangs2(self, points)"... | 2 | stack_v2_sparse_classes_30k_train_009749 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int
- def numberOfBoomerangs2(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int
- def numberOfBoomerangs2(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|>
c... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def numberOfBoomerangs2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
result = 0
for i in range(len(points)):
group = collections.defaultdict(int)
for j in range(len(points)):
if j == i:
continue
... | the_stack_v2_python_sparse | leetcode_python/Hash_table/number-of-boomerangs.py | yennanliu/CS_basics | train | 64 | |
30e718aeb74dcebea62c3f791381acb56093de60 | [
"if fus_stage not in FUS2DSS:\n print(f'Custom stage \"{fus_stage}\" provided. Skipping Fusillade check.')\n return\nelse:\n self.fus_stage = fus_stage\n self.dss_stage = FUS2DSS[fus_stage]\nthis_dir = os.path.abspath(os.path.dirname(__file__))\nself.scripts_dir = this_dir\nself.dss_dir = os.path.join(t... | <|body_start_0|>
if fus_stage not in FUS2DSS:
print(f'Custom stage "{fus_stage}" provided. Skipping Fusillade check.')
return
else:
self.fus_stage = fus_stage
self.dss_stage = FUS2DSS[fus_stage]
this_dir = os.path.abspath(os.path.dirname(__file__))... | This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from roles.json is present in roles listed in fusillade | FusilladeChecker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FusilladeChecker:
"""This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from roles.json is present in roles listed in ... | stack_v2_sparse_classes_36k_train_017870 | 5,075 | permissive | [
{
"docstring": "Set up stage info and check values",
"name": "__init__",
"signature": "def __init__(self, fus_stage)"
},
{
"docstring": "Return a serialized JSON of the environment variables for this stage",
"name": "get_stage_env",
"signature": "def get_stage_env(self, env_file)"
},
... | 6 | null | Implement the Python class `FusilladeChecker` described below.
Class description:
This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from ro... | Implement the Python class `FusilladeChecker` described below.
Class description:
This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from ro... | 6b27d0f7e0110c62b3079151708689ab5145f15b | <|skeleton|>
class FusilladeChecker:
"""This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from roles.json is present in roles listed in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FusilladeChecker:
"""This class defines functionality to check that the data store roles specified in roles.json have been deployed correctly to Fusillade. Steps: - collect info from roles.json in repo and extract list of roles - check that each role from roles.json is present in roles listed in fusillade"""
... | the_stack_v2_python_sparse | scripts/check_fusillade.py | shunsunsun/data-store | train | 0 |
5cc9d4fce0ac1d601bd9ee6c6c92ec016ba228ff | [
"self.tiempo = tiempo\nself.dia = dia\nself._funcion = funcion\nself.iteracion = iteracion\nself.descripcion = descripcion\nself.afectados = afectados\nself.generador = entidad_generadora",
"tiempo1 = str(self.tiempo[0])\ntiempo2 = str(int(self.tiempo[1]))\nif len(tiempo2) < 2:\n tiempo2 = '0' + tiempo2\nretur... | <|body_start_0|>
self.tiempo = tiempo
self.dia = dia
self._funcion = funcion
self.iteracion = iteracion
self.descripcion = descripcion
self.afectados = afectados
self.generador = entidad_generadora
<|end_body_0|>
<|body_start_1|>
tiempo1 = str(self.tiempo... | Evento | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evento:
def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora):
"""tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: str, afectados: str, generador: str"""
<|body_0|>
def str_tiempo(self):
"""r... | stack_v2_sparse_classes_36k_train_017871 | 4,009 | no_license | [
{
"docstring": "tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: str, afectados: str, generador: str",
"name": "__init__",
"signature": "def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora)"
},
{
"docstring": "retorna u... | 4 | null | Implement the Python class `Evento` described below.
Class description:
Implement the Evento class.
Method signatures and docstrings:
- def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora): tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: st... | Implement the Python class `Evento` described below.
Class description:
Implement the Evento class.
Method signatures and docstrings:
- def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora): tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: st... | 884be9365cd20a87aa0a75018a724e6ca0bc0182 | <|skeleton|>
class Evento:
def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora):
"""tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: str, afectados: str, generador: str"""
<|body_0|>
def str_tiempo(self):
"""r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Evento:
def __init__(self, tiempo, dia, funcion, iteracion, descripcion, afectados, entidad_generadora):
"""tiempo: tuple(int), funcion: class function, dia: str, iteracion: int, descrpción: str, afectados: str, generador: str"""
self.tiempo = tiempo
self.dia = dia
self._funcio... | the_stack_v2_python_sparse | Tareas/T04/eventos.py | JoseAvanzada2019/IIC2233-2018-1-SantiRepo | train | 0 | |
7ab37ab224045abd7cee10ff3e0815e662abc1af | [
"self.frame = frame\nsuper().__init__(self.frame)\nself.give_shape()\nself.brick_matrix = self.make_brick_matrix(self.frame)",
"for r in range(len(self.location_n_type_matrix)):\n for c in range(len(self.location_n_type_matrix[r])):\n if r == len(self.location_n_type_matrix) - 1:\n self.locat... | <|body_start_0|>
self.frame = frame
super().__init__(self.frame)
self.give_shape()
self.brick_matrix = self.make_brick_matrix(self.frame)
<|end_body_0|>
<|body_start_1|>
for r in range(len(self.location_n_type_matrix)):
for c in range(len(self.location_n_type_matrix[... | BrickLayout for stage | LayoutStage1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutStage1:
"""BrickLayout for stage"""
def __init__(self, frame: Frame):
"""constructor for this class"""
<|body_0|>
def give_shape(self):
"""This function is from the parrent class. Now overriding it to give"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_017872 | 8,421 | no_license | [
{
"docstring": "constructor for this class",
"name": "__init__",
"signature": "def __init__(self, frame: Frame)"
},
{
"docstring": "This function is from the parrent class. Now overriding it to give",
"name": "give_shape",
"signature": "def give_shape(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017737 | Implement the Python class `LayoutStage1` described below.
Class description:
BrickLayout for stage
Method signatures and docstrings:
- def __init__(self, frame: Frame): constructor for this class
- def give_shape(self): This function is from the parrent class. Now overriding it to give | Implement the Python class `LayoutStage1` described below.
Class description:
BrickLayout for stage
Method signatures and docstrings:
- def __init__(self, frame: Frame): constructor for this class
- def give_shape(self): This function is from the parrent class. Now overriding it to give
<|skeleton|>
class LayoutStag... | c4cd10f631aba51d290395dec446850a0fbfe1b5 | <|skeleton|>
class LayoutStage1:
"""BrickLayout for stage"""
def __init__(self, frame: Frame):
"""constructor for this class"""
<|body_0|>
def give_shape(self):
"""This function is from the parrent class. Now overriding it to give"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayoutStage1:
"""BrickLayout for stage"""
def __init__(self, frame: Frame):
"""constructor for this class"""
self.frame = frame
super().__init__(self.frame)
self.give_shape()
self.brick_matrix = self.make_brick_matrix(self.frame)
def give_shape(self):
... | the_stack_v2_python_sparse | v1/brick_layout.py | ayushsharma-crypto/Brick-Breaker-Terminal-Based-Game | train | 0 |
b741e499eeb3669aad00d443fe6ddf1d485ea171 | [
"startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\ndistrictList = list(repo[STATE_SENATE_ELECTIONS_NAME].distinct('district'))\ndistr... | <|body_start_0|>
startTime = datetime.datetime.now()
if trial:
endTime = datetime.datetime.now()
return {'start': startTime, 'end': endTime}
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate(TEAM_NAME, TEAM_NAME)
districtList ... | transformationSenateDistrictIdeology | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformationSenateDistrictIdeology:
def execute(trial=False):
"""Transformation to determine basic ideology score for each house district by calculating number of republican or democratic candidates elected from each district from 2000-2018 ex) { "district" : "1st Hampden and Hampshire... | stack_v2_sparse_classes_36k_train_017873 | 6,289 | no_license | [
{
"docstring": "Transformation to determine basic ideology score for each house district by calculating number of republican or democratic candidates elected from each district from 2000-2018 ex) { \"district\" : \"1st Hampden and Hampshire\", \"percentDem\" : 70, \"percentRepub\" : 30, \"numDemWins\" : 7, \"nu... | 3 | null | Implement the Python class `transformationSenateDistrictIdeology` described below.
Class description:
Implement the transformationSenateDistrictIdeology class.
Method signatures and docstrings:
- def execute(trial=False): Transformation to determine basic ideology score for each house district by calculating number o... | Implement the Python class `transformationSenateDistrictIdeology` described below.
Class description:
Implement the transformationSenateDistrictIdeology class.
Method signatures and docstrings:
- def execute(trial=False): Transformation to determine basic ideology score for each house district by calculating number o... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformationSenateDistrictIdeology:
def execute(trial=False):
"""Transformation to determine basic ideology score for each house district by calculating number of republican or democratic candidates elected from each district from 2000-2018 ex) { "district" : "1st Hampden and Hampshire... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transformationSenateDistrictIdeology:
def execute(trial=False):
"""Transformation to determine basic ideology score for each house district by calculating number of republican or democratic candidates elected from each district from 2000-2018 ex) { "district" : "1st Hampden and Hampshire", "percentDem... | the_stack_v2_python_sparse | ldisalvo_skeesara_vidyaap/transformationSenateDistrictIdeology.py | maximega/course-2019-spr-proj | train | 2 | |
e950fbfcf69b019a8053c215eb14f042df82d41c | [
"lst = []\ns = s.strip()\ntmp = s.split(' ')\nfor i in range(len(tmp)):\n tmp[i].strip()\n if tmp[i] == '':\n continue\n lst.append(tmp[i])\nrtn = ''\nif lst != []:\n rtn = ''.join([lst.pop()])\nwhile lst != []:\n rtn = ''.join([rtn, ' ', lst.pop()])\nreturn rtn",
"s = s.strip()\nS = s.split... | <|body_start_0|>
lst = []
s = s.strip()
tmp = s.split(' ')
for i in range(len(tmp)):
tmp[i].strip()
if tmp[i] == '':
continue
lst.append(tmp[i])
rtn = ''
if lst != []:
rtn = ''.join([lst.pop()])
while... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lst = []
s = s.strip()
tmp = s.split(' ')
... | stack_v2_sparse_classes_36k_train_017874 | 2,491 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords2",
"signature": "def reverseWords2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
"... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
lst = []
s = s.strip()
tmp = s.split(' ')
for i in range(len(tmp)):
tmp[i].strip()
if tmp[i] == '':
continue
lst.append(tmp[i])
rtn = ''
... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00151.Reverse_Words_in_a_String.py | roger6blog/LeetCode | train | 0 | |
7fc8618bcd316b1997dc88ff8adf3f143db89b1e | [
"dummy = ListNode(None)\nptr = dummy\ncarry = 0\nwhile l1 or l2:\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n ptr.next = ListNode(carry % 10)\n ptr = ptr.next\n carry /= 10\nif carry != 0:\n ptr.next = ListNode(1)\nreturn dummy.n... | <|body_start_0|>
dummy = ListNode(None)
ptr = dummy
carry = 0
while l1 or l2:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
ptr.next = ListNode(carry % 10)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :typ2 l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017875 | 1,686 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :typ2 l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers2",
"signature": "def addTwoNumbers2(self, l1... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :typ2 l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :typ2 l2: ListNode :rtype: ListNode... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :typ2 l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
dummy = ListNode(None)
ptr = dummy
carry = 0
while l1 or l2:
if l1:
carry += l1.val
l1 = l1.next
if l2:
... | the_stack_v2_python_sparse | prob002_addtwonumbers.py | Hu-Wenchao/leetcode | train | 0 | |
82c29a670cd97ff382c20b51e1906d7c40adac83 | [
"count = c_int()\nself._call('GetEventCount', byref(count))\nreturn count.value",
"count = self.event_count\narray = (c_void_p * count)()\nwritten = c_int()\nself._call('GetEventList', array, count, byref(written))\nassert count == written.value\ndescs = []\nfor pointer in array:\n descs.append(EventDescriptio... | <|body_start_0|>
count = c_int()
self._call('GetEventCount', byref(count))
return count.value
<|end_body_0|>
<|body_start_1|>
count = self.event_count
array = (c_void_p * count)()
written = c_int()
self._call('GetEventList', array, count, byref(written))
... | FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks. | Bank | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bank:
"""FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks."""
def event_count(self):
"""The number of eve... | stack_v2_sparse_classes_36k_train_017876 | 1,179 | permissive | [
{
"docstring": "The number of event descriptions in the bank.",
"name": "event_count",
"signature": "def event_count(self)"
},
{
"docstring": "The event descriptions in the bank.",
"name": "events",
"signature": "def events(self)"
}
] | 2 | null | Implement the Python class `Bank` described below.
Class description:
FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks.
Method signatures a... | Implement the Python class `Bank` described below.
Class description:
FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks.
Method signatures a... | 68277e40e2cf47f63944ab8acafb92ab50c451bd | <|skeleton|>
class Bank:
"""FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks."""
def event_count(self):
"""The number of eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bank:
"""FMOD Studio banks contain the metadata and audio sample data required for runtime mixing and playback. Audio sample data may be packed into the same bank as the events which reference it, or it may be packed into separate banks."""
def event_count(self):
"""The number of event descriptio... | the_stack_v2_python_sparse | pyfmodex/studio/bank.py | tyrylu/pyfmodex | train | 29 |
1754f5acdf34df7b0963316bcc2a7a2d44538469 | [
"super().__init__()\nself.version = version\nself.tclass = tclass\nself.flabel = flabel\nself.length = length\nself.next_header = next_header\nself.hop_limit = hop_limit\nself.source = IPv6Address(source)\nself.destination = IPv6Address(destination)\nself.data = data",
"self.length = len(self.data)\n_version_tcla... | <|body_start_0|>
super().__init__()
self.version = version
self.tclass = tclass
self.flabel = flabel
self.length = length
self.next_header = next_header
self.hop_limit = hop_limit
self.source = IPv6Address(source)
self.destination = IPv6Address(des... | IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will take into account the values in ... | IPv6 | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPv6:
"""IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will ... | stack_v2_sparse_classes_36k_train_017877 | 27,921 | permissive | [
{
"docstring": "Create an IPv6 with the parameters below. Args: version (int): IP protocol version. Defaults to 6. tclass (int): DS (6 bits) + ECN (2 bits). Default is 0. flabel (int): Flow label. Defaults to 0. length (int): Payload length in bytes. Defaults to 0. next_header (int): Type of next header or prot... | 3 | null | Implement the Python class `IPv6` described below.
Class description:
IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class a... | Implement the Python class `IPv6` described below.
Class description:
IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class a... | 89940bed83f8e792f5ed5c9f12346016cd380d6f | <|skeleton|>
class IPv6:
"""IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IPv6:
"""IPv6 packet "struct". Contains all fields of an IP version 6 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will take into acc... | the_stack_v2_python_sparse | pyof/foundation/network_types.py | kytos/python-openflow | train | 53 |
e4a057e1eacae4d27726ef3749e9b477336a5575 | [
"pre = dummy = ListNode('#')\ndummy.next = head\nnode = head\nwhile node and node.next:\n val = node.val\n while node.next.val == val:\n node = node.next\n pre.next = None\n node = node.next\n if pre.next != None:\n pre = pre.next\n pre.next = node\nreturn dummy.next",
"if head... | <|body_start_0|>
pre = dummy = ListNode('#')
dummy.next = head
node = head
while node and node.next:
val = node.val
while node.next.val == val:
node = node.next
pre.next = None
node = node.next
if pre.next !=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = dummy = ListNode('#'... | stack_v2_sparse_classes_36k_train_017878 | 1,262 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates2",
"signature": "def deleteDuplicates2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006956 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 0fc972e5cd2baf1b5ddf8b192962629f40bc3bf4 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
pre = dummy = ListNode('#')
dummy.next = head
node = head
while node and node.next:
val = node.val
while node.next.val == val:
node = node.nex... | the_stack_v2_python_sparse | Linked List/82. Remove Duplicates from Sorted List II.py | yukiii-zhong/Leetcode | train | 2 | |
1864b588badddf2659aa28b2bb8d5ddd182e95cb | [
"parser = MagicCommandParser(prog='snap', description='insert a snap window inside a notebook')\nparser.add_argument('-f', '--file', type=str, default='', help='scratch or snap file to display')\nparser.add_argument('-d', '--div', type=str, default='scratch_div_id', help='id for the HTML div')\nparser.add_argument(... | <|body_start_0|>
parser = MagicCommandParser(prog='snap', description='insert a snap window inside a notebook')
parser.add_argument('-f', '--file', type=str, default='', help='scratch or snap file to display')
parser.add_argument('-d', '--div', type=str, default='scratch_div_id', help='id for th... | Defines magic commands to list the content of a folder .. versionadded:: 1.1 | MagicScratch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicScratch:
"""Defines magic commands to list the content of a folder .. versionadded:: 1.1"""
def snap_parser():
"""defines the way to parse the magic command ``%snap``"""
<|body_0|>
def snap(self, line):
"""Defines ``%snap`` which inserts a :epkg:`snap` windo... | stack_v2_sparse_classes_36k_train_017879 | 2,129 | permissive | [
{
"docstring": "defines the way to parse the magic command ``%snap``",
"name": "snap_parser",
"signature": "def snap_parser()"
},
{
"docstring": "Defines ``%snap`` which inserts a :epkg:`snap` window inside a notebook.",
"name": "snap",
"signature": "def snap(self, line)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005984 | Implement the Python class `MagicScratch` described below.
Class description:
Defines magic commands to list the content of a folder .. versionadded:: 1.1
Method signatures and docstrings:
- def snap_parser(): defines the way to parse the magic command ``%snap``
- def snap(self, line): Defines ``%snap`` which inserts... | Implement the Python class `MagicScratch` described below.
Class description:
Defines magic commands to list the content of a folder .. versionadded:: 1.1
Method signatures and docstrings:
- def snap_parser(): defines the way to parse the magic command ``%snap``
- def snap(self, line): Defines ``%snap`` which inserts... | e39f8ae416c23940c1a227c11c667c19104b2ff4 | <|skeleton|>
class MagicScratch:
"""Defines magic commands to list the content of a folder .. versionadded:: 1.1"""
def snap_parser():
"""defines the way to parse the magic command ``%snap``"""
<|body_0|>
def snap(self, line):
"""Defines ``%snap`` which inserts a :epkg:`snap` windo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagicScratch:
"""Defines magic commands to list the content of a folder .. versionadded:: 1.1"""
def snap_parser():
"""defines the way to parse the magic command ``%snap``"""
parser = MagicCommandParser(prog='snap', description='insert a snap window inside a notebook')
parser.add_... | the_stack_v2_python_sparse | src/code_beatrix/ipythonhelper/magic_scratch.py | sdpython/code_beatrix | train | 1 |
c9b26b95d1890e17806162f3c42619bfc8f4636c | [
"header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))\nheader('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))\nheader('Access-Control-Allow-Methods', '*')\nheader('Access-Control-Allow-Credentials', 'true')\nheader('Access-Control-Expose-Headers', 'X-Rucio-Auth-Token... | <|body_start_0|>
header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
header('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))
header('Access-Control-Allow-Methods', '*')
header('Access-Control-Allow-Credentials', 'true')
header('Acc... | Validate a Rucio Auth Token. | Validate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validate:
"""Validate a Rucio Auth Token."""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
<|body_0|>
def GET(self):
"""HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Auth-Token: as a variab... | stack_v2_sparse_classes_36k_train_017880 | 18,732 | permissive | [
{
"docstring": "HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.",
"name": "OPTIONS",
"signature": "def OPTIONS(self)"
},
{
"docstring": "HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Auth-Token: as a variable-length string. :returns: Tuple(account n... | 2 | null | Implement the Python class `Validate` described below.
Class description:
Validate a Rucio Auth Token.
Method signatures and docstrings:
- def OPTIONS(self): HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.
- def GET(self): HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Au... | Implement the Python class `Validate` described below.
Class description:
Validate a Rucio Auth Token.
Method signatures and docstrings:
- def OPTIONS(self): HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.
- def GET(self): HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Au... | 355a997a5ea213c427a5d841ab151ceb01073eb4 | <|skeleton|>
class Validate:
"""Validate a Rucio Auth Token."""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
<|body_0|>
def GET(self):
"""HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Auth-Token: as a variab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Validate:
"""Validate a Rucio Auth Token."""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
header('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CON... | the_stack_v2_python_sparse | lib/rucio/web/rest/webpy/v1/authentication.py | pujanm/rucio | train | 1 |
a90b03fe212378f95373e2cdd081680bd4d16050 | [
"super().__init__()\n\ndef discriminator_block(in_filters, out_filters, normalize=True):\n \"\"\"Returns downsampling layers of each discriminator block\"\"\"\n layers = [torch.nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]\n if normalize:\n layers.append(torch.nn.InstanceNorm2d(out_fil... | <|body_start_0|>
super().__init__()
def discriminator_block(in_filters, out_filters, normalize=True):
"""Returns downsampling layers of each discriminator block"""
layers = [torch.nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]
if normalize:
... | A discriminator operating on multiple Paths each with a different resolution | MultiResolutionDiscriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiResolutionDiscriminator:
"""A discriminator operating on multiple Paths each with a different resolution"""
def __init__(self, in_channels=3, num_paths=3):
"""Parameters ---------- in_channels : int number of channels per input image num_paths : int number of parallel discrimina... | stack_v2_sparse_classes_36k_train_017881 | 16,260 | permissive | [
{
"docstring": "Parameters ---------- in_channels : int number of channels per input image num_paths : int number of parallel discriminator paths (each with lower resolution than the ones before)",
"name": "__init__",
"signature": "def __init__(self, in_channels=3, num_paths=3)"
},
{
"docstring"... | 2 | null | Implement the Python class `MultiResolutionDiscriminator` described below.
Class description:
A discriminator operating on multiple Paths each with a different resolution
Method signatures and docstrings:
- def __init__(self, in_channels=3, num_paths=3): Parameters ---------- in_channels : int number of channels per ... | Implement the Python class `MultiResolutionDiscriminator` described below.
Class description:
A discriminator operating on multiple Paths each with a different resolution
Method signatures and docstrings:
- def __init__(self, in_channels=3, num_paths=3): Parameters ---------- in_channels : int number of channels per ... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class MultiResolutionDiscriminator:
"""A discriminator operating on multiple Paths each with a different resolution"""
def __init__(self, in_channels=3, num_paths=3):
"""Parameters ---------- in_channels : int number of channels per input image num_paths : int number of parallel discrimina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiResolutionDiscriminator:
"""A discriminator operating on multiple Paths each with a different resolution"""
def __init__(self, in_channels=3, num_paths=3):
"""Parameters ---------- in_channels : int number of channels per input image num_paths : int number of parallel discriminator paths (ea... | the_stack_v2_python_sparse | dlutils/models/gans/munit/models.py | justusschock/dl-utils | train | 15 |
b584176e6215690f66c6b7855024688721ffeb8e | [
"self.ReportServiceStatus(win32service.SERVICE_START_PENDING)\nself.httpd = self.trac_init()\nself.ReportServiceStatus(win32service.SERVICE_RUNNING)\ntry:\n self.httpd.serve_forever()\nexcept OSError:\n sys.exit(1)",
"self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\nif self.httpd:\n self.http... | <|body_start_0|>
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
self.httpd = self.trac_init()
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
try:
self.httpd.serve_forever()
except OSError:
sys.exit(1)
<|end_body_0|>
<|body_start_1|>
... | Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation at the end of this module or navigate to the directory where this module is located ... | TracWindowsService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TracWindowsService:
"""Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation at the end of this module or navigate ... | stack_v2_sparse_classes_36k_train_017882 | 5,370 | no_license | [
{
"docstring": "Called when the Windows Service runs.",
"name": "SvcDoRun",
"signature": "def SvcDoRun(self)"
},
{
"docstring": "Called when Windows receives a service stop request.",
"name": "SvcStop",
"signature": "def SvcStop(self)"
},
{
"docstring": "Checks for the required d... | 3 | null | Implement the Python class `TracWindowsService` described below.
Class description:
Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation... | Implement the Python class `TracWindowsService` described below.
Class description:
Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation... | 4fcd4aeba81d734654f5d9ec524218b91d54a0e1 | <|skeleton|>
class TracWindowsService:
"""Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation at the end of this module or navigate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TracWindowsService:
"""Trac Windows Service helper class. The TracWindowsService class contains all the functionality required for running Trac application as a Windows Service. For information on installing the application, please refer to the documentation at the end of this module or navigate to the direct... | the_stack_v2_python_sparse | windowsservicescript/tracservice.py | woochica/trachacks | train | 0 |
94710249488a5812d482b5085e0ec44941cee055 | [
"super(L2TTlnTest, self).setUp()\nself._output = io.BytesIO()\nself._formatter = l2t_tln.L2tTlnOutputFormatter(None, self._formatter_mediator, filehandle=self._output)\nself._event_object = TlnTestEvent()",
"expected_header = b'Time|Source|Host|User|Description|TZ|Notes\\n'\nself._formatter.WriteHeader()\nheader ... | <|body_start_0|>
super(L2TTlnTest, self).setUp()
self._output = io.BytesIO()
self._formatter = l2t_tln.L2tTlnOutputFormatter(None, self._formatter_mediator, filehandle=self._output)
self._event_object = TlnTestEvent()
<|end_body_0|>
<|body_start_1|>
expected_header = b'Time|Sour... | Tests for the TLN outputter. | L2TTlnTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2TTlnTest:
"""Tests for the TLN outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
<|body_0|>
def testWriteHeader(self):
"""Tests the WriteHeader function."""
<|body_1|>
def testWriteEventBody(self):
"""Tests the ... | stack_v2_sparse_classes_36k_train_017883 | 2,494 | permissive | [
{
"docstring": "Sets up the objects needed for this test.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the WriteHeader function.",
"name": "testWriteHeader",
"signature": "def testWriteHeader(self)"
},
{
"docstring": "Tests the WriteEventBody functio... | 3 | stack_v2_sparse_classes_30k_val_000069 | Implement the Python class `L2TTlnTest` described below.
Class description:
Tests for the TLN outputter.
Method signatures and docstrings:
- def setUp(self): Sets up the objects needed for this test.
- def testWriteHeader(self): Tests the WriteHeader function.
- def testWriteEventBody(self): Tests the WriteEventBody ... | Implement the Python class `L2TTlnTest` described below.
Class description:
Tests for the TLN outputter.
Method signatures and docstrings:
- def setUp(self): Sets up the objects needed for this test.
- def testWriteHeader(self): Tests the WriteHeader function.
- def testWriteEventBody(self): Tests the WriteEventBody ... | 2c504690d589bb9e6203d00d9ad53bfd45b32255 | <|skeleton|>
class L2TTlnTest:
"""Tests for the TLN outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
<|body_0|>
def testWriteHeader(self):
"""Tests the WriteHeader function."""
<|body_1|>
def testWriteEventBody(self):
"""Tests the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L2TTlnTest:
"""Tests for the TLN outputter."""
def setUp(self):
"""Sets up the objects needed for this test."""
super(L2TTlnTest, self).setUp()
self._output = io.BytesIO()
self._formatter = l2t_tln.L2tTlnOutputFormatter(None, self._formatter_mediator, filehandle=self._outp... | the_stack_v2_python_sparse | plaso/output/l2t_tln_test.py | f-s-p/plaso | train | 0 |
30dcd74a1938553d2edf2cebe5da196bcd4ff16f | [
"ObjectManager.__init__(self)\nself.setters.update({'description': 'set_general', 'external_reference': 'set_general', 'facebook_message': 'set_general', 'lag_time': 'set_general', 'lead_time': 'set_general', 'name_prefix': 'set_general', 'notify_cfgs': 'set_many', 'organization': 'set_foreign_key', 'product_line':... | <|body_start_0|>
ObjectManager.__init__(self)
self.setters.update({'description': 'set_general', 'external_reference': 'set_general', 'facebook_message': 'set_general', 'lag_time': 'set_general', 'lead_time': 'set_general', 'name_prefix': 'set_general', 'notify_cfgs': 'set_many', 'organization': 'set_fo... | Manage EventTemplates in the Power Reg system | EventTemplateManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTemplateManager:
"""Manage EventTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name_prefix, title, description, optional_attributes=None):
"""Create a new EventTemplate. @param name_prefix P... | stack_v2_sparse_classes_36k_train_017884 | 3,075 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new EventTemplate. @param name_prefix Prefix that will be used in generating a unique name @param title title of the EventTemplate @param description description of the EventTemplate @... | 2 | stack_v2_sparse_classes_30k_train_003118 | Implement the Python class `EventTemplateManager` described below.
Class description:
Manage EventTemplates in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name_prefix, title, description, optional_attributes=None): Create a new EventTemplate.... | Implement the Python class `EventTemplateManager` described below.
Class description:
Manage EventTemplates in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name_prefix, title, description, optional_attributes=None): Create a new EventTemplate.... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class EventTemplateManager:
"""Manage EventTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name_prefix, title, description, optional_attributes=None):
"""Create a new EventTemplate. @param name_prefix P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventTemplateManager:
"""Manage EventTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.setters.update({'description': 'set_general', 'external_reference': 'set_general', 'facebook_message': 'set_general', 'lag_time': 'set_... | the_stack_v2_python_sparse | pr_services/event_system/event_template_manager.py | ninemoreminutes/openassign-server | train | 0 |
e864bffcad4ce5cf8ab33a706a3beb9ac7a936b0 | [
"q = set([(r, c)])\nP = [[0 for _ in range(N)] for _ in range(N)]\nP[r][c] = 1\nk = 0\nwhile k < K:\n k += 1\n cur_q = set()\n cur_P = [[0 for _ in range(N)] for _ in range(N)]\n for i, j in q:\n for di, dj in dirs:\n I = i + di\n J = j + dj\n if 0 <= I < N and 0 ... | <|body_start_0|>
q = set([(r, c)])
P = [[0 for _ in range(N)] for _ in range(N)]
P[r][c] = 1
k = 0
while k < K:
k += 1
cur_q = set()
cur_P = [[0 for _ in range(N)] for _ in range(N)]
for i, j in q:
for di, dj in dirs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
"""brute force K step with memory, it is considered dp"""
<|body_0|>
def knightProbability_error(self, N: int, K: int, r: int, c: int) -> float:
"""brute force K step"""
<|body_1|... | stack_v2_sparse_classes_36k_train_017885 | 3,087 | no_license | [
{
"docstring": "brute force K step with memory, it is considered dp",
"name": "knightProbability",
"signature": "def knightProbability(self, N: int, K: int, r: int, c: int) -> float"
},
{
"docstring": "brute force K step",
"name": "knightProbability_error",
"signature": "def knightProbab... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability(self, N: int, K: int, r: int, c: int) -> float: brute force K step with memory, it is considered dp
- def knightProbability_error(self, N: int, K: int, r: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightProbability(self, N: int, K: int, r: int, c: int) -> float: brute force K step with memory, it is considered dp
- def knightProbability_error(self, N: int, K: int, r: i... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
"""brute force K step with memory, it is considered dp"""
<|body_0|>
def knightProbability_error(self, N: int, K: int, r: int, c: int) -> float:
"""brute force K step"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
"""brute force K step with memory, it is considered dp"""
q = set([(r, c)])
P = [[0 for _ in range(N)] for _ in range(N)]
P[r][c] = 1
k = 0
while k < K:
k += 1
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/688 Knight Probability in Chessboard.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
15082037857da5ac101a1023b8849f68182fd270 | [
"self.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.data_read_bytes = data_read_bytes\nself.data_written_bytes = data_written_bytes\nself.logical_used_bytes = logical_used_bytes\nself.peak_read_throughput = peak_read_throughput\nself.peak_write_throughput = peak_write_throughpu... | <|body_start_0|>
self.cluster_id = cluster_id
self.cluster_incarnation_id = cluster_incarnation_id
self.data_read_bytes = data_read_bytes
self.data_written_bytes = data_written_bytes
self.logical_used_bytes = logical_used_bytes
self.peak_read_throughput = peak_read_throug... | Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_written_bytes (long|int): Specifies the ... | ViewStatInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_... | stack_v2_sparse_classes_36k_train_017886 | 5,259 | permissive | [
{
"docstring": "Constructor for the ViewStatInfo class",
"name": "__init__",
"signature": "def __init__(self, cluster_id=None, cluster_incarnation_id=None, data_read_bytes=None, data_written_bytes=None, logical_used_bytes=None, peak_read_throughput=None, peak_write_throughput=None, physical_used_bytes=N... | 2 | null | Implement the Python class `ViewStatInfo` described below.
Class description:
Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): ... | Implement the Python class `ViewStatInfo` described below.
Class description:
Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_written_bytes... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_stat_info.py | cohesity/management-sdk-python | train | 24 |
c7c59a3256cab217fe69367aafdb46b451dec57f | [
"if not isinstance(df, pd.DataFrame):\n raise Exception('df is not DataFrame!')\nreturn preprocessing.scale(df)",
"if not isinstance(df, pd.DataFrame):\n raise Exception('df is not DataFrame!')\nreturn preprocessing.minmax_scale(df)",
"if not isinstance(df, pd.DataFrame):\n raise Exception('df is not D... | <|body_start_0|>
if not isinstance(df, pd.DataFrame):
raise Exception('df is not DataFrame!')
return preprocessing.scale(df)
<|end_body_0|>
<|body_start_1|>
if not isinstance(df, pd.DataFrame):
raise Exception('df is not DataFrame!')
return preprocessing.minmax_s... | 数据归一化库类,归一化对DataFrame所有数据 | NormalizationGallery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizationGallery:
"""数据归一化库类,归一化对DataFrame所有数据"""
def scale(df):
"""将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据"""
<|body_0|>
def minMaxScale(df):
"""将数据最大最小化标准化 :param df: 传入DataFrame :returns: 标准化后的数据"""
<|body_1|>
def normalize(df):
... | stack_v2_sparse_classes_36k_train_017887 | 1,883 | no_license | [
{
"docstring": "将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据",
"name": "scale",
"signature": "def scale(df)"
},
{
"docstring": "将数据最大最小化标准化 :param df: 传入DataFrame :returns: 标准化后的数据",
"name": "minMaxScale",
"signature": "def minMaxScale(df)"
},
{
"docstring": "将数据正态分布化 :param d... | 4 | stack_v2_sparse_classes_30k_train_020768 | Implement the Python class `NormalizationGallery` described below.
Class description:
数据归一化库类,归一化对DataFrame所有数据
Method signatures and docstrings:
- def scale(df): 将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据
- def minMaxScale(df): 将数据最大最小化标准化 :param df: 传入DataFrame :returns: 标准化后的数据
- def normalize(df): 将数据正态分布化 :... | Implement the Python class `NormalizationGallery` described below.
Class description:
数据归一化库类,归一化对DataFrame所有数据
Method signatures and docstrings:
- def scale(df): 将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据
- def minMaxScale(df): 将数据最大最小化标准化 :param df: 传入DataFrame :returns: 标准化后的数据
- def normalize(df): 将数据正态分布化 :... | 493ea4b86a03170ff37a29fd9d85ec981235d14f | <|skeleton|>
class NormalizationGallery:
"""数据归一化库类,归一化对DataFrame所有数据"""
def scale(df):
"""将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据"""
<|body_0|>
def minMaxScale(df):
"""将数据最大最小化标准化 :param df: 传入DataFrame :returns: 标准化后的数据"""
<|body_1|>
def normalize(df):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizationGallery:
"""数据归一化库类,归一化对DataFrame所有数据"""
def scale(df):
"""将数据标准化 :param df: 传入DataFrame :returns: 标准化后的数据"""
if not isinstance(df, pd.DataFrame):
raise Exception('df is not DataFrame!')
return preprocessing.scale(df)
def minMaxScale(df):
"""将... | the_stack_v2_python_sparse | first-sklearn/pysrc/normalizationGallery.py | ssh352/WQ-Testcode | train | 0 |
175cf8cc571e1c8cd0a6909539bfbfa724a6a556 | [
"a = 0\nb = 1\nwhile b < len(nums):\n if nums[b] != nums[a]:\n a += 1\n nums[a] = nums[b]\n b += 1\nreturn a + 1",
"a = 0\nb = 1\nwhile b < len(nums):\n if nums[b] == nums[a]:\n b += 1\n else:\n a += 1\n nums[a] = nums[b]\n b += 1\nreturn a + 1",
"a = 0\nb =... | <|body_start_0|>
a = 0
b = 1
while b < len(nums):
if nums[b] != nums[a]:
a += 1
nums[a] = nums[b]
b += 1
return a + 1
<|end_body_0|>
<|body_start_1|>
a = 0
b = 1
while b < len(nums):
if nums[b] =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype:... | stack_v2_sparse_classes_36k_train_017888 | 1,470 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":t... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :typ... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
a = 0
b = 1
while b < len(nums):
if nums[b] != nums[a]:
a += 1
nums[a] = nums[b]
b += 1
return a + 1
def removeDuplicates(sel... | the_stack_v2_python_sparse | 0026_Remove_Duplicates_from_Sorted_Array.py | bingli8802/leetcode | train | 0 | |
f8270a6ea14fb2678ece836387bf92c5d06348a8 | [
"SelectEntity.__init__(self)\nsuper().__init__(data_handler)\nself._home_id = home_id\nself._climate_state_class = f'{CLIMATE_STATE_CLASS_NAME}-{self._home_id}'\nself._climate_state: pyatmo.AsyncClimate = data_handler.data[self._climate_state_class]\nself._home = self._climate_state.homes[self._home_id]\nself._data... | <|body_start_0|>
SelectEntity.__init__(self)
super().__init__(data_handler)
self._home_id = home_id
self._climate_state_class = f'{CLIMATE_STATE_CLASS_NAME}-{self._home_id}'
self._climate_state: pyatmo.AsyncClimate = data_handler.data[self._climate_state_class]
self._home... | Representation a Netatmo thermostat schedule selector. | NetatmoScheduleSelect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetatmoScheduleSelect:
"""Representation a Netatmo thermostat schedule selector."""
def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None:
"""Initialize the select entity."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_36k_train_017889 | 5,649 | permissive | [
{
"docstring": "Initialize the select entity.",
"name": "__init__",
"signature": "def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None"
},
{
"docstring": "Entity created.",
"name": "async_added_to_hass",
"signature": "async def async_added_to_hass(sel... | 5 | stack_v2_sparse_classes_30k_train_004503 | Implement the Python class `NetatmoScheduleSelect` described below.
Class description:
Representation a Netatmo thermostat schedule selector.
Method signatures and docstrings:
- def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None: Initialize the select entity.
- async def async_a... | Implement the Python class `NetatmoScheduleSelect` described below.
Class description:
Representation a Netatmo thermostat schedule selector.
Method signatures and docstrings:
- def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None: Initialize the select entity.
- async def async_a... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class NetatmoScheduleSelect:
"""Representation a Netatmo thermostat schedule selector."""
def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None:
"""Initialize the select entity."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetatmoScheduleSelect:
"""Representation a Netatmo thermostat schedule selector."""
def __init__(self, data_handler: NetatmoDataHandler, home_id: str, options: list) -> None:
"""Initialize the select entity."""
SelectEntity.__init__(self)
super().__init__(data_handler)
sel... | the_stack_v2_python_sparse | homeassistant/components/netatmo/select.py | JeffLIrion/home-assistant | train | 5 |
0730cc568bce59a19b226f681c633781e6f67bce | [
"queue = PriorityQueue()\nsample_item = 5\nqueue.push(Priorities.MEDIUM, sample_item)\nreturned_item = queue.pop()\nself.assertEqual(sample_item, returned_item, 'Not inserting and removing items correctly.')",
"queue = PriorityQueue()\nitems = [1, 2, 3]\npriorities = [Priorities.LOW, Priorities.MEDIUM, Pr... | <|body_start_0|>
queue = PriorityQueue()
sample_item = 5
queue.push(Priorities.MEDIUM, sample_item)
returned_item = queue.pop()
self.assertEqual(sample_item, returned_item, 'Not inserting and removing items correctly.')
<|end_body_0|>
<|body_start_1|>
queue = Pri... | TestPriorityQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPriorityQueue:
def test_insertion(self):
"""Test that items are able to be inserted an removed."""
<|body_0|>
def test_proper_order(self):
"""Test that a mixed-bag of priorities comes out in the right order."""
<|body_1|>
def test_pop_empty_queue(sel... | stack_v2_sparse_classes_36k_train_017890 | 1,631 | no_license | [
{
"docstring": "Test that items are able to be inserted an removed.",
"name": "test_insertion",
"signature": "def test_insertion(self)"
},
{
"docstring": "Test that a mixed-bag of priorities comes out in the right order.",
"name": "test_proper_order",
"signature": "def test_proper_order(... | 4 | stack_v2_sparse_classes_30k_val_000658 | Implement the Python class `TestPriorityQueue` described below.
Class description:
Implement the TestPriorityQueue class.
Method signatures and docstrings:
- def test_insertion(self): Test that items are able to be inserted an removed.
- def test_proper_order(self): Test that a mixed-bag of priorities comes out in th... | Implement the Python class `TestPriorityQueue` described below.
Class description:
Implement the TestPriorityQueue class.
Method signatures and docstrings:
- def test_insertion(self): Test that items are able to be inserted an removed.
- def test_proper_order(self): Test that a mixed-bag of priorities comes out in th... | 6228d8a4f0396b422b2803f24873070ea5c8b4e1 | <|skeleton|>
class TestPriorityQueue:
def test_insertion(self):
"""Test that items are able to be inserted an removed."""
<|body_0|>
def test_proper_order(self):
"""Test that a mixed-bag of priorities comes out in the right order."""
<|body_1|>
def test_pop_empty_queue(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPriorityQueue:
def test_insertion(self):
"""Test that items are able to be inserted an removed."""
queue = PriorityQueue()
sample_item = 5
queue.push(Priorities.MEDIUM, sample_item)
returned_item = queue.pop()
self.assertEqual(sample_item, returned_item, 'No... | the_stack_v2_python_sparse | unit_tests/priority_queue_test.py | MissouriMRR/IARC-2019 | train | 6 | |
bf95d91ee1f90a2835f47c7633abe3e5bc4f60d2 | [
"Editeur.__init__(self, pere, objet, attribut)\nself.ajouter_option('c', self.opt_creer_chambre)\nself.ajouter_option('d', self.opt_supprimer_chambre)",
"auberge = self.objet\nmsg = '| |tit|' + \"Édition des chambres de l'auberge {}\".format(auberge.cle).ljust(76)\nmsg += '|ff||\\n' + self.opts.separateur + '\\n'... | <|body_start_0|>
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('c', self.opt_creer_chambre)
self.ajouter_option('d', self.opt_supprimer_chambre)
<|end_body_0|>
<|body_start_1|>
auberge = self.objet
msg = '| |tit|' + "Édition des chambres de l'auberge {}".form... | Contexte-éditeur des chambres d'une auberge. | EdtChambres | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdtChambres:
"""Contexte-éditeur des chambres d'une auberge."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def accueil(self):
"""Message d'accueil du contexte"""
<|body_1|>
def opt_creer_chambre(se... | stack_v2_sparse_classes_36k_train_017891 | 5,517 | permissive | [
{
"docstring": "Constructeur de l'éditeur",
"name": "__init__",
"signature": "def __init__(self, pere, objet=None, attribut=None)"
},
{
"docstring": "Message d'accueil du contexte",
"name": "accueil",
"signature": "def accueil(self)"
},
{
"docstring": "Ajoute une chambre. Syntaxe... | 5 | null | Implement the Python class `EdtChambres` described below.
Class description:
Contexte-éditeur des chambres d'une auberge.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def accueil(self): Message d'accueil du contexte
- def opt_creer_chambre(self, ... | Implement the Python class `EdtChambres` described below.
Class description:
Contexte-éditeur des chambres d'une auberge.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def accueil(self): Message d'accueil du contexte
- def opt_creer_chambre(self, ... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class EdtChambres:
"""Contexte-éditeur des chambres d'une auberge."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def accueil(self):
"""Message d'accueil du contexte"""
<|body_1|>
def opt_creer_chambre(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdtChambres:
"""Contexte-éditeur des chambres d'une auberge."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('c', self.opt_creer_chambre)
self.ajouter_option('d', self... | the_stack_v2_python_sparse | src/secondaires/auberge/editeurs/aubedit/edt_chambres.py | vincent-lg/tsunami | train | 5 |
0d1c887a8fd12b8f64849a937e33c746faa9b10a | [
"super().__init__(cv)\nself.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='orange')\nself.x = x\nself.pps = pps\nself.colors = colors\nself._tospawn = 0",
"super().update(dt)\nself._tospawn += self.pps * dt\ncolor = self.colors[int(self.age / 3) % len(self.colors)]\nfor i in range(int(self._tospa... | <|body_start_0|>
super().__init__(cv)
self.cid = cv.create_polygon(x - 12, 530, x + 12, 530, x, 500, fill='orange')
self.x = x
self.pps = pps
self.colors = colors
self._tospawn = 0
<|end_body_0|>
<|body_start_1|>
super().update(dt)
self._tospawn += self.p... | A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn. | Volcano | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""... | stack_v2_sparse_classes_36k_train_017892 | 17,823 | no_license | [
{
"docstring": "Init Volcano objects. Args: cv (Tk.canvas): the canvas in which the particle is drawn. x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.",
"name": "__init__",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_010739 | Implement the Python class `Volcano` described below.
Class description:
A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.
Method signatures a... | Implement the Python class `Volcano` described below.
Class description:
A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn.
Method signatures a... | 5e51c57c17ee8c233a0fe63f32942e80549040fd | <|skeleton|>
class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Volcano:
"""A volcano that continuously emits colored particles. Attributes: x (float): x-coordinate of the volcano. pps (float): the number of particles to spawn per second. colors (list of string): the colors of the particles to spawn."""
def __init__(self, cv, x, pps, colors):
"""Init Volcano ... | the_stack_v2_python_sparse | semester_one/infoI/sheet10/fireworks.py | fkarg/uni-stuff | train | 0 |
ae646cba6ce2f88c719c62c6020ebca6ee3af95f | [
"super().__init__()\nself.resize(400, 400)\nself.setWindowTitle('Progress')\nself.createProgressWidget()\nprogressDialogLayout = QVBoxLayout()\nprogressDialogLayout.addWidget(self.progressWidget)\nself.setLayout(progressDialogLayout)",
"self.progressWidget = QWidget()\nself.progressText = QTextBrowser()\nself.pro... | <|body_start_0|>
super().__init__()
self.resize(400, 400)
self.setWindowTitle('Progress')
self.createProgressWidget()
progressDialogLayout = QVBoxLayout()
progressDialogLayout.addWidget(self.progressWidget)
self.setLayout(progressDialogLayout)
<|end_body_0|>
<|bo... | Dialog Show the progress of the computation of the model by the Engine printing the statuses. | Progress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Progress:
"""Dialog Show the progress of the computation of the model by the Engine printing the statuses."""
def __init__(self):
"""Instantiate the dimensions of the dialog and the widget inside it whit its layout."""
<|body_0|>
def createProgressWidget(self):
"... | stack_v2_sparse_classes_36k_train_017893 | 49,456 | no_license | [
{
"docstring": "Instantiate the dimensions of the dialog and the widget inside it whit its layout.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create the widget of the progress statuses and its layout.",
"name": "createProgressWidget",
"signature": "def cre... | 2 | stack_v2_sparse_classes_30k_train_009343 | Implement the Python class `Progress` described below.
Class description:
Dialog Show the progress of the computation of the model by the Engine printing the statuses.
Method signatures and docstrings:
- def __init__(self): Instantiate the dimensions of the dialog and the widget inside it whit its layout.
- def creat... | Implement the Python class `Progress` described below.
Class description:
Dialog Show the progress of the computation of the model by the Engine printing the statuses.
Method signatures and docstrings:
- def __init__(self): Instantiate the dimensions of the dialog and the widget inside it whit its layout.
- def creat... | c0549695e9ee41842e6af0d9c6b3f75b75338eb7 | <|skeleton|>
class Progress:
"""Dialog Show the progress of the computation of the model by the Engine printing the statuses."""
def __init__(self):
"""Instantiate the dimensions of the dialog and the widget inside it whit its layout."""
<|body_0|>
def createProgressWidget(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Progress:
"""Dialog Show the progress of the computation of the model by the Engine printing the statuses."""
def __init__(self):
"""Instantiate the dimensions of the dialog and the widget inside it whit its layout."""
super().__init__()
self.resize(400, 400)
self.setWindo... | the_stack_v2_python_sparse | src/classes/GUI.py | mnarizzano/se20-project-16 | train | 0 |
ec77e5f2083daba0c58efe8a6e8f2644aeabb214 | [
"super().__init__(name)\nself.__name__ = name\nself.gen = gen",
"rval = []\nfor tup, param in zip(tups, params):\n if not isinstance(tup, AbstractTuple):\n raise MyiaTypeError(f'Expected AbstractTuple, not {tup}')\n rval.append([g.apply(P.tuple_getitem, param, i) for i, elem in enumerate(tup.elements... | <|body_start_0|>
super().__init__(name)
self.__name__ = name
self.gen = gen
<|end_body_0|>
<|body_start_1|>
rval = []
for tup, param in zip(tups, params):
if not isinstance(tup, AbstractTuple):
raise MyiaTypeError(f'Expected AbstractTuple, not {tup}')... | Parametrizable MetaGraph to combine or extract tuples. | TupleReorganizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
<|body_0|>
def map_tuples(self, g, params, tups):
"""Map each element of each tuple to a getitem on the parameter.""... | stack_v2_sparse_classes_36k_train_017894 | 2,705 | permissive | [
{
"docstring": "Initialize a TupleReorganizer.",
"name": "__init__",
"signature": "def __init__(self, name, gen)"
},
{
"docstring": "Map each element of each tuple to a getitem on the parameter.",
"name": "map_tuples",
"signature": "def map_tuples(self, g, params, tups)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_000856 | Implement the Python class `TupleReorganizer` described below.
Class description:
Parametrizable MetaGraph to combine or extract tuples.
Method signatures and docstrings:
- def __init__(self, name, gen): Initialize a TupleReorganizer.
- def map_tuples(self, g, params, tups): Map each element of each tuple to a getite... | Implement the Python class `TupleReorganizer` described below.
Class description:
Parametrizable MetaGraph to combine or extract tuples.
Method signatures and docstrings:
- def __init__(self, name, gen): Initialize a TupleReorganizer.
- def map_tuples(self, g, params, tups): Map each element of each tuple to a getite... | d7b12c15453079e1a2c4fdae611c5f741574363d | <|skeleton|>
class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
<|body_0|>
def map_tuples(self, g, params, tups):
"""Map each element of each tuple to a getitem on the parameter.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
super().__init__(name)
self.__name__ = name
self.gen = gen
def map_tuples(self, g, params, tups):
"""Map each ele... | the_stack_v2_python_sparse | myia/operations/ops_tuple.py | breuleux/myia | train | 1 |
946dc54231e6c560fde952e1fbd64907e1da3f72 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['rental_pri... | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = self.product_code
output_dict['description'] = self.d... | ElectricAppliances class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_017895 | 1,089 | no_license | [
{
"docstring": ":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": ":return:",
"name"... | 2 | stack_v2_sparse_classes_30k_train_021423 | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): :param product_code: :param description: :param market_price: :param rental_price:... | Implement the Python class `ElectricAppliances` described below.
Class description:
ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): :param product_code: :param description: :param market_price: :param rental_price:... | 6ffd7b4ab8346076d3b6cc02ca1ebca3bf028697 | <|skeleton|>
class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
""":param product_code: :param description: :param market_price: :param rental_price: :param brand: :param voltage:"""
Inventory.__init__(self, pro... | the_stack_v2_python_sparse | students/jsward/lesson01/assignment/inventory_management/electric_appliances.py | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | train | 4 |
87352b43014573f1d752b529665636c623b15d04 | [
"sixteen = {'MIPS16', 'MIPSFPU', 'MIPSFPU16'}\nthirtytwo = {'I386', 'R3000BE', 'R3000', 'WCEMIPSV2', 'ALPHAOLD', 'ALPHA', 'SH3', 'SH3DSP', 'SH3E', 'SH4', 'SH5', 'ARM', 'THUMB', 'ARM2', 'AM33', 'POWERPC', 'POWERPCFP', 'TRICORE', 'CEF', 'M32R'}\nsixtyfour = {'I860', 'R4000', 'R10000', 'IA64', 'ALPHA64', 'AMD64', 'ARM... | <|body_start_0|>
sixteen = {'MIPS16', 'MIPSFPU', 'MIPSFPU16'}
thirtytwo = {'I386', 'R3000BE', 'R3000', 'WCEMIPSV2', 'ALPHAOLD', 'ALPHA', 'SH3', 'SH3DSP', 'SH3E', 'SH4', 'SH5', 'ARM', 'THUMB', 'ARM2', 'AM33', 'POWERPC', 'POWERPCFP', 'TRICORE', 'CEF', 'M32R'}
sixtyfour = {'I860', 'R4000', 'R10000'... | IMAGE_FILE_HEADER.Machine | IMAGE_FILE_MACHINE_ | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IMAGE_FILE_MACHINE_:
"""IMAGE_FILE_HEADER.Machine"""
def Architecture(self):
"""Return the word size for the stored machine type."""
<|body_0|>
def Order(self):
"""Return the byteorder (endianness) for the stored machine type."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_017896 | 11,460 | permissive | [
{
"docstring": "Return the word size for the stored machine type.",
"name": "Architecture",
"signature": "def Architecture(self)"
},
{
"docstring": "Return the byteorder (endianness) for the stored machine type.",
"name": "Order",
"signature": "def Order(self)"
}
] | 2 | null | Implement the Python class `IMAGE_FILE_MACHINE_` described below.
Class description:
IMAGE_FILE_HEADER.Machine
Method signatures and docstrings:
- def Architecture(self): Return the word size for the stored machine type.
- def Order(self): Return the byteorder (endianness) for the stored machine type. | Implement the Python class `IMAGE_FILE_MACHINE_` described below.
Class description:
IMAGE_FILE_HEADER.Machine
Method signatures and docstrings:
- def Architecture(self): Return the word size for the stored machine type.
- def Order(self): Return the byteorder (endianness) for the stored machine type.
<|skeleton|>
c... | e02b014dc764ed822288210248c9438a843af8a9 | <|skeleton|>
class IMAGE_FILE_MACHINE_:
"""IMAGE_FILE_HEADER.Machine"""
def Architecture(self):
"""Return the word size for the stored machine type."""
<|body_0|>
def Order(self):
"""Return the byteorder (endianness) for the stored machine type."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IMAGE_FILE_MACHINE_:
"""IMAGE_FILE_HEADER.Machine"""
def Architecture(self):
"""Return the word size for the stored machine type."""
sixteen = {'MIPS16', 'MIPSFPU', 'MIPSFPU16'}
thirtytwo = {'I386', 'R3000BE', 'R3000', 'WCEMIPSV2', 'ALPHAOLD', 'ALPHA', 'SH3', 'SH3DSP', 'SH3E', 'SH... | the_stack_v2_python_sparse | lib/pecoff/headers.py | arizvisa/syringe | train | 36 |
389ecba9ae43e88b6069e5549751adcf6ca1f7f6 | [
"fake_parser = commandline.ArgumentParser()\nfake_subparser = fake_parser.add_subparsers()\nimage_parser = fake_subparser.add_parser('image')\ncros_image.ImageCommand.AddParser(image_parser)\noptions = fake_parser.parse_args(['image'])\ninstance = options.command_class(options)\nself.assertEqual(instance.options.ad... | <|body_start_0|>
fake_parser = commandline.ArgumentParser()
fake_subparser = fake_parser.add_subparsers()
image_parser = fake_subparser.add_parser('image')
cros_image.ImageCommand.AddParser(image_parser)
options = fake_parser.parse_args(['image'])
instance = options.comma... | Test class for our ImageCommand's parser. | ImageCommandParserTest | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCommandParserTest:
"""Test class for our ImageCommand's parser."""
def testParserDefaults(self):
"""Tests that the parser's default values are correct."""
<|body_0|>
def testParserSetValues(self):
"""Tests that the parser reads in values correctly."""
... | stack_v2_sparse_classes_36k_train_017897 | 13,120 | permissive | [
{
"docstring": "Tests that the parser's default values are correct.",
"name": "testParserDefaults",
"signature": "def testParserDefaults(self)"
},
{
"docstring": "Tests that the parser reads in values correctly.",
"name": "testParserSetValues",
"signature": "def testParserSetValues(self)... | 6 | stack_v2_sparse_classes_30k_train_009824 | Implement the Python class `ImageCommandParserTest` described below.
Class description:
Test class for our ImageCommand's parser.
Method signatures and docstrings:
- def testParserDefaults(self): Tests that the parser's default values are correct.
- def testParserSetValues(self): Tests that the parser reads in values... | Implement the Python class `ImageCommandParserTest` described below.
Class description:
Test class for our ImageCommand's parser.
Method signatures and docstrings:
- def testParserDefaults(self): Tests that the parser's default values are correct.
- def testParserSetValues(self): Tests that the parser reads in values... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class ImageCommandParserTest:
"""Test class for our ImageCommand's parser."""
def testParserDefaults(self):
"""Tests that the parser's default values are correct."""
<|body_0|>
def testParserSetValues(self):
"""Tests that the parser reads in values correctly."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageCommandParserTest:
"""Test class for our ImageCommand's parser."""
def testParserDefaults(self):
"""Tests that the parser's default values are correct."""
fake_parser = commandline.ArgumentParser()
fake_subparser = fake_parser.add_subparsers()
image_parser = fake_subp... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/cros_image_unittest.py | zenoalbisser/chromium | train | 0 |
e14992f978988da0b5fd3dc203a98520110e732f | [
"global SWIFT_SESSION\ntry:\n if not SWIFT_SESSION:\n SWIFT_SESSION = keystone.get_session('swift')\n self.connection = openstack.connection.Connection(session=SWIFT_SESSION, oslo_conf=CONF).object_store\nexcept Exception as exc:\n raise utils.Error(_('Could not connect to the object storage service... | <|body_start_0|>
global SWIFT_SESSION
try:
if not SWIFT_SESSION:
SWIFT_SESSION = keystone.get_session('swift')
self.connection = openstack.connection.Connection(session=SWIFT_SESSION, oslo_conf=CONF).object_store
except Exception as exc:
raise ... | API for communicating with Swift. | SwiftAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwiftAPI:
"""API for communicating with Swift."""
def __init__(self):
"""Constructor for creating a SwiftAPI object. Authentification is loaded from config file."""
<|body_0|>
def create_object(self, object, data, container=None, headers=None):
"""Uploads a given... | stack_v2_sparse_classes_36k_train_017898 | 5,346 | permissive | [
{
"docstring": "Constructor for creating a SwiftAPI object. Authentification is loaded from config file.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Uploads a given string to Swift. :param object: The name of the object in Swift :param data: string data to put in t... | 3 | null | Implement the Python class `SwiftAPI` described below.
Class description:
API for communicating with Swift.
Method signatures and docstrings:
- def __init__(self): Constructor for creating a SwiftAPI object. Authentification is loaded from config file.
- def create_object(self, object, data, container=None, headers=N... | Implement the Python class `SwiftAPI` described below.
Class description:
API for communicating with Swift.
Method signatures and docstrings:
- def __init__(self): Constructor for creating a SwiftAPI object. Authentification is loaded from config file.
- def create_object(self, object, data, container=None, headers=N... | 4a6bdaaf4bdd14ce9dc479cde83176b4c1100f42 | <|skeleton|>
class SwiftAPI:
"""API for communicating with Swift."""
def __init__(self):
"""Constructor for creating a SwiftAPI object. Authentification is loaded from config file."""
<|body_0|>
def create_object(self, object, data, container=None, headers=None):
"""Uploads a given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwiftAPI:
"""API for communicating with Swift."""
def __init__(self):
"""Constructor for creating a SwiftAPI object. Authentification is loaded from config file."""
global SWIFT_SESSION
try:
if not SWIFT_SESSION:
SWIFT_SESSION = keystone.get_session('sw... | the_stack_v2_python_sparse | ironic_inspector/common/swift.py | openstack/ironic-inspector | train | 34 |
4a3d25c7358022048e0f534ec908b5337c91dbe5 | [
"self.config = config\nself.binary = libp2p_node_binary\nself._proc = None",
"config_file = '.acn_config'\nself.config.dump(config_file)\ncmd = [self.binary, config_file]\nif self.config.config[AcnNodeConfig.ACN_LOG_FILE] != '':\n self._proc = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=s... | <|body_start_0|>
self.config = config
self.binary = libp2p_node_binary
self._proc = None
<|end_body_0|>
<|body_start_1|>
config_file = '.acn_config'
self.config.dump(config_file)
cmd = [self.binary, config_file]
if self.config.config[AcnNodeConfig.ACN_LOG_FILE] !... | Deploy an acn node in standalone mode. | AcnNodeStandalone | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcnNodeStandalone:
"""Deploy an acn node in standalone mode."""
def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str):
"""Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p_node_binary: path to libp2p node binary"""
<|bod... | stack_v2_sparse_classes_36k_train_017899 | 12,337 | permissive | [
{
"docstring": "Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p_node_binary: path to libp2p node binary",
"name": "__init__",
"signature": "def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str)"
},
{
"docstring": "Run the node.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_016327 | Implement the Python class `AcnNodeStandalone` described below.
Class description:
Deploy an acn node in standalone mode.
Method signatures and docstrings:
- def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str): Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p... | Implement the Python class `AcnNodeStandalone` described below.
Class description:
Deploy an acn node in standalone mode.
Method signatures and docstrings:
- def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str): Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class AcnNodeStandalone:
"""Deploy an acn node in standalone mode."""
def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str):
"""Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p_node_binary: path to libp2p node binary"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcnNodeStandalone:
"""Deploy an acn node in standalone mode."""
def __init__(self, config: AcnNodeConfig, libp2p_node_binary: str):
"""Initialize a new AcnNodeStandalone object. :param config: node's configuration :param libp2p_node_binary: path to libp2p node binary"""
self.config = conf... | the_stack_v2_python_sparse | scripts/acn/run_acn_node_standalone.py | fetchai/agents-aea | train | 192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.