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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2132f693cd3d9057d4094bcc1b5431be37171a0e | [
"with CommandGroup(self, '', 'superbench.cli._handler#{}') as g:\n g.command('version', 'version_command_handler')\n g.command('deploy', 'deploy_command_handler')\n g.command('exec', 'exec_command_handler')\n g.command('run', 'run_command_handler')\nreturn super().load_command_table(args)",
"with Argu... | <|body_start_0|>
with CommandGroup(self, '', 'superbench.cli._handler#{}') as g:
g.command('version', 'version_command_handler')
g.command('deploy', 'deploy_command_handler')
g.command('exec', 'exec_command_handler')
g.command('run', 'run_command_handler')
... | SuperBench CLI commands loader. | SuperBenchCommandsLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
... | stack_v2_sparse_classes_36k_train_030600 | 2,668 | permissive | [
{
"docstring": "Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table.",
"name": "load_command_table",
"signature": "def load_command_table(self, args)"
},
{
"docstring": "Load argu... | 2 | stack_v2_sparse_classes_30k_train_004256 | Implement the Python class `SuperBenchCommandsLoader` described below.
Class description:
SuperBench CLI commands loader.
Method signatures and docstrings:
- def load_command_table(self, args): Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.Order... | Implement the Python class `SuperBenchCommandsLoader` described below.
Class description:
SuperBench CLI commands loader.
Method signatures and docstrings:
- def load_command_table(self, args): Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.Order... | 43620c3f46701d11514901e5c238d7a571ab3ea9 | <|skeleton|>
class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperBenchCommandsLoader:
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table. Args: args (list): List of arguments from the command line. Returns: collections.OrderedDict: Load commands into the command table."""
with CommandG... | the_stack_v2_python_sparse | superbench/cli/_commands.py | QPC-database/superbenchmark | train | 1 |
2662eab3094ce1b4b0db9369edac940ffe9ada52 | [
"self.wrapped_exc = exception\nself.status_int = self.wrapped_exc.status_int\nself._body_function = body_function or _default_body_function",
"fault_data, metadata = self._body_function(self.wrapped_exc)\ncontent_type = req.best_match_content_type()\nserializer = {'application/json': JSONDictSerializer()}[content... | <|body_start_0|>
self.wrapped_exc = exception
self.status_int = self.wrapped_exc.status_int
self._body_function = body_function or _default_body_function
<|end_body_0|>
<|body_start_1|>
fault_data, metadata = self._body_function(self.wrapped_exc)
content_type = req.best_match_co... | Generates an HTTP response from a webob HTTP exception. | Fault | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
<|body_0|>
def __call__(self, req):
"""Generate a WSGI response based on the exception... | stack_v2_sparse_classes_36k_train_030601 | 29,625 | permissive | [
{
"docstring": "Creates a Fault for the given webob.exc.exception.",
"name": "__init__",
"signature": "def __init__(self, exception, body_function=None)"
},
{
"docstring": "Generate a WSGI response based on the exception passed to ctor.",
"name": "__call__",
"signature": "def __call__(se... | 2 | stack_v2_sparse_classes_30k_train_019814 | Implement the Python class `Fault` described below.
Class description:
Generates an HTTP response from a webob HTTP exception.
Method signatures and docstrings:
- def __init__(self, exception, body_function=None): Creates a Fault for the given webob.exc.exception.
- def __call__(self, req): Generate a WSGI response b... | Implement the Python class `Fault` described below.
Class description:
Generates an HTTP response from a webob HTTP exception.
Method signatures and docstrings:
- def __init__(self, exception, body_function=None): Creates a Fault for the given webob.exc.exception.
- def __call__(self, req): Generate a WSGI response b... | dde31aae392b80341f6440eb38db1583563d7d1f | <|skeleton|>
class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
<|body_0|>
def __call__(self, req):
"""Generate a WSGI response based on the exception... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
self.wrapped_exc = exception
self.status_int = self.wrapped_exc.status_int
self._body_function =... | the_stack_v2_python_sparse | neutron/wsgi.py | openstack/neutron | train | 1,174 |
e9c32f36a1365b4dfbe8c593f8d51cfe54fcedf0 | [
"if widget.currentIndex() == -1:\n return None\nelse:\n return widget.itemText(widget.currentIndex())",
"idx = widget.findText(value)\nif idx == -1:\n if value is not None:\n raise ValueError(\"Cannot find text '{0}' in combo box\".format(value))\nwidget.setCurrentIndex(idx)"
] | <|body_start_0|>
if widget.currentIndex() == -1:
return None
else:
return widget.itemText(widget.currentIndex())
<|end_body_0|>
<|body_start_1|>
idx = widget.findText(value)
if idx == -1:
if value is not None:
raise ValueError("Cannot ... | Wrapper around the text in QComboBox. | CurrentComboTextProperty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrentComboTextProperty:
"""Wrapper around the text in QComboBox."""
def getter(self, widget):
"""Return the itemData stored in the currently-selected item"""
<|body_0|>
def setter(self, widget, value):
"""Update the currently selected item to the one which stor... | stack_v2_sparse_classes_36k_train_030602 | 8,602 | permissive | [
{
"docstring": "Return the itemData stored in the currently-selected item",
"name": "getter",
"signature": "def getter(self, widget)"
},
{
"docstring": "Update the currently selected item to the one which stores value in its itemData",
"name": "setter",
"signature": "def setter(self, wid... | 2 | null | Implement the Python class `CurrentComboTextProperty` described below.
Class description:
Wrapper around the text in QComboBox.
Method signatures and docstrings:
- def getter(self, widget): Return the itemData stored in the currently-selected item
- def setter(self, widget, value): Update the currently selected item ... | Implement the Python class `CurrentComboTextProperty` described below.
Class description:
Wrapper around the text in QComboBox.
Method signatures and docstrings:
- def getter(self, widget): Return the itemData stored in the currently-selected item
- def setter(self, widget, value): Update the currently selected item ... | 4aa8c64a6f65629207e40df9963232473a24c9f6 | <|skeleton|>
class CurrentComboTextProperty:
"""Wrapper around the text in QComboBox."""
def getter(self, widget):
"""Return the itemData stored in the currently-selected item"""
<|body_0|>
def setter(self, widget, value):
"""Update the currently selected item to the one which stor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrentComboTextProperty:
"""Wrapper around the text in QComboBox."""
def getter(self, widget):
"""Return the itemData stored in the currently-selected item"""
if widget.currentIndex() == -1:
return None
else:
return widget.itemText(widget.currentIndex())
... | the_stack_v2_python_sparse | glue/utils/qt/widget_properties.py | astrofrog/glue | train | 3 |
0e0e74307e8a63090893e1c80f9f9cd77eb1a9f9 | [
"self.default_branch_setting_func = kwargs.pop('branch_setting_func', lambda: ModuleStoreEnum.Branch.published_only)\nsuper().__init__(*args, **kwargs)\nself.thread_cache = threading.local()",
"previous_thread_branch_setting = getattr(self.thread_cache, 'branch_setting', None)\ntry:\n self.thread_cache.branch_... | <|body_start_0|>
self.default_branch_setting_func = kwargs.pop('branch_setting_func', lambda: ModuleStoreEnum.Branch.published_only)
super().__init__(*args, **kwargs)
self.thread_cache = threading.local()
<|end_body_0|>
<|body_start_1|>
previous_thread_branch_setting = getattr(self.thre... | A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init method 3. the default branch setting being Module... | BranchSettingMixin | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init met... | stack_v2_sparse_classes_36k_train_030603 | 8,397 | permissive | [
{
"docstring": ":param branch_setting_func: a function that returns the default branch setting for this object. If not specified, ModuleStoreEnum.Branch.published_only is used as the default setting.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "A co... | 3 | stack_v2_sparse_classes_30k_train_002830 | Implement the Python class `BranchSettingMixin` described below.
Class description:
A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting... | Implement the Python class `BranchSettingMixin` described below.
Class description:
A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BranchSettingMixin:
"""A mixin to manage a module store's branch setting. The order of override is (from higher precedence to lower): 1. thread-specific setting temporarily set using the branch_setting contextmanager 2. the return value of the branch_setting_func passed into this mixin's init method 3. the de... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/modulestore/draft_and_published.py | luque/better-ways-of-thinking-about-software | train | 3 |
ad43c797f50b00bbdf820ecc6f9525399c45c97e | [
"self.rects = rects\nself.range = []\nsum = 0\nfor x1, y1, x2, y2 in rects:\n sum += (x2 - x1 + 1) * (y2 - y1 + 1)\n self.range.append(sum)",
"n = random.randint(0, self.range[-1] - 1)\ni = bisect.bisect(self.range, n) - 1\nx1, y1, x2, y2 = self.rects[i]\nn -= self.range[i]\nreturn [x1 + n % (x2 - x1 + 1), ... | <|body_start_0|>
self.rects = rects
self.range = []
sum = 0
for x1, y1, x2, y2 in rects:
sum += (x2 - x1 + 1) * (y2 - y1 + 1)
self.range.append(sum)
<|end_body_0|>
<|body_start_1|>
n = random.randint(0, self.range[-1] - 1)
i = bisect.bisect(self.r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.range = []
sum = 0
for x1, y1, x2... | stack_v2_sparse_classes_36k_train_030604 | 982 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003931 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 63faf361cd4eefe0f6f1e50c49ea22577a75ea74 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
self.range = []
sum = 0
for x1, y1, x2, y2 in rects:
sum += (x2 - x1 + 1) * (y2 - y1 + 1)
self.range.append(sum)
def pick(self):
""":rtype: Li... | the_stack_v2_python_sparse | leetcode/RandomPointinNon-overlappingRectangles/a.py | iamslash/learntocode | train | 7 | |
8b4742ec2e047edf74ace413674ec963f05ebd2a | [
"bfs = deque()\nbfs.append((root, 1))\nwhile bfs:\n node, level = bfs.popleft()\n if not node:\n continue\n if not node.left and (not node.right):\n return level\n bfs.append((node.left, level + 1))\n bfs.append((node.right, level + 1))\nreturn 0",
"if not root:\n return 0\nif not ... | <|body_start_0|>
bfs = deque()
bfs.append((root, 1))
while bfs:
node, level = bfs.popleft()
if not node:
continue
if not node.left and (not node.right):
return level
bfs.append((node.left, level + 1))
bfs... | LeetCode Monthly Challenge problem for October 22nd, 2020. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Exampl... | stack_v2_sparse_classes_36k_train_030605 | 2,267 | no_license | [
{
"docstring": "Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Example: Given the following tree, t: 3 / 9 20 / 15 7 minDepth(t) -> 2",
"name": "minDepth",
"signature": "def minDepth(self, root:... | 2 | stack_v2_sparse_classes_30k_test_000308 | Implement the Python class `Solution` described below.
Class description:
LeetCode Monthly Challenge problem for October 22nd, 2020.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. ... | Implement the Python class `Solution` described below.
Class description:
LeetCode Monthly Challenge problem for October 22nd, 2020.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. ... | c6d600bc74afd14e00d4f0ffed40696192b229c3 | <|skeleton|>
class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Exampl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Example: Given the ... | the_stack_v2_python_sparse | python/Monthly/Oct2020/minbinarytreedepth.py | Hilldrupca/LeetCode | train | 0 |
d57f1ea9c44b01e3c4c2620a3be81af25f562479 | [
"if 'query' not in input_data:\n error('No query in the input specified. Exiting ...')\nquery = input_data['query']\nreturn SparqlDockerWrapper._query_triplestore(database_uri, query)",
"sparql = SPARQLWrapper(endpoint, returnFormat=_SPARQL_RETURN_FORMAT)\nsparql.setQuery(query)\nresult = sparql.query().conver... | <|body_start_0|>
if 'query' not in input_data:
error('No query in the input specified. Exiting ...')
query = input_data['query']
return SparqlDockerWrapper._query_triplestore(database_uri, query)
<|end_body_0|>
<|body_start_1|>
sparql = SPARQLWrapper(endpoint, returnFormat=_... | SparqlDockerWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparqlDockerWrapper:
def load_data(database_uri: str, input_data: dict) -> pandas.DataFrame:
"""Load the local privacy-sensitive data from the database. Parameters ---------- database_uri : str URI of the triplestore, supplied by te node input_data : dict Can contain a 'query', to retrie... | stack_v2_sparse_classes_36k_train_030606 | 21,880 | permissive | [
{
"docstring": "Load the local privacy-sensitive data from the database. Parameters ---------- database_uri : str URI of the triplestore, supplied by te node input_data : dict Can contain a 'query', to retrieve the data from the triplestore Returns ------- pandas.DataFrame The data from the triplestore",
"n... | 2 | stack_v2_sparse_classes_30k_train_003990 | Implement the Python class `SparqlDockerWrapper` described below.
Class description:
Implement the SparqlDockerWrapper class.
Method signatures and docstrings:
- def load_data(database_uri: str, input_data: dict) -> pandas.DataFrame: Load the local privacy-sensitive data from the database. Parameters ---------- datab... | Implement the Python class `SparqlDockerWrapper` described below.
Class description:
Implement the SparqlDockerWrapper class.
Method signatures and docstrings:
- def load_data(database_uri: str, input_data: dict) -> pandas.DataFrame: Load the local privacy-sensitive data from the database. Parameters ---------- datab... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class SparqlDockerWrapper:
def load_data(database_uri: str, input_data: dict) -> pandas.DataFrame:
"""Load the local privacy-sensitive data from the database. Parameters ---------- database_uri : str URI of the triplestore, supplied by te node input_data : dict Can contain a 'query', to retrie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparqlDockerWrapper:
def load_data(database_uri: str, input_data: dict) -> pandas.DataFrame:
"""Load the local privacy-sensitive data from the database. Parameters ---------- database_uri : str URI of the triplestore, supplied by te node input_data : dict Can contain a 'query', to retrieve the data fr... | the_stack_v2_python_sparse | vantage6-client/vantage6/tools/wrapper.py | vantage6/vantage6 | train | 15 | |
1fb4e09fd76e0453944b136d2b931f883048cc55 | [
"serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\ntry:\n self.perform_create(serializer)\nexcept IntegrityError as e:\n response = dict(IntegrityError=str(e).replace('key', 'field'))\n return Response(response, status=status.HTTP_400_BAD_REQUEST)\nheaders = se... | <|body_start_0|>
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
self.perform_create(serializer)
except IntegrityError as e:
response = dict(IntegrityError=str(e).replace('key', 'field'))
return Respon... | API endpoint that allows Actuators to be viewed or edited. | DeviceViewSet | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def create(self, request, *args, **kwargs):
"""Create a device if the user has permission"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Update a specific device that a ... | stack_v2_sparse_classes_36k_train_030607 | 3,311 | permissive | [
{
"docstring": "Create a device if the user has permission",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "Update a specific device that a user has permission for",
"name": "update",
"signature": "def update(self, request, *args, **kwargs)... | 3 | stack_v2_sparse_classes_30k_train_020908 | Implement the Python class `DeviceViewSet` described below.
Class description:
API endpoint that allows Actuators to be viewed or edited.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Create a device if the user has permission
- def update(self, request, *args, **kwargs): Update a sp... | Implement the Python class `DeviceViewSet` described below.
Class description:
API endpoint that allows Actuators to be viewed or edited.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): Create a device if the user has permission
- def update(self, request, *args, **kwargs): Update a sp... | 9227d38cb53204b45641ac55aefd6a13d2aad563 | <|skeleton|>
class DeviceViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def create(self, request, *args, **kwargs):
"""Create a device if the user has permission"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Update a specific device that a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def create(self, request, *args, **kwargs):
"""Create a device if the user has permission"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
... | the_stack_v2_python_sparse | orchestrator/core/orc_server/device/views/viewsets.py | sumodgeorge/openc2-oif-orchestrator | train | 0 |
882905b66eb19f6db75b4fed87543117ef47e4d2 | [
"map_file = open(Serializer.FILE_NAME, 'wb')\npickle.dump(game_map, map_file)\ncustom_log.logger.info('Map Saved!')\ncustom_log.logger.info('---------------------------------------------------')",
"try:\n with open(Serializer.FILE_NAME, 'rb') as map_file:\n game_map = pickle.load(map_file)\n cust... | <|body_start_0|>
map_file = open(Serializer.FILE_NAME, 'wb')
pickle.dump(game_map, map_file)
custom_log.logger.info('Map Saved!')
custom_log.logger.info('---------------------------------------------------')
<|end_body_0|>
<|body_start_1|>
try:
with open(Serializer.F... | Serializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializer:
def save_map(game_map):
"""Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None."""
<|body_0|>
def load_map():
"""Load Game map. :returns: Game Map. :rtype: str."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_030608 | 1,231 | permissive | [
{
"docstring": "Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None.",
"name": "save_map",
"signature": "def save_map(game_map)"
},
{
"docstring": "Load Game map. :returns: Game Map. :rtype: str.",
"name": "load_map",
"signature": "def load_map()"
... | 2 | stack_v2_sparse_classes_30k_train_019640 | Implement the Python class `Serializer` described below.
Class description:
Implement the Serializer class.
Method signatures and docstrings:
- def save_map(game_map): Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None.
- def load_map(): Load Game map. :returns: Game Map. :rty... | Implement the Python class `Serializer` described below.
Class description:
Implement the Serializer class.
Method signatures and docstrings:
- def save_map(game_map): Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None.
- def load_map(): Load Game map. :returns: Game Map. :rty... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class Serializer:
def save_map(game_map):
"""Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None."""
<|body_0|>
def load_map():
"""Load Game map. :returns: Game Map. :rtype: str."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Serializer:
def save_map(game_map):
"""Save Game map. :param game_map: game map. :game_map type: str. :returns: None. :rtype: None."""
map_file = open(Serializer.FILE_NAME, 'wb')
pickle.dump(game_map, map_file)
custom_log.logger.info('Map Saved!')
custom_log.logger.info... | the_stack_v2_python_sparse | Yurii_Smazhnyi/10/dungeon_game/dungeon_game_smazhnyi/serializer.py | SmischenkoB/campus_2018_python | train | 0 | |
9ff0a9d5e878badb56dca68b7b31d21c9f5f5a5e | [
"if collection is None or self.schema is None:\n return\ntry:\n for item in collection:\n self._schema.filter(model=item, context=context if self.use_context else None)\nexcept TypeError:\n pass",
"if self._schema is None or not collection:\n return\nresult = []\ntry:\n for index, item in en... | <|body_start_0|>
if collection is None or self.schema is None:
return
try:
for item in collection:
self._schema.filter(model=item, context=context if self.use_context else None)
except TypeError:
pass
<|end_body_0|>
<|body_start_1|>
if... | Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection. | CollectionProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, c... | stack_v2_sparse_classes_36k_train_030609 | 5,839 | permissive | [
{
"docstring": "Perform collection items filtering with schema",
"name": "filter_with_schema",
"signature": "def filter_with_schema(self, collection=None, context=None)"
},
{
"docstring": "Validate each item in collection with our schema",
"name": "validate_with_schema",
"signature": "de... | 2 | null | Implement the Python class `CollectionProperty` described below.
Class description:
Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection.... | Implement the Python class `CollectionProperty` described below.
Class description:
Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection.... | c598d1af5df40fae65cf3878b8f67accbcd059b7 | <|skeleton|>
class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectionProperty:
"""Collection property Allows to validate nested collection of entities that exist on a property of another entity. Filters and validators will be applied to collection as whole, when schema will be applied to each item in the collection."""
def filter_with_schema(self, collection=Non... | the_stack_v2_python_sparse | shiftschema/property.py | projectshift/shift-schema | train | 2 |
8ca6da106fd53e80c9ee6f41c4f4d9bc0755851f | [
"self.map = dict()\nself.array = list()\nself.size = 0",
"if val in self.map:\n return False\nself.map[val] = self.size\nif self.size < len(self.array):\n self.array[self.size] = val\nelse:\n self.array.append(val)\nself.size += 1\nreturn True",
"if val not in self.map:\n return False\nindex = self.... | <|body_start_0|>
self.map = dict()
self.array = list()
self.size = 0
<|end_body_0|>
<|body_start_1|>
if val in self.map:
return False
self.map[val] = self.size
if self.size < len(self.array):
self.array[self.size] = val
else:
s... | The amortized time complexity of add/remove from array/hashmap is O(1). | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
"""The amortized time complexity of add/remove from array/hashmap is O(1)."""
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already co... | stack_v2_sparse_classes_36k_train_030610 | 1,556 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | null | Implement the Python class `RandomizedSet` described below.
Class description:
The amortized time complexity of add/remove from array/hashmap is O(1).
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the s... | Implement the Python class `RandomizedSet` described below.
Class description:
The amortized time complexity of add/remove from array/hashmap is O(1).
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the s... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class RandomizedSet:
"""The amortized time complexity of add/remove from array/hashmap is O(1)."""
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
"""The amortized time complexity of add/remove from array/hashmap is O(1)."""
def __init__(self):
"""Initialize your data structure here."""
self.map = dict()
self.array = list()
self.size = 0
def insert(self, val):
"""Inserts a value to the set... | the_stack_v2_python_sparse | 380_Insert_Delete_GetRandom_O(1).py | susunini/leetcode | train | 1 |
53d86418b8f6f5e1f6feec50ce18f3954f72eb7d | [
"_, _, patch = self._CommonGitSetup()\npatch.project = constants.CHROMITE_PROJECT\nself.assertTrue(trybot_patch_pool.ChromiteFilter(patch))\npatch.project = 'foooo'\nself.assertFalse(trybot_patch_pool.ChromiteFilter(patch))",
"_, _, patch = self._CommonGitSetup()\npatch.project = constants.CHROMITE_PROJECT\nself.... | <|body_start_0|>
_, _, patch = self._CommonGitSetup()
patch.project = constants.CHROMITE_PROJECT
self.assertTrue(trybot_patch_pool.ChromiteFilter(patch))
patch.project = 'foooo'
self.assertFalse(trybot_patch_pool.ChromiteFilter(patch))
<|end_body_0|>
<|body_start_1|>
_, ... | Tests for all the various filters. | FilterTests | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterTests:
"""Tests for all the various filters."""
def testChromiteFilter(self):
"""Make sure the chromite filter works"""
<|body_0|>
def testManifestFilters(self):
"""Make sure the manifest filters work"""
<|body_1|>
def testBranchFilter(self):
... | stack_v2_sparse_classes_36k_train_030611 | 2,095 | permissive | [
{
"docstring": "Make sure the chromite filter works",
"name": "testChromiteFilter",
"signature": "def testChromiteFilter(self)"
},
{
"docstring": "Make sure the manifest filters work",
"name": "testManifestFilters",
"signature": "def testManifestFilters(self)"
},
{
"docstring": "... | 3 | null | Implement the Python class `FilterTests` described below.
Class description:
Tests for all the various filters.
Method signatures and docstrings:
- def testChromiteFilter(self): Make sure the chromite filter works
- def testManifestFilters(self): Make sure the manifest filters work
- def testBranchFilter(self): Make ... | Implement the Python class `FilterTests` described below.
Class description:
Tests for all the various filters.
Method signatures and docstrings:
- def testChromiteFilter(self): Make sure the chromite filter works
- def testManifestFilters(self): Make sure the manifest filters work
- def testBranchFilter(self): Make ... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class FilterTests:
"""Tests for all the various filters."""
def testChromiteFilter(self):
"""Make sure the chromite filter works"""
<|body_0|>
def testManifestFilters(self):
"""Make sure the manifest filters work"""
<|body_1|>
def testBranchFilter(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterTests:
"""Tests for all the various filters."""
def testChromiteFilter(self):
"""Make sure the chromite filter works"""
_, _, patch = self._CommonGitSetup()
patch.project = constants.CHROMITE_PROJECT
self.assertTrue(trybot_patch_pool.ChromiteFilter(patch))
pa... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/trybot_patch_pool_unittest.py | metux/chromium-suckless | train | 5 |
ae7c3a40d553f17625f74135bdd8e35e0b3fb143 | [
"config = read_config(config_path)\nperms = config.get('umask', 23)\nos.umask(perms)\nif not model_type:\n model_type = config.get('model')\nif not model_type:\n raise ValueError('Cannot determine model type.')\nself.model_type = model_type\nif lab_path:\n self.basepath = lab_path\nelif 'PAYU_LAB_PATH' in ... | <|body_start_0|>
config = read_config(config_path)
perms = config.get('umask', 23)
os.umask(perms)
if not model_type:
model_type = config.get('model')
if not model_type:
raise ValueError('Cannot determine model type.')
self.model_type = model_type
... | Interface to the numerical model's laboratory. | Laboratory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Laboratory:
"""Interface to the numerical model's laboratory."""
def __init__(self, model_type=None, config_path=None, lab_path=None):
"""Create the Payu laboratory interface."""
<|body_0|>
def get_default_lab_path(self, config):
"""Generate a default laboratory ... | stack_v2_sparse_classes_36k_train_030612 | 2,636 | permissive | [
{
"docstring": "Create the Payu laboratory interface.",
"name": "__init__",
"signature": "def __init__(self, model_type=None, config_path=None, lab_path=None)"
},
{
"docstring": "Generate a default laboratory path based on user environment.",
"name": "get_default_lab_path",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_021515 | Implement the Python class `Laboratory` described below.
Class description:
Interface to the numerical model's laboratory.
Method signatures and docstrings:
- def __init__(self, model_type=None, config_path=None, lab_path=None): Create the Payu laboratory interface.
- def get_default_lab_path(self, config): Generate ... | Implement the Python class `Laboratory` described below.
Class description:
Interface to the numerical model's laboratory.
Method signatures and docstrings:
- def __init__(self, model_type=None, config_path=None, lab_path=None): Create the Payu laboratory interface.
- def get_default_lab_path(self, config): Generate ... | d52b6dc661249752fee48d883504d80594a2df2e | <|skeleton|>
class Laboratory:
"""Interface to the numerical model's laboratory."""
def __init__(self, model_type=None, config_path=None, lab_path=None):
"""Create the Payu laboratory interface."""
<|body_0|>
def get_default_lab_path(self, config):
"""Generate a default laboratory ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Laboratory:
"""Interface to the numerical model's laboratory."""
def __init__(self, model_type=None, config_path=None, lab_path=None):
"""Create the Payu laboratory interface."""
config = read_config(config_path)
perms = config.get('umask', 23)
os.umask(perms)
if n... | the_stack_v2_python_sparse | payu/laboratory.py | aidanheerdegen/payu | train | 0 |
c9b3b1168945795c711dc72edc811399579443e4 | [
"self.size = size\nself.st = []\nself.sum = 0.0",
"self.st.append(val)\nself.sum += val\nif len(self.st) > self.size:\n self.sum -= self.st.pop(0)\nreturn self.sum / len(self.st)"
] | <|body_start_0|>
self.size = size
self.st = []
self.sum = 0.0
<|end_body_0|>
<|body_start_1|>
self.st.append(val)
self.sum += val
if len(self.st) > self.size:
self.sum -= self.st.pop(0)
return self.sum / len(self.st)
<|end_body_1|>
| MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.st = []... | stack_v2_sparse_classes_36k_train_030613 | 610 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019468 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 98e7852ba144cefbdb02f705651b1519155ee4d6 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.st = []
self.sum = 0.0
def next(self, val):
""":type val: int :rtype: float"""
self.st.append(val)
self.sum += val
if l... | the_stack_v2_python_sparse | movingAverage.py | Franktian/leetcode | train | 1 | |
1809ac811b3aa166def31e207ce6c8ab0fcc0046 | [
"if self.request.method == 'GET':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method == 'DELETE':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsDep... | <|body_start_0|>
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method == 'DELETE':
return (perm... | Join key view set | JoinKeyViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinKeyViewSet:
"""Join key view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List join keys"""
<... | stack_v2_sparse_classes_36k_train_030614 | 7,281 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List join keys",
"name": "list",
... | 3 | stack_v2_sparse_classes_30k_train_001863 | Implement the Python class `JoinKeyViewSet` described below.
Class description:
Join key view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List join keys | Implement the Python class `JoinKeyViewSet` described below.
Class description:
Join key view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List join keys
<|skeleton|>
class JoinKey... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class JoinKeyViewSet:
"""Join key view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List join keys"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JoinKeyViewSet:
"""Join key view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommunity())
elif self.request.method == 'POST':
return (permiss... | the_stack_v2_python_sparse | generator/views.py | 810Teams/clubs-and-events-backend | train | 3 |
7bf94723357d75790a5614d990d0a1c7e3b1b865 | [
"kwargs['default'] = default\nkwargs['types'] = (Palette, str, tuple, list)\nsuper().__init__(**kwargs)",
"if isinstance(value, Palette):\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 Palette.create(value)"
] | <|body_start_0|>
kwargs['default'] = default
kwargs['types'] = (Palette, str, tuple, list)
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, Palette):
return value
value = super().parse(value)
if value is UNDEF or value is None:
... | Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name. | PaletteProperty | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaletteProperty:
"""Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name."""
def __init__(self, default=UNDEF, **kwarg... | stack_v2_sparse_classes_36k_train_030615 | 4,576 | permissive | [
{
"docstring": "Initializes a new instance of PaletteProperty.",
"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 `PaletteProperty` described below.
Class description:
Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name.
Method si... | Implement the Python class `PaletteProperty` described below.
Class description:
Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name.
Method si... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class PaletteProperty:
"""Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name."""
def __init__(self, default=UNDEF, **kwarg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaletteProperty:
"""Defines a color palette property, which simplifies a palette definition by automatically creating a pero.Palette instance from various input options such as a list of supported pero.Color definitions or registered palette name."""
def __init__(self, default=UNDEF, **kwargs):
"... | the_stack_v2_python_sparse | pero/properties/special.py | xxao/pero | train | 31 |
7a11661851d6ae1c1ebfe94d17bd709e276cb085 | [
"self.rwords = set([])\nself.rre = []\nself.restoreList = []\nself.tokenOffsets = Offsets()\nfinput = AltFileInput(ifile)\nmobj = None\nfor line in finput:\n line = skip_comments(line)\n if not line:\n continue\n mobj = __RWORD_RE__.match(line)\n if mobj:\n self.rwords.add(mobj.group(1))\n... | <|body_start_0|>
self.rwords = set([])
self.rre = []
self.restoreList = []
self.tokenOffsets = Offsets()
finput = AltFileInput(ifile)
mobj = None
for line in finput:
line = skip_comments(line)
if not line:
continue
... | Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should be restored self.restoreList - list of elements that should be restored self.toke... | NoiseRestorer | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoiseRestorer:
"""Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should be restored self.restoreList - list of e... | stack_v2_sparse_classes_36k_train_030616 | 8,631 | permissive | [
{
"docstring": "Create an instance of NoiseRestorer. @param ifile - name of file containing list of elements which should be restored",
"name": "__init__",
"signature": "def __init__(self, ifile=DEFAULT_NR_FILE)"
},
{
"docstring": "Read and store necessary meta-information from istring. @param i... | 5 | stack_v2_sparse_classes_30k_train_020296 | Implement the Python class `NoiseRestorer` described below.
Class description:
Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should b... | Implement the Python class `NoiseRestorer` described below.
Class description:
Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should b... | ac645fb41260b86491b17fbc50e5ea3300dc28b7 | <|skeleton|>
class NoiseRestorer:
"""Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should be restored self.restoreList - list of e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoiseRestorer:
"""Class for restoring strings that were previosuly deleted from messages. Instance variables: self.rwords - set of replacement words that should be restored self.rre - list of regular expressions that match replacement elements which should be restored self.restoreList - list of elements that ... | the_stack_v2_python_sparse | scripts/lib/python/ld/noise_restorer.py | WladimirSidorenko/TextNormalization | train | 1 |
80702c1c1a0693f67a45dd53fa386325a0066403 | [
"if self.request.method == 'POST':\n return NotExistingVoteSerializer\nreturn ExistingVoteSerializer",
"queryset = self.filter_queryset(self.get_queryset())\ntry:\n query = request.query_params.get('voted_for_user')\n if query is not None:\n membership_ids = [i.id for i in Membership.objects.filte... | <|body_start_0|>
if self.request.method == 'POST':
return NotExistingVoteSerializer
return ExistingVoteSerializer
<|end_body_0|>
<|body_start_1|>
queryset = self.filter_queryset(self.get_queryset())
try:
query = request.query_params.get('voted_for_user')
... | Vote view set | VoteViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoteViewSet:
"""Vote view set"""
def get_serializer_class(self):
"""Get serializer class"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List communities"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.request.method == 'POST'... | stack_v2_sparse_classes_36k_train_030617 | 3,137 | permissive | [
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List communities",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `VoteViewSet` described below.
Class description:
Vote view set
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List communities | Implement the Python class `VoteViewSet` described below.
Class description:
Vote view set
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List communities
<|skeleton|>
class VoteViewSet:
"""Vote view set"""
def get_seriali... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class VoteViewSet:
"""Vote view set"""
def get_serializer_class(self):
"""Get serializer class"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List communities"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoteViewSet:
"""Vote view set"""
def get_serializer_class(self):
"""Get serializer class"""
if self.request.method == 'POST':
return NotExistingVoteSerializer
return ExistingVoteSerializer
def list(self, request, *args, **kwargs):
"""List communities"""
... | the_stack_v2_python_sparse | misc/views.py | 810Teams/clubs-and-events-backend | train | 3 |
66836878fa8c7e89d676dd6883b493adc6b39a0f | [
"likelihood = gpytorch.likelihoods.GaussianLikelihood(noise_constraint=noise_constraint, noise_prior=noise_hyperprior)\nif train_y is not None:\n train_y = train_y.squeeze(-1)\nsuper(ExactGPSEModel, self).__init__(train_x, train_y, likelihood)\nself.mean_module = gpytorch.means.ConstantMean()\nif prior_mean != 0... | <|body_start_0|>
likelihood = gpytorch.likelihoods.GaussianLikelihood(noise_constraint=noise_constraint, noise_prior=noise_hyperprior)
if train_y is not None:
train_y = train_y.squeeze(-1)
super(ExactGPSEModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = g... | An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use a GPyTorch model in BoTorch. This adds all the api calls that botorch expects in... | ExactGPSEModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExactGPSEModel:
"""An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use a GPyTorch model in BoTorch. This adds... | stack_v2_sparse_classes_36k_train_030618 | 10,247 | no_license | [
{
"docstring": "Inits GP model with data and a Gaussian likelihood.",
"name": "__init__",
"signature": "def __init__(self, train_x: torch.Tensor, train_y: torch.Tensor, lengthscale_constraint=None, lengthscale_hyperprior=None, outputscale_constraint=None, outputscale_hyperprior=None, noise_constraint=No... | 2 | stack_v2_sparse_classes_30k_train_001115 | Implement the Python class `ExactGPSEModel` described below.
Class description:
An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use... | Implement the Python class `ExactGPSEModel` described below.
Class description:
An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use... | f5603a77cbcec26422ef5131261ddc7d48e0d127 | <|skeleton|>
class ExactGPSEModel:
"""An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use a GPyTorch model in BoTorch. This adds... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExactGPSEModel:
"""An exact Gaussian process (GP) model with a squared exponential (SE) kernel. ExactGP: The base class of gpytorch for any Gaussian process latent function to be used in conjunction with exact inference. GPyTorchModel: The easiest way to use a GPyTorch model in BoTorch. This adds all the api ... | the_stack_v2_python_sparse | src/model.py | gibo-neurips-2021/GIBO | train | 0 |
cd304260a992fbef7915dfaddcd9d4274396174c | [
"classParams = parameters.params\nparnames = [x for x, y, z, v, c in classParams]\nif type(excludeparams) is not list:\n excludeparams = [excludeparams]\nfor par in excludeparams:\n if type(par) is not str:\n print('Parameters should be strings!')\n exit()\n if par in parnames:\n parna... | <|body_start_0|>
classParams = parameters.params
parnames = [x for x, y, z, v, c in classParams]
if type(excludeparams) is not list:
excludeparams = [excludeparams]
for par in excludeparams:
if type(par) is not str:
print('Parameters should be stri... | All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram | parameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class parameters:
"""All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram"""
def exclude_params(excludeparams):
"""Takes a list of input parameters (or a single parameter) ... | stack_v2_sparse_classes_36k_train_030619 | 31,341 | permissive | [
{
"docstring": "Takes a list of input parameters (or a single parameter) as strings and returns the entire params list, except for the params given as input.",
"name": "exclude_params",
"signature": "def exclude_params(excludeparams)"
},
{
"docstring": "Takes a list of input parameters (or a sin... | 2 | stack_v2_sparse_classes_30k_train_006326 | Implement the Python class `parameters` described below.
Class description:
All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram
Method signatures and docstrings:
- def exclude_params(excludeparams): ... | Implement the Python class `parameters` described below.
Class description:
All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram
Method signatures and docstrings:
- def exclude_params(excludeparams): ... | 6e084a1e283b39a1f18d3f022496f7ffe37cd095 | <|skeleton|>
class parameters:
"""All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram"""
def exclude_params(excludeparams):
"""Takes a list of input parameters (or a single parameter) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class parameters:
"""All the different parameters in the form: (name, unit, pname, remark, color) - Note some parameters are only available for certain tracks. - Color is for the Kiel diagram"""
def exclude_params(excludeparams):
"""Takes a list of input parameters (or a single parameter) as strings an... | the_stack_v2_python_sparse | basta/constants.py | yutaozhou/BASTA | train | 0 |
c3c6c1f3ea5634d704e09f64c83ff1c7c8f5e5a1 | [
"if not lang:\n lang = SettingsDAO().get_value('language', str)\nself.set_many(True)\nfor name, value in strValues.items():\n data = {'lang': lang, 'target_id': objectId, 'type': objectType.value, 'name': name, 'value': value}\n self.insert('translates', data)\nself.insert_many_execute()\nself.set_many(Fal... | <|body_start_0|>
if not lang:
lang = SettingsDAO().get_value('language', str)
self.set_many(True)
for name, value in strValues.items():
data = {'lang': lang, 'target_id': objectId, 'type': objectType.value, 'name': name, 'value': value}
self.insert('translates... | ObjectDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectDatabase:
def insert_translate(self, strValues: dict, lang: str, objectId: int, objectType: ObjectType) -> None:
"""Insert translate for object to database :param strValues: dictionary of names and values :param lang: lang of translate :param objectId: id ob object :param objectTyp... | stack_v2_sparse_classes_36k_train_030620 | 2,991 | no_license | [
{
"docstring": "Insert translate for object to database :param strValues: dictionary of names and values :param lang: lang of translate :param objectId: id ob object :param objectType: objectType of object",
"name": "insert_translate",
"signature": "def insert_translate(self, strValues: dict, lang: str,... | 2 | stack_v2_sparse_classes_30k_train_008254 | Implement the Python class `ObjectDatabase` described below.
Class description:
Implement the ObjectDatabase class.
Method signatures and docstrings:
- def insert_translate(self, strValues: dict, lang: str, objectId: int, objectType: ObjectType) -> None: Insert translate for object to database :param strValues: dicti... | Implement the Python class `ObjectDatabase` described below.
Class description:
Implement the ObjectDatabase class.
Method signatures and docstrings:
- def insert_translate(self, strValues: dict, lang: str, objectId: int, objectType: ObjectType) -> None: Insert translate for object to database :param strValues: dicti... | 40b088e061042599cbb30373ac229d37dddc01e6 | <|skeleton|>
class ObjectDatabase:
def insert_translate(self, strValues: dict, lang: str, objectId: int, objectType: ObjectType) -> None:
"""Insert translate for object to database :param strValues: dictionary of names and values :param lang: lang of translate :param objectId: id ob object :param objectTyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectDatabase:
def insert_translate(self, strValues: dict, lang: str, objectId: int, objectType: ObjectType) -> None:
"""Insert translate for object to database :param strValues: dictionary of names and values :param lang: lang of translate :param objectId: id ob object :param objectType: objectType ... | the_stack_v2_python_sparse | Program/data/database/ObjectDatabase.py | Wilson194/DeskChar | train | 0 | |
56364556a08b8fef01cc57e249ddc6f3b584acd4 | [
"for pattern in copyfiles:\n glob_path = os.path.join(orig_dir, pattern)\n files = glob.glob(glob_path)\n for ff in files:\n f = os.path.basename(ff)\n orig_path = os.path.join(orig_dir, f)\n dest_path = os.path.join(dest_dir, f)\n try:\n copyfile(orig_path, dest_path... | <|body_start_0|>
for pattern in copyfiles:
glob_path = os.path.join(orig_dir, pattern)
files = glob.glob(glob_path)
for ff in files:
f = os.path.basename(ff)
orig_path = os.path.join(orig_dir, f)
dest_path = os.path.join(dest_di... | Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module. | CopyBaseROI | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyBaseROI:
"""Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module."""
def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles):
"""Copy a list of files from orig_dir to dest_dir"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_030621 | 21,082 | permissive | [
{
"docstring": "Copy a list of files from orig_dir to dest_dir",
"name": "copy_analysis_files",
"signature": "def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles)"
},
{
"docstring": "Create and populate directoris for target analysis",
"name": "copy_target_dir",
"signature": "def ... | 3 | null | Implement the Python class `CopyBaseROI` described below.
Class description:
Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module.
Method signatures and docstrings:
- def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles): Copy a list of ... | Implement the Python class `CopyBaseROI` described below.
Class description:
Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module.
Method signatures and docstrings:
- def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles): Copy a list of ... | fbd4c95ffadbff31cbb9cc862ff84a78dc734ef5 | <|skeleton|>
class CopyBaseROI:
"""Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module."""
def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles):
"""Copy a list of files from orig_dir to dest_dir"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopyBaseROI:
"""Small class to copy a baseline ROI to a simulation area This is useful for parallelizing analysis using the fermipy.jobs module."""
def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles):
"""Copy a list of files from orig_dir to dest_dir"""
for pattern in copyfiles:
... | the_stack_v2_python_sparse | fermipy/jobs/target_sim.py | fermiPy/fermipy | train | 51 |
99a87cf4dd8dec1c60589536347e0d301d593081 | [
"super().__init__()\nif criterion not in self._supported_criterion:\n raise ValueError(\"Invalid criterion '%s' specified for %s. Must be one of %s.\" % (criterion, self.__class__.__name__, self._supported_criterion))\nself._samples = samples\nself._criterion = criterion\nself._iterations = iterations\nself._see... | <|body_start_0|>
super().__init__()
if criterion not in self._supported_criterion:
raise ValueError("Invalid criterion '%s' specified for %s. Must be one of %s." % (criterion, self.__class__.__name__, self._supported_criterion))
self._samples = samples
self._criterion = crite... | DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion to use. _iterations : int The number of iterations to use for maximin and correlations al... | LatinHypercubeGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatinHypercubeGenerator:
"""DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion to use. _iterations : int The number o... | stack_v2_sparse_classes_36k_train_030622 | 21,019 | no_license | [
{
"docstring": "Initialize the LatinHypercubeGenerator. See : https://pythonhosted.org/pyDOE/randomized.html Parameters ---------- samples : int, optional The number of samples to generate for each factor (Defaults to n) criterion : str, optional Allowable values are \"center\" or \"c\", \"maximin\" or \"m\", \... | 2 | stack_v2_sparse_classes_30k_test_000871 | Implement the Python class `LatinHypercubeGenerator` described below.
Class description:
DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion... | Implement the Python class `LatinHypercubeGenerator` described below.
Class description:
DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion... | d9e89fe017f1131d554599c248247f73bb9b534d | <|skeleton|>
class LatinHypercubeGenerator:
"""DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion to use. _iterations : int The number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LatinHypercubeGenerator:
"""DOE case generator implementing Latin hypercube method via pyDOE2. Attributes ---------- _samples : int The number of evenly spaced levels between each design variable lower and upper bound. _criterion : string the pyDOE criterion to use. _iterations : int The number of iterations ... | the_stack_v2_python_sparse | venv/Lib/site-packages/openmdao/drivers/doe_generators.py | ManojDjs/Heart-rate-estimation | train | 1 |
08920f847356531caa299c44ac95c97e73f83b74 | [
"if not nums:\n return 0\nm = len(nums)\ndp = [1] * m\nfor i in range(1, m):\n for j in range(i, -1, -1):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], 1 + dp[j])\nreturn max(dp)",
"size = len(nums)\nif size < 2:\n return size\ntail = [nums[0]]\nfor i in range(1, size):\n if nums[i] >... | <|body_start_0|>
if not nums:
return 0
m = len(nums)
dp = [1] * m
for i in range(1, m):
for j in range(i, -1, -1):
if nums[j] < nums[i]:
dp[i] = max(dp[i], 1 + dp[j])
return max(dp)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS_1(self, nums) -> int:
"""*dp 时间复杂度 o(n*n) 空间复杂度 o(n)"""
<|body_0|>
def lengthOfLIS_2(self, nums) -> int:
"""*dp+二分 时间复杂度 o(nlogn) 空间复杂度 o(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
... | stack_v2_sparse_classes_36k_train_030623 | 1,903 | no_license | [
{
"docstring": "*dp 时间复杂度 o(n*n) 空间复杂度 o(n)",
"name": "lengthOfLIS_1",
"signature": "def lengthOfLIS_1(self, nums) -> int"
},
{
"docstring": "*dp+二分 时间复杂度 o(nlogn) 空间复杂度 o(n)",
"name": "lengthOfLIS_2",
"signature": "def lengthOfLIS_2(self, nums) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_007189 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_1(self, nums) -> int: *dp 时间复杂度 o(n*n) 空间复杂度 o(n)
- def lengthOfLIS_2(self, nums) -> int: *dp+二分 时间复杂度 o(nlogn) 空间复杂度 o(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_1(self, nums) -> int: *dp 时间复杂度 o(n*n) 空间复杂度 o(n)
- def lengthOfLIS_2(self, nums) -> int: *dp+二分 时间复杂度 o(nlogn) 空间复杂度 o(n)
<|skeleton|>
class Solution:
def ... | ebf9503d4bc6d4335c463aa2b4622dd7df55fb87 | <|skeleton|>
class Solution:
def lengthOfLIS_1(self, nums) -> int:
"""*dp 时间复杂度 o(n*n) 空间复杂度 o(n)"""
<|body_0|>
def lengthOfLIS_2(self, nums) -> int:
"""*dp+二分 时间复杂度 o(nlogn) 空间复杂度 o(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS_1(self, nums) -> int:
"""*dp 时间复杂度 o(n*n) 空间复杂度 o(n)"""
if not nums:
return 0
m = len(nums)
dp = [1] * m
for i in range(1, m):
for j in range(i, -1, -1):
if nums[j] < nums[i]:
dp[i] = ... | the_stack_v2_python_sparse | dynamic_programming/300_longest_increasing_subsequence.py | huuu97/LeetCode | train | 0 | |
a63fcd94ca0865893d29f0e633366c85e521b29c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ScheduleInformation()",
"from .free_busy_error import FreeBusyError\nfrom .schedule_item import ScheduleItem\nfrom .working_hours import WorkingHours\nfrom .free_busy_error import FreeBusyError\nfrom .schedule_item import ScheduleItem\... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ScheduleInformation()
<|end_body_0|>
<|body_start_1|>
from .free_busy_error import FreeBusyError
from .schedule_item import ScheduleItem
from .working_hours import WorkingHours
... | ScheduleInformation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ScheduleInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k_train_030624 | 4,465 | 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: ScheduleInformation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | stack_v2_sparse_classes_30k_train_011518 | Implement the Python class `ScheduleInformation` described below.
Class description:
Implement the ScheduleInformation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ScheduleInformation: Creates a new instance of the appropriate class based on d... | Implement the Python class `ScheduleInformation` described below.
Class description:
Implement the ScheduleInformation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ScheduleInformation: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ScheduleInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ScheduleInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleInformation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ScheduleInformation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/schedule_information.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fb6b85b6bba11054c5ec916cb67322b82dec70b6 | [
"resp, body = self.get('/')\nbody = json.loads(body)\nself.expected_success(200, resp.status)\nreturn rest_client.ResponseBody(resp, body)",
"resp, body = self.get(version + '/')\nbody = json.loads(body)\nself.expected_success(200, resp.status)\nreturn rest_client.ResponseBody(resp, body)"
] | <|body_start_0|>
resp, body = self.get('/')
body = json.loads(body)
self.expected_success(200, resp.status)
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body_start_1|>
resp, body = self.get(version + '/')
body = json.loads(body)
self.expected_succ... | NetworkVersionsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
<|body_0|>
def show_versi... | stack_v2_sparse_classes_36k_train_030625 | 1,823 | permissive | [
{
"docstring": "Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions",
"name": "list_versions",
"signature": "def list_versions(self)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_014612 | Implement the Python class `NetworkVersionsClient` described below.
Class description:
Implement the NetworkVersionsClient class.
Method signatures and docstrings:
- def list_versions(self): Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https:... | Implement the Python class `NetworkVersionsClient` described below.
Class description:
Implement the NetworkVersionsClient class.
Method signatures and docstrings:
- def list_versions(self): Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https:... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
<|body_0|>
def show_versi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkVersionsClient:
def list_versions(self):
"""Do a GET / to fetch available API version information. For more information, please refer to the official API reference: https://docs.openstack.org/api-ref/network/v2/index.html#list-api-versions"""
resp, body = self.get('/')
body = js... | the_stack_v2_python_sparse | tempest/lib/services/network/versions_client.py | openstack/tempest | train | 270 | |
1a2dfdf83890287c248e74fb05550cabdf242794 | [
"if len(a) == 0:\n return 0\nminVal = a[0]\nsummary = 0\ncurMax = 0\nfor i in range(1, len(a)):\n if a[i] > minVal and a[i] > a[i - 1]:\n curMax = max(curMax, a[i] - minVal)\n else:\n summary += curMax\n curMax = 0\n minVal = a[i]\nsummary += curMax\nreturn summary",
"t1 = 0\n... | <|body_start_0|>
if len(a) == 0:
return 0
minVal = a[0]
summary = 0
curMax = 0
for i in range(1, len(a)):
if a[i] > minVal and a[i] > a[i - 1]:
curMax = max(curMax, a[i] - minVal)
else:
summary += curMax
... | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/"""
def maxProfit(self, a):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, a):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_030626 | 1,152 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, a)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, a)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
Method signatures and docstrings:
- def maxProfit(self, a): :type prices: List[int] :rtype: int
- def maxProfit2(self, a): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
Method signatures and docstrings:
- def maxProfit(self, a): :type prices: List[int] :rtype: int
- def maxProfit2(self, a): :type prices: List[int] :rtype: int
<|skel... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/"""
def maxProfit(self, a):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, a):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/"""
def maxProfit(self, a):
""":type prices: List[int] :rtype: int"""
if len(a) == 0:
return 0
minVal = a[0]
summary = 0
curMax = 0
for i in range(1, len(a... | the_stack_v2_python_sparse | old/Session002/DynamicProgramming/BestTimeBuyandSellStockII.py | MaxIakovliev/algorithms | train | 0 |
5fe54ef6692d607040370e9838cd4a4d0f827859 | [
"parent = self.parentWidget()\nif parent is not None:\n size = parent.explicitMinimumSize()\n if size.isValid():\n return size\nreturn super(QWindowLayout, self).minimumSize()",
"parent = self.parentWidget()\nif parent is not None:\n size = parent.explicitMaximumSize()\n if size.isValid():\n ... | <|body_start_0|>
parent = self.parentWidget()
if parent is not None:
size = parent.explicitMinimumSize()
if size.isValid():
return size
return super(QWindowLayout, self).minimumSize()
<|end_body_0|>
<|body_start_1|>
parent = self.parentWidget()
... | A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes. | QWindowLayout | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QWindowLayout:
"""A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes."""
def minimumSize(self):
"""The minimum size for the layout area. This is a reimpleme... | stack_v2_sparse_classes_36k_train_030627 | 5,075 | permissive | [
{
"docstring": "The minimum size for the layout area. This is a reimplemented method which will return the explicit minimum size of the window, if provided.",
"name": "minimumSize",
"signature": "def minimumSize(self)"
},
{
"docstring": "The maximum size for the layout area. This is a reimplemen... | 2 | stack_v2_sparse_classes_30k_train_003404 | Implement the Python class `QWindowLayout` described below.
Class description:
A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes.
Method signatures and docstrings:
- def minimumSize(self): ... | Implement the Python class `QWindowLayout` described below.
Class description:
A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes.
Method signatures and docstrings:
- def minimumSize(self): ... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QWindowLayout:
"""A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes."""
def minimumSize(self):
"""The minimum size for the layout area. This is a reimpleme... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QWindowLayout:
"""A single widget layout for use with window classes. This class extends the single widget layout to add support for QWindowBase classes and their use of explicit min and max sizes."""
def minimumSize(self):
"""The minimum size for the layout area. This is a reimplemented method w... | the_stack_v2_python_sparse | enaml/qt/q_window_base.py | MatthieuDartiailh/enaml | train | 26 |
104757768b979c59f9284a42c0d9ad5e5611bef7 | [
"self.screen_width = 1300\nself.screen_height = 800\nself.image = pygame.image.load('blue_bg.png')\nself.ship_speed_factor = 20\nself.bullet_speed_factor = 15\nself.bullet_width = 5\nself.bullet_height = 25\nself.bullet_color = (255, 0, 0)\nself.bullets_allowed = 30\nself.alien_speed_factor = 3\nself.speedup_scale ... | <|body_start_0|>
self.screen_width = 1300
self.screen_height = 800
self.image = pygame.image.load('blue_bg.png')
self.ship_speed_factor = 20
self.bullet_speed_factor = 15
self.bullet_width = 5
self.bullet_height = 25
self.bullet_color = (255, 0, 0)
... | Класс для хранения всех настроек игры Alien Invasion. | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_030628 | 2,153 | no_license | [
{
"docstring": "Инициализирует настройки игры.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Инициализирует настройки, изменяющиеся в ходе игры.",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_017211 | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion.
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры.
- def incr... | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion.
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры.
- def incr... | a70c56c3b3298766acfe220fc0fad7978baa3290 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры."""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
self.screen_width = 1300
self.screen_height = 800
self.image = pygame.image.load('blue_bg.png')
self.ship_speed_factor = 20
self.b... | the_stack_v2_python_sparse | Game Alien/setgame.py | semen-ksv/Python_learn | train | 0 |
69eb84d65d80308ae3861e63510fbf95e7d39e7f | [
"resource_args.AddMigrationJobResourceArgs(parser, 'to update')\nmj_flags.AddNoAsyncFlag(parser)\nmj_flags.AddDisplayNameFlag(parser)\nmj_flags.AddTypeFlag(parser)\nmj_flags.AddDumpPathFlag(parser)\nmj_flags.AddConnectivityGroupFlag(parser, mj_flags.ApiType.UPDATE)\nflags.AddLabelsUpdateFlags(parser)",
"migration... | <|body_start_0|>
resource_args.AddMigrationJobResourceArgs(parser, 'to update')
mj_flags.AddNoAsyncFlag(parser)
mj_flags.AddDisplayNameFlag(parser)
mj_flags.AddTypeFlag(parser)
mj_flags.AddDumpPathFlag(parser)
mj_flags.AddConnectivityGroupFlag(parser, mj_flags.ApiType.UPD... | Update a Database Migration Service migration job. | _Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Update:
"""Update a Database Migration Service migration job."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional argume... | stack_v2_sparse_classes_36k_train_030629 | 5,054 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_003201 | Implement the Python class `_Update` described below.
Class description:
Update a Database Migration Service migration job.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go ... | Implement the Python class `_Update` described below.
Class description:
Update a Database Migration Service migration job.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class _Update:
"""Update a Database Migration Service migration job."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional argume... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Update:
"""Update a Database Migration Service migration job."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allow... | the_stack_v2_python_sparse | lib/surface/database_migration/migration_jobs/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
142d2619b3d48199c9def00d59834d845b0eeaef | [
"if config['lang'] not in ['zh', 'zh-hans', 'zh-hant']:\n raise Exception('Jieba tokenizer is currently only allowed in Chinese (simplified or traditional) pipelines.')\ncheck_jieba()\nimport jieba\nself.nlp = jieba\nself.no_ssplit = config.get('no_ssplit', False)",
"if isinstance(document, doc.Document):\n ... | <|body_start_0|>
if config['lang'] not in ['zh', 'zh-hans', 'zh-hant']:
raise Exception('Jieba tokenizer is currently only allowed in Chinese (simplified or traditional) pipelines.')
check_jieba()
import jieba
self.nlp = jieba
self.no_ssplit = config.get('no_ssplit', ... | JiebaTokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiebaTokenizer:
def __init__(self, config):
"""Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation."""
<|body_0|>
def process(self, document):
"""Tokenize a document with the Jieba tokenizer a... | stack_v2_sparse_classes_36k_train_030630 | 2,378 | permissive | [
{
"docstring": "Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Tokenize a document with the Jieba tokenizer and wrap the results int... | 2 | null | Implement the Python class `JiebaTokenizer` described below.
Class description:
Implement the JiebaTokenizer class.
Method signatures and docstrings:
- def __init__(self, config): Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation.
- def proc... | Implement the Python class `JiebaTokenizer` described below.
Class description:
Implement the JiebaTokenizer class.
Method signatures and docstrings:
- def __init__(self, config): Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation.
- def proc... | c530c9af647d521262b56b717bcc38b0cfc5f1b8 | <|skeleton|>
class JiebaTokenizer:
def __init__(self, config):
"""Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation."""
<|body_0|>
def process(self, document):
"""Tokenize a document with the Jieba tokenizer a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JiebaTokenizer:
def __init__(self, config):
"""Construct a Jieba-based tokenizer by loading the Jieba pipeline. Note that this tokenizer uses regex for sentence segmentation."""
if config['lang'] not in ['zh', 'zh-hans', 'zh-hant']:
raise Exception('Jieba tokenizer is currently onl... | the_stack_v2_python_sparse | stanza/pipeline/external/jieba.py | stanfordnlp/stanza | train | 4,281 | |
7a699bb81e9b9652baf9a288f1bd2fcfd2a70fe7 | [
"LOGGER.info('Importing CDK...')\nfrom aws_cdk.core import App\nfrom pcluster.templates.cdk_artifacts_manager import CDKArtifactsManager\nfrom pcluster.templates.cluster_stack import ClusterCdkStack\nLOGGER.info('CDK import completed successfully')\nLOGGER.info('Starting CDK template generation...')\nwith tempfile.... | <|body_start_0|>
LOGGER.info('Importing CDK...')
from aws_cdk.core import App
from pcluster.templates.cdk_artifacts_manager import CDKArtifactsManager
from pcluster.templates.cluster_stack import ClusterCdkStack
LOGGER.info('CDK import completed successfully')
LOGGER.info... | Create the template, starting from the given resources. | CDKTemplateBuilder | [
"Python-2.0",
"GPL-1.0-or-later",
"MPL-2.0",
"MIT",
"LicenseRef-scancode-python-cwi",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"MIT-0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format.""... | stack_v2_sparse_classes_36k_train_030631 | 3,232 | permissive | [
{
"docstring": "Build template for the given cluster and return as output in Yaml format.",
"name": "build_cluster_template",
"signature": "def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None)"
},
{
"docstring": "Build templat... | 2 | stack_v2_sparse_classes_30k_train_000391 | Implement the Python class `CDKTemplateBuilder` described below.
Class description:
Create the template, starting from the given resources.
Method signatures and docstrings:
- def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None): Build template for... | Implement the Python class `CDKTemplateBuilder` described below.
Class description:
Create the template, starting from the given resources.
Method signatures and docstrings:
- def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None): Build template for... | a213978a09ea7fc80855bf55c539861ea95259f9 | <|skeleton|>
class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format."""
LOG... | the_stack_v2_python_sparse | cli/src/pcluster/templates/cdk_builder.py | aws/aws-parallelcluster | train | 520 |
df78ee9fbfed5ac0e3e7adb16fbda10d0a136ae2 | [
"len1 = len(s1)\nlen2 = len(s2)\nlen3 = len(s3)\nif len1 + len2 != len3:\n return False\ndp = [[False] * (len2 + 1) for _ in range(len1 + 1)]\ndp[0][0] = True\nfor i in xrange(len1 + 1):\n for j in xrange(len2 + 1):\n if j > 0:\n dp[i][j] = dp[i][j - 1] and s3[i + j - 1] == s2[j - 1]\n ... | <|body_start_0|>
len1 = len(s1)
len2 = len(s2)
len3 = len(s3)
if len1 + len2 != len3:
return False
dp = [[False] * (len2 + 1) for _ in range(len1 + 1)]
dp[0][0] = True
for i in xrange(len1 + 1):
for j in xrange(len2 + 1):
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_030632 | 2,358 | no_license | [
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave",
"signature": "def isInterleave(self, s1, s2, s3)"
},
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave2",
"signature": "def isInterleave2(self, s1... | 2 | stack_v2_sparse_classes_30k_train_002226 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | db2d0b05020a1fcb9f0cfaf9386f79daeaad759e | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
len1 = len(s1)
len2 = len(s2)
len3 = len(s3)
if len1 + len2 != len3:
return False
dp = [[False] * (len2 + 1) for _ in range(len1 + 1)]
... | the_stack_v2_python_sparse | leetcode/dynamic_programming/97_is_interleave.py | longgb246/MLlearn | train | 0 | |
19669e4f1ecd7f76ab0f783d0edd99c97ecf5131 | [
"self.beamline_name = beamline_name\nself.loop = loop\nasyncio.ensure_future(self.setup(), loop=self.loop)",
"try:\n self.beamline = BL_SPEC(self)\n await self.beamline.setup()\n print(\"Finished beamline setup for '{}'\".format(self.beamline_name))\nexcept:\n print('Caught exception in setup of beaml... | <|body_start_0|>
self.beamline_name = beamline_name
self.loop = loop
asyncio.ensure_future(self.setup(), loop=self.loop)
<|end_body_0|>
<|body_start_1|>
try:
self.beamline = BL_SPEC(self)
await self.beamline.setup()
print("Finished beamline setup for ... | This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the beamlines. Each beamline will have it's own LMD_beamlineInteraction() object. | BL_Interaction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BL_Interaction:
"""This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the beamlines. Each beamline will have it'... | stack_v2_sparse_classes_36k_train_030633 | 20,468 | permissive | [
{
"docstring": "Sets up all of the objects discussed above. The only argument is the 'fun' unique name of the beamline that appears in the beamline config YAML files.",
"name": "__init__",
"signature": "def __init__(self, beamline_name, loop)"
},
{
"docstring": "Setup anything that depends on as... | 2 | null | Implement the Python class `BL_Interaction` described below.
Class description:
This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the... | Implement the Python class `BL_Interaction` described below.
Class description:
This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the... | f145e757d092d85b5a21dc4c36d99f82d55f7037 | <|skeleton|>
class BL_Interaction:
"""This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the beamlines. Each beamline will have it'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BL_Interaction:
"""This class is holds all of the beamline interaction objects and initilizes all of their functionality. This includes the beamline variables, rosetta object, beamline state configuration object, and subroutines for executing commands on the beamlines. Each beamline will have it's own LMD_bea... | the_stack_v2_python_sparse | xdart/modules/pySSRL_bServer/bServer/bl_interaction.py | rwalroth/xdart | train | 2 |
f3b928986c0b8b3588b0b5e195041c07725e641f | [
"res = super(StudentAttendanceByMonth, self).default_get(fields)\nstudents = self.env['student.student'].browse(self._context.get('active_id'))\nif students.state == 'draft':\n raise ValidationError(_('You can not print report for student in unconfirm state!'))\nreturn res",
"stud_search = self.env['student.st... | <|body_start_0|>
res = super(StudentAttendanceByMonth, self).default_get(fields)
students = self.env['student.student'].browse(self._context.get('active_id'))
if students.state == 'draft':
raise ValidationError(_('You can not print report for student in unconfirm state!'))
re... | Defining Student Attendance By Month. | StudentAttendanceByMonth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentAttendanceByMonth:
"""Defining Student Attendance By Month."""
def default_get(self, fields):
"""Overriding DefaultGet."""
<|body_0|>
def print_report(self):
"""This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid :... | stack_v2_sparse_classes_36k_train_030634 | 2,598 | no_license | [
{
"docstring": "Overriding DefaultGet.",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param context : sta... | 2 | stack_v2_sparse_classes_30k_train_000277 | Implement the Python class `StudentAttendanceByMonth` described below.
Class description:
Defining Student Attendance By Month.
Method signatures and docstrings:
- def default_get(self, fields): Overriding DefaultGet.
- def print_report(self): This method prints report @param self : Object Pointer @param cr : Databas... | Implement the Python class `StudentAttendanceByMonth` described below.
Class description:
Defining Student Attendance By Month.
Method signatures and docstrings:
- def default_get(self, fields): Overriding DefaultGet.
- def print_report(self): This method prints report @param self : Object Pointer @param cr : Databas... | 6a9793f3a15da9eed40bf840b1d9a46457c5fd55 | <|skeleton|>
class StudentAttendanceByMonth:
"""Defining Student Attendance By Month."""
def default_get(self, fields):
"""Overriding DefaultGet."""
<|body_0|>
def print_report(self):
"""This method prints report @param self : Object Pointer @param cr : Database Cursor @param uid :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentAttendanceByMonth:
"""Defining Student Attendance By Month."""
def default_get(self, fields):
"""Overriding DefaultGet."""
res = super(StudentAttendanceByMonth, self).default_get(fields)
students = self.env['student.student'].browse(self._context.get('active_id'))
i... | the_stack_v2_python_sparse | school_attendance/wizard/student_attendance_by_month.py | JayVora-SerpentCS/OdooEduERP | train | 121 |
5e2086c362276746a37e37faf8b0b7faa5c22cb4 | [
"course = Course(name='testing course', slug='testing-course')\ncourse.save()\ncoursesection = CourseSection(name='Section 1', course=course)\ncoursesection.save()\ncategory = Category(name='Category 1 for testing course', slug='cat-1-testing-course', section=coursesection)\ncategory.save()\nassert category.course ... | <|body_start_0|>
course = Course(name='testing course', slug='testing-course')
course.save()
coursesection = CourseSection(name='Section 1', course=course)
coursesection.save()
category = Category(name='Category 1 for testing course', slug='cat-1-testing-course', section=coursese... | Tests related to the actual Category and Subcategory functionality. | CategoryTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryTests:
"""Tests related to the actual Category and Subcategory functionality."""
def test_category_creation(self):
"""Tests creating a category."""
<|body_0|>
def test_category_uniqueness(self):
"""Testing the uniqueness of a Category."""
<|body_1... | stack_v2_sparse_classes_36k_train_030635 | 5,866 | no_license | [
{
"docstring": "Tests creating a category.",
"name": "test_category_creation",
"signature": "def test_category_creation(self)"
},
{
"docstring": "Testing the uniqueness of a Category.",
"name": "test_category_uniqueness",
"signature": "def test_category_uniqueness(self)"
},
{
"do... | 4 | null | Implement the Python class `CategoryTests` described below.
Class description:
Tests related to the actual Category and Subcategory functionality.
Method signatures and docstrings:
- def test_category_creation(self): Tests creating a category.
- def test_category_uniqueness(self): Testing the uniqueness of a Category... | Implement the Python class `CategoryTests` described below.
Class description:
Tests related to the actual Category and Subcategory functionality.
Method signatures and docstrings:
- def test_category_creation(self): Tests creating a category.
- def test_category_uniqueness(self): Testing the uniqueness of a Category... | cd4ff5222e437fca055dce4790c8c349699d3f5f | <|skeleton|>
class CategoryTests:
"""Tests related to the actual Category and Subcategory functionality."""
def test_category_creation(self):
"""Tests creating a category."""
<|body_0|>
def test_category_uniqueness(self):
"""Testing the uniqueness of a Category."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryTests:
"""Tests related to the actual Category and Subcategory functionality."""
def test_category_creation(self):
"""Tests creating a category."""
course = Course(name='testing course', slug='testing-course')
course.save()
coursesection = CourseSection(name='Secti... | the_stack_v2_python_sparse | src/categories/tests.py | av8ramit/caprende | train | 0 |
522dd7377ad92ef5686fbadbe09409e807c6cfa1 | [
"self.workflow = kwargs.pop('workflow')\nself.user = kwargs.pop('user')\nsuper().__init__(*args, **kwargs)",
"if record.is_verified:\n return format_html('<a href=\"{0}\" ' + 'data-toggle=\"tooltip\" title=\"{1}\">{2}', reverse('dataops:plugin_invoke', kwargs={'pk': record.id}), _('Execute the transformation')... | <|body_start_0|>
self.workflow = kwargs.pop('workflow')
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if record.is_verified:
return format_html('<a href="{0}" ' + 'data-toggle="tooltip" title="{1}">{2}', reverse('dataops:plu... | Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation. | PluginAvailableTable | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginAvailableTable:
"""Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation."""
def __init__(self, *args, **kwargs):
"""Set workflow and user to get latest execution time."""
<... | stack_v2_sparse_classes_36k_train_030636 | 9,489 | permissive | [
{
"docstring": "Set workflow and user to get latest execution time.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Render as a link or empty if it has not been verified.",
"name": "render_name",
"signature": "def render_name(self, record)"
}... | 3 | null | Implement the Python class `PluginAvailableTable` described below.
Class description:
Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set wor... | Implement the Python class `PluginAvailableTable` described below.
Class description:
Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set wor... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class PluginAvailableTable:
"""Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation."""
def __init__(self, *args, **kwargs):
"""Set workflow and user to get latest execution time."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PluginAvailableTable:
"""Class to render the table with plugins available for execution. The Operations column is inheriting from another class to centralise the customisation."""
def __init__(self, *args, **kwargs):
"""Set workflow and user to get latest execution time."""
self.workflow ... | the_stack_v2_python_sparse | ontask/dataops/views/transform.py | LucasFranciscoCorreia/ontask_b | train | 0 |
2944f6f3ab6fcc732264db3ce87dc8c8234e4075 | [
"super().__init__()\nself.rnn_type = rnn_type\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.enforce_sorted = enforce_sorted\nif rnn_type in ['lstm', 'gru']:\n if kwargs:\n logger.warn(f\"The following '{kwargs}' will be ignored \" + \"as they are only considered when using 'sru' as \... | <|body_start_0|>
super().__init__()
self.rnn_type = rnn_type
self.input_size = input_size
self.hidden_size = hidden_size
self.enforce_sorted = enforce_sorted
if rnn_type in ['lstm', 'gru']:
if kwargs:
logger.warn(f"The following '{kwargs}' will... | Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding. Padding is delt with by using torch's... | RNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding.... | stack_v2_sparse_classes_36k_train_030637 | 9,960 | permissive | [
{
"docstring": "Initializes the RNNEncoder object. Parameters ---------- input_size : int The dimension the input data hidden_size : int The hidden dimension to encode the data in n_layers : int, optional The number of rnn layers, defaults to 1 rnn_type : str, optional The type of rnn cell, one of: `lstm`, `gru... | 2 | stack_v2_sparse_classes_30k_train_017944 | Implement the Python class `RNNEncoder` described below.
Class description:
Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by takin... | Implement the Python class `RNNEncoder` described below.
Class description:
Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by takin... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""Implements a multi-layer RNN. This module can be used to create multi-layer RNN models, and provides a way to reduce to output of the RNN to a single hidden state by pooling the encoder states either by taking the maximum, average, or by taking the last hidden state before padding. Padding is d... | the_stack_v2_python_sparse | flambe/nn/rnn.py | cle-ros/flambe | train | 1 |
9b377d5c4177bc48b2cbe79c205a8e44ec0f748a | [
"if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if self.cleaned_data['password1'] != self.cleaned_data['password2']:\n raise forms.ValidationError(_(\"The two password fields didn't match.\"))\nreturn self.cleaned_data",
"if User.objects.filter(username__exact=self.cleaned_d... | <|body_start_0|>
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data
<|end_body_0|>
<|b... | Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. | RegistrationForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos."""
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note tha... | stack_v2_sparse_classes_36k_train_030638 | 2,791 | permissive | [
{
"docstring": "Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Validate that the supplied email addr... | 3 | stack_v2_sparse_classes_30k_train_010265 | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos.
Method signatures and docstrings:
- def clean(self): Verifiy that the va... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos.
Method signatures and docstrings:
- def clean(self): Verifiy that the va... | f6ce11da22154bce9cba42e896989bdb0fd5e865 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos."""
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos."""
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note that an error he... | the_stack_v2_python_sparse | apps/accounts/forms.py | cartwheelweb/packaginator | train | 53 |
bfb0e40107f99fd368af8e5d8eb5bbb450d11e81 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.ProcessorInformation = ProcessorInformation\nself.Classification = Classification\nself.ProductName = ProductName\nself.ProductClass = ProductClass\nself.ProductType = Prod... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.ProcessorInformation = ProcessorInformation
self.Classification = Classification
self.ProductName = ProductN... | Contains general information about product creation. | ProductCreationType | [
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductCreationType:
"""Contains general information about product creation."""
def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensions=None, **kwargs):
"""Parameters ---------- ProcessorInfor... | stack_v2_sparse_classes_36k_train_030639 | 16,798 | permissive | [
{
"docstring": "Parameters ---------- ProcessorInformation : ProcessorInformationType Classification : ProductClassificationType ProductName : str ProductClass : str ProductType : str ProductCreationExtensions : ParametersCollection|dict kwargs",
"name": "__init__",
"signature": "def __init__(self, Proc... | 2 | null | Implement the Python class `ProductCreationType` described below.
Class description:
Contains general information about product creation.
Method signatures and docstrings:
- def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensi... | Implement the Python class `ProductCreationType` described below.
Class description:
Contains general information about product creation.
Method signatures and docstrings:
- def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensi... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class ProductCreationType:
"""Contains general information about product creation."""
def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensions=None, **kwargs):
"""Parameters ---------- ProcessorInfor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductCreationType:
"""Contains general information about product creation."""
def __init__(self, ProcessorInformation=None, Classification=None, ProductName=None, ProductClass=None, ProductType=None, ProductCreationExtensions=None, **kwargs):
"""Parameters ---------- ProcessorInformation : Proc... | the_stack_v2_python_sparse | sarpy/io/product/sidd2_elements/ProductCreation.py | ngageoint/sarpy | train | 192 |
aa14fc261b54db9a2ab6cd09c586f1dece3d837a | [
"assert isinstance(fraction, float) and fraction > 0.0\nself.fraction = fraction\nsuper(SubsamplingStep, self).__init__(optimizer=optimizer, scope=scope, summary_labels=summary_labels)",
"arguments_iter = iter(arguments.values())\nsome_argument = next(arguments_iter)\ntry:\n while not isinstance(some_argument,... | <|body_start_0|>
assert isinstance(fraction, float) and fraction > 0.0
self.fraction = fraction
super(SubsamplingStep, self).__init__(optimizer=optimizer, scope=scope, summary_labels=summary_labels)
<|end_body_0|>
<|body_start_1|>
arguments_iter = iter(arguments.values())
some_a... | The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer. | SubsamplingStep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubsamplingStep:
"""The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer."""
def __init__(self, optimizer, fraction=0.1, scope='subsampling-step', summary_labels=()):
"""Creates a new subsampling-step... | stack_v2_sparse_classes_36k_train_030640 | 4,026 | permissive | [
{
"docstring": "Creates a new subsampling-step meta optimizer instance. Args: optimizer: The optimizer which is modified by this meta optimizer. fraction: The fraction of instances of the batch to subsample.",
"name": "__init__",
"signature": "def __init__(self, optimizer, fraction=0.1, scope='subsampli... | 2 | stack_v2_sparse_classes_30k_val_000930 | Implement the Python class `SubsamplingStep` described below.
Class description:
The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer.
Method signatures and docstrings:
- def __init__(self, optimizer, fraction=0.1, scope='subsampling-... | Implement the Python class `SubsamplingStep` described below.
Class description:
The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer.
Method signatures and docstrings:
- def __init__(self, optimizer, fraction=0.1, scope='subsampling-... | afd56f7dc73cb7f21b4ea9b7a3cd85a1c3e5eeec | <|skeleton|>
class SubsamplingStep:
"""The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer."""
def __init__(self, optimizer, fraction=0.1, scope='subsampling-step', summary_labels=()):
"""Creates a new subsampling-step... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubsamplingStep:
"""The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate the optimization step of another optimizer."""
def __init__(self, optimizer, fraction=0.1, scope='subsampling-step', summary_labels=()):
"""Creates a new subsampling-step meta optimiz... | the_stack_v2_python_sparse | tensorforce/core/optimizers/subsampling_step.py | miskolc/tensorforce | train | 1 |
3894fc824c7d8eb33e9d6787fee7554c7e5b41c1 | [
"parser = parent.add_parser('create', help='create pod')\nsuper().subparser(parser)\nparser.add_argument('--cgroup-parent', dest='cgroupparent', type=str, help='Path to cgroups under which the cgroup for the pod will be created.')\nparser.add_flag('--infra', help='Create an infra container and associate it with the... | <|body_start_0|>
parser = parent.add_parser('create', help='create pod')
super().subparser(parser)
parser.add_argument('--cgroup-parent', dest='cgroupparent', type=str, help='Path to cgroups under which the cgroup for the pod will be created.')
parser.add_flag('--infra', help='Create an ... | Implement Create Pod command. | CreatePod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
<|body_0|>
def create(self):
"""Create Pod from given options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser = par... | stack_v2_sparse_classes_36k_train_030641 | 2,499 | permissive | [
{
"docstring": "Add Pod Create command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Create Pod from given options.",
"name": "create",
"signature": "def create(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000518 | Implement the Python class `CreatePod` described below.
Class description:
Implement Create Pod command.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Create command to parent parser.
- def create(self): Create Pod from given options. | Implement the Python class `CreatePod` described below.
Class description:
Implement Create Pod command.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Create command to parent parser.
- def create(self): Create Pod from given options.
<|skeleton|>
class CreatePod:
"""Implement Create Po... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
<|body_0|>
def create(self):
"""Create Pod from given options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
parser = parent.add_parser('create', help='create pod')
super().subparser(parser)
parser.add_argument('--cgroup-parent', dest='cgroupparent', type=str,... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/pod/create_parser.py | 4383/python-podman | train | 0 |
ebe34b5ef54df06e32fc428ca137f24d7da63308 | [
"client = Http_client()\nclient.get(url=url, params=jsondata, header=headers)\nassert client.status_code == checkpoint['status_code']\nassert len(client.jsonResponse['data']) == checkpoint['data']\nassert client.elapsed <= 20.0",
"client = Http_client()\nclient.get(url=url, params=eval(jsondata), header=headers)\... | <|body_start_0|>
client = Http_client()
client.get(url=url, params=jsondata, header=headers)
assert client.status_code == checkpoint['status_code']
assert len(client.jsonResponse['data']) == checkpoint['data']
assert client.elapsed <= 20.0
<|end_body_0|>
<|body_start_1|>
... | Test_GetAllStrategyInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_GetAllStrategyInfo_name_mode200(self, url, jsondata, headers, check... | stack_v2_sparse_classes_36k_train_030642 | 5,553 | no_license | [
{
"docstring": "用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查",
"name": "test_GetAllStrategyInfo200",
"signature": "def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint)"
},
{
"docstring": "用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json... | 4 | stack_v2_sparse_classes_30k_train_011056 | Implement the Python class `Test_GetAllStrategyInfo` described below.
Class description:
Implement the Test_GetAllStrategyInfo class.
Method signatures and docstrings:
- def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint): 用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不... | Implement the Python class `Test_GetAllStrategyInfo` described below.
Class description:
Implement the Test_GetAllStrategyInfo class.
Method signatures and docstrings:
- def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint): 用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不... | ab922c82c2454a3397ddbf4cd0771067734e1111 | <|skeleton|>
class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_GetAllStrategyInfo_name_mode200(self, url, jsondata, headers, check... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
client = Http_client()
client.get(url=url, params=jsondata, header=headers)
assert client.... | the_stack_v2_python_sparse | Case/AS/Http/DocPolicyMgnt/test_GetAllStrategyInfo.py | GWenPeng/Apitest_framework | train | 0 | |
9bb59affcaf8b62f0459e74e07a828cac9e0da3a | [
"try:\n import puremagic\n clazz._log.log_d(f'\"import puremagic\" succeeds')\n return True\nexcept ModuleNotFoundError as ex:\n clazz._log.log_d(f'puremagic module not found')\n pass\nreturn False",
"filename = bf_check.check_file(filename)\nimport puremagic\ntry:\n rv = puremagic.magic_file(fi... | <|body_start_0|>
try:
import puremagic
clazz._log.log_d(f'"import puremagic" succeeds')
return True
except ModuleNotFoundError as ex:
clazz._log.log_d(f'puremagic module not found')
pass
return False
<|end_body_0|>
<|body_start_1|>
... | _bf_mime_type_detector_puremagic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz, ... | stack_v2_sparse_classes_36k_train_030643 | 1,494 | permissive | [
{
"docstring": "Return True if this class is supported on the current platform.",
"name": "is_supported",
"signature": "def is_supported(clazz)"
},
{
"docstring": "Detect the mime type for file.",
"name": "detect_mime_type",
"signature": "def detect_mime_type(clazz, filename)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_017037 | Implement the Python class `_bf_mime_type_detector_puremagic` described below.
Class description:
Implement the _bf_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): ... | Implement the Python class `_bf_mime_type_detector_puremagic` described below.
Class description:
Implement the _bf_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): ... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
try:
import puremagic
clazz._log.log_d(f'"import puremagic" succeeds')
return True
except ModuleNotFoundError as ex:
... | the_stack_v2_python_sparse | lib/bes/files/mime/_detail/_bf_mime_type_detector_puremagic.py | reconstruir/bes | train | 0 | |
44aeb635127e158c8f7626e8a91a5badd0892409 | [
"self.type = 'cch' if 'c1' in dict else 'hch'\nself.c1 = float(dict['c1']) if self.type == 'cch' else 0.0\nself.h1 = float(dict['h1']) if self.type == 'hch' else 0.0\nself.c2 = float(dict['c2'])\nself.h2 = float(dict['h2'])\nself.intensity = float(dict['intensity'])",
"assert self.type == other.type\nif self.type... | <|body_start_0|>
self.type = 'cch' if 'c1' in dict else 'hch'
self.c1 = float(dict['c1']) if self.type == 'cch' else 0.0
self.h1 = float(dict['h1']) if self.type == 'hch' else 0.0
self.c2 = float(dict['c2'])
self.h2 = float(dict['h2'])
self.intensity = float(dict['intensi... | Class for storing peaks so that we can eliminate duplicates using a connected component algorithm | Peak | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Peak:
"""Class for storing peaks so that we can eliminate duplicates using a connected component algorithm"""
def __init__(self, dict):
"""Construct from dictionary"""
<|body_0|>
def connected(self, other, ctol, htol):
"""Determine if these are close enough in sp... | stack_v2_sparse_classes_36k_train_030644 | 4,828 | no_license | [
{
"docstring": "Construct from dictionary",
"name": "__init__",
"signature": "def __init__(self, dict)"
},
{
"docstring": "Determine if these are close enough in space to be connected",
"name": "connected",
"signature": "def connected(self, other, ctol, htol)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006387 | Implement the Python class `Peak` described below.
Class description:
Class for storing peaks so that we can eliminate duplicates using a connected component algorithm
Method signatures and docstrings:
- def __init__(self, dict): Construct from dictionary
- def connected(self, other, ctol, htol): Determine if these a... | Implement the Python class `Peak` described below.
Class description:
Class for storing peaks so that we can eliminate duplicates using a connected component algorithm
Method signatures and docstrings:
- def __init__(self, dict): Construct from dictionary
- def connected(self, other, ctol, htol): Determine if these a... | a34db94ca47e1a3afe9c73889b73ca37f8f97b3d | <|skeleton|>
class Peak:
"""Class for storing peaks so that we can eliminate duplicates using a connected component algorithm"""
def __init__(self, dict):
"""Construct from dictionary"""
<|body_0|>
def connected(self, other, ctol, htol):
"""Determine if these are close enough in sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Peak:
"""Class for storing peaks so that we can eliminate duplicates using a connected component algorithm"""
def __init__(self, dict):
"""Construct from dictionary"""
self.type = 'cch' if 'c1' in dict else 'hch'
self.c1 = float(dict['c1']) if self.type == 'cch' else 0.0
s... | the_stack_v2_python_sparse | scripts/pipe2meth.py | bcsherma/camera | train | 0 |
35cfa53256eefca2ed5e0c4429c1ae4275be0a24 | [
"rows, cols = (len(board), len(board[0]))\ndp = [0] * (cols + 1)\nmax_len = prev = 0\nfor row in range(1, rows + 1):\n for col in range(1, cols + 1):\n temp = dp[col]\n if board[row - 1][col - 1] == '1':\n dp[col] = min(min(dp[col], prev), dp[col - 1]) + 1\n max_len = max(max_... | <|body_start_0|>
rows, cols = (len(board), len(board[0]))
dp = [0] * (cols + 1)
max_len = prev = 0
for row in range(1, rows + 1):
for col in range(1, cols + 1):
temp = dp[col]
if board[row - 1][col - 1] == '1':
dp[col] = min... | Square | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
<|body_0|>
def maximal_area(self, board: List[List[int]]) -> int:
"""Approach: DP (2D Array) Time Comple... | stack_v2_sparse_classes_36k_train_030645 | 1,900 | no_license | [
{
"docstring": "Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:",
"name": "maximal_area_",
"signature": "def maximal_area_(self, board: List[List[int]]) -> int"
},
{
"docstring": "Approach: DP (2D Array) Time Complexity: O(MN) Space Complexity: O(MN) ... | 2 | null | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def maximal_area_(self, board: List[List[int]]) -> int: Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:
- def maximal_area(self, board: L... | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def maximal_area_(self, board: List[List[int]]) -> int: Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:
- def maximal_area(self, board: L... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
<|body_0|>
def maximal_area(self, board: List[List[int]]) -> int:
"""Approach: DP (2D Array) Time Comple... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
rows, cols = (len(board), len(board[0]))
dp = [0] * (cols + 1)
max_len = prev = 0
for row in range(1, rows ... | the_stack_v2_python_sparse | amazon/dynamic_programming/maximal_square.py | Shiv2157k/leet_code | train | 1 | |
128bc6d37f288a77ec7a17c7877c1157ec936faa | [
"super().__init__()\nself.margin = margin\nself.reduction = reduction or 'none'",
"bs = len(distance_true)\nmargin_distance = self.margin - distance_pred\nmargin_distance = torch.clamp(margin_distance, min=0.0)\nloss = (1 - distance_true) * torch.pow(distance_pred, 2) + distance_true * torch.pow(margin_distance, ... | <|body_start_0|>
super().__init__()
self.margin = margin
self.reduction = reduction or 'none'
<|end_body_0|>
<|body_start_1|>
bs = len(distance_true)
margin_distance = self.margin - distance_pred
margin_distance = torch.clamp(margin_distance, min=0.0)
loss = (1 -... | The Contrastive distance loss. @TODO: Docs. Contribution is welcome. | ContrastiveDistanceLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type"""
<|body_0|>
def forward(self, distance_pred, dist... | stack_v2_sparse_classes_36k_train_030646 | 7,661 | permissive | [
{
"docstring": "Args: margin: margin parameter reduction: criterion reduction type",
"name": "__init__",
"signature": "def __init__(self, margin=1.0, reduction='mean')"
},
{
"docstring": "Forward propagation method for the contrastive loss. Args: distance_pred: predicted distances distance_true:... | 2 | stack_v2_sparse_classes_30k_train_019291 | Implement the Python class `ContrastiveDistanceLoss` described below.
Class description:
The Contrastive distance loss. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: margin: margin parameter reduction: criterion reduction type
- def f... | Implement the Python class `ContrastiveDistanceLoss` described below.
Class description:
The Contrastive distance loss. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: margin: margin parameter reduction: criterion reduction type
- def f... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type"""
<|body_0|>
def forward(self, distance_pred, dist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContrastiveDistanceLoss:
"""The Contrastive distance loss. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type"""
super().__init__()
self.margin = margin
self.reduc... | the_stack_v2_python_sparse | catalyst/contrib/losses/contrastive.py | catalyst-team/catalyst | train | 3,038 |
a20ccf251dcb4b1a894f184ff281d8a7f7eaffca | [
"if k == 0:\n soln = [[]]\nelif k == 1:\n soln = [[i] for i in nums]\nelif len(nums) - k == 0:\n soln = [nums]\nelse:\n soln = self.combine(nums[:-1], k)\n below = self.combine(nums[:-1], k - 1)\n for b in below:\n if b:\n b.append(nums[-1])\n soln.append(b)\nreturn so... | <|body_start_0|>
if k == 0:
soln = [[]]
elif k == 1:
soln = [[i] for i in nums]
elif len(nums) - k == 0:
soln = [nums]
else:
soln = self.combine(nums[:-1], k)
below = self.combine(nums[:-1], k - 1)
for b in below:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combine(self, nums, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if k == 0:
... | stack_v2_sparse_classes_36k_train_030647 | 855 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine",
"signature": "def combine(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000327 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, nums, k): :type n: int :type k: int :rtype: List[List[int]]
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, nums, k): :type n: int :type k: int :rtype: List[List[int]]
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solutio... | 6e4129d7c092be933497da2156680d25f72e42a4 | <|skeleton|>
class Solution:
def combine(self, nums, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combine(self, nums, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
if k == 0:
soln = [[]]
elif k == 1:
soln = [[i] for i in nums]
elif len(nums) - k == 0:
soln = [nums]
else:
soln = self.combine(... | the_stack_v2_python_sparse | 078_subsets.py | setu4993/LeetCode | train | 0 | |
160262b25931bd41fe484fc6689929c70b834ef1 | [
"n = len(height)\nmax_area = 0\nfor i in range(n - 1):\n for j in range(i + 1, n):\n area = (j - i) * min(height[i], height[j])\n max_area = max(area, max_area)\nreturn max_area",
"i, j = (0, len(height) - 1)\nmax_area = 0\nwhile i < j:\n if height[i] < height[j]:\n min_height = height[... | <|body_start_0|>
n = len(height)
max_area = 0
for i in range(n - 1):
for j in range(i + 1, n):
area = (j - i) * min(height[i], height[j])
max_area = max(area, max_area)
return max_area
<|end_body_0|>
<|body_start_1|>
i, j = (0, len(hei... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_1(self, height: List[int]) -> int:
"""1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)"""
<|body_0|>
def maxArea(self, height: List[int]) -> int:
"""2. 双指针 i、j,分别指向首尾,都向中间靠近。 原理:循环时宽总在减少;改变 i、j 中较大者,最终高不变或减小,面积总减小; 改变较小者,高可能增大,面积才可能增大;所以优先改变较小者。 复杂度:时间 O(n) 空间... | stack_v2_sparse_classes_36k_train_030648 | 2,150 | no_license | [
{
"docstring": "1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)",
"name": "maxArea_1",
"signature": "def maxArea_1(self, height: List[int]) -> int"
},
{
"docstring": "2. 双指针 i、j,分别指向首尾,都向中间靠近。 原理:循环时宽总在减少;改变 i、j 中较大者,最终高不变或减小,面积总减小; 改变较小者,高可能增大,面积才可能增大;所以优先改变较小者。 复杂度:时间 O(n) 空间 O(1)",
"name": "maxArea",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_1(self, height: List[int]) -> int: 1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)
- def maxArea(self, height: List[int]) -> int: 2. 双指针 i、j,分别指向首尾,都向中间靠近。 原理:循环时宽总在减少;改变 i、j 中较大者,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_1(self, height: List[int]) -> int: 1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)
- def maxArea(self, height: List[int]) -> int: 2. 双指针 i、j,分别指向首尾,都向中间靠近。 原理:循环时宽总在减少;改变 i、j 中较大者,... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def maxArea_1(self, height: List[int]) -> int:
"""1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)"""
<|body_0|>
def maxArea(self, height: List[int]) -> int:
"""2. 双指针 i、j,分别指向首尾,都向中间靠近。 原理:循环时宽总在减少;改变 i、j 中较大者,最终高不变或减小,面积总减小; 改变较小者,高可能增大,面积才可能增大;所以优先改变较小者。 复杂度:时间 O(n) 空间... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea_1(self, height: List[int]) -> int:
"""1. 暴力法,两层循环 复杂度:时间 O(n^2) 空间 O(1)"""
n = len(height)
max_area = 0
for i in range(n - 1):
for j in range(i + 1, n):
area = (j - i) * min(height[i], height[j])
max_area = max(a... | the_stack_v2_python_sparse | 01-array/11.盛最多水的容器.py | xiaoruijiang/algorithm | train | 0 | |
05d0a6fd9c981c37a461a33e67c09f1bd713475d | [
"user = self.request.user\nqueryset = self.queryset.filter(pk=user.pk)\nreturn queryset",
"try:\n account = self.get_queryset().get()\nexcept Exception:\n return Response(status=status.HTTP_404_NOT_FOUND)\nserializer = self.get_serializer(account)\nreturn Response(serializer.data)"
] | <|body_start_0|>
user = self.request.user
queryset = self.queryset.filter(pk=user.pk)
return queryset
<|end_body_0|>
<|body_start_1|>
try:
account = self.get_queryset().get()
except Exception:
return Response(status=status.HTTP_404_NOT_FOUND)
seri... | AccountView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountView:
def get_queryset(self):
"""Filter account by user pk :return: queryset"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()"""
<|b... | stack_v2_sparse_classes_36k_train_030649 | 4,771 | no_license | [
{
"docstring": "Filter account by user pk :return: queryset",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()",
"name": "list",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_007923 | Implement the Python class `AccountView` described below.
Class description:
Implement the AccountView class.
Method signatures and docstrings:
- def get_queryset(self): Filter account by user pk :return: queryset
- def list(self, request, *args, **kwargs): Redeclared list method to return one instance :param request... | Implement the Python class `AccountView` described below.
Class description:
Implement the AccountView class.
Method signatures and docstrings:
- def get_queryset(self): Filter account by user pk :return: queryset
- def list(self, request, *args, **kwargs): Redeclared list method to return one instance :param request... | 0e3e755d49b284eb3e7ec2c2f8542d013d313abd | <|skeleton|>
class AccountView:
def get_queryset(self):
"""Filter account by user pk :return: queryset"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""Redeclared list method to return one instance :param request: :param args: :param kwargs: :return: Response()"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountView:
def get_queryset(self):
"""Filter account by user pk :return: queryset"""
user = self.request.user
queryset = self.queryset.filter(pk=user.pk)
return queryset
def list(self, request, *args, **kwargs):
"""Redeclared list method to return one instance :p... | the_stack_v2_python_sparse | grc_account/views.py | kolexander/common | train | 0 | |
65d32b24360987dc07225a4d1a2c127bb8ab0486 | [
"self.config = config\nself.cookie = cookie\nself.quotas = quotas",
"if dictionary is None:\n return None\nconfig = cohesity_management_sdk.models.dir_quota_config.DirQuotaConfig.from_dictionary(dictionary.get('config')) if dictionary.get('config') else None\ncookie = dictionary.get('cookie')\nquotas = None\ni... | <|body_start_0|>
self.config = config
self.cookie = cookie
self.quotas = quotas
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
config = cohesity_management_sdk.models.dir_quota_config.DirQuotaConfig.from_dictionary(dictionary.get('config')) if dic... | Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be used in the succeeding call to list user quotas and usages to get the next set... | DirQuotaInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirQuotaInfo:
"""Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be used in the succeeding call to list us... | stack_v2_sparse_classes_36k_train_030650 | 2,492 | permissive | [
{
"docstring": "Constructor for the DirQuotaInfo class",
"name": "__init__",
"signature": "def __init__(self, config=None, cookie=None, quotas=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as... | 2 | null | Implement the Python class `DirQuotaInfo` described below.
Class description:
Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be... | Implement the Python class `DirQuotaInfo` described below.
Class description:
Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DirQuotaInfo:
"""Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be used in the succeeding call to list us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirQuotaInfo:
"""Implementation of the 'DirQuotaInfo' model. Specifies the configuration and policy details for directory quota in a view. Attributes: config (DirQuotaConfig): Specifies the directory quota configuration. cookie (long|int): This cookie can be used in the succeeding call to list user quotas and... | the_stack_v2_python_sparse | cohesity_management_sdk/models/dir_quota_info.py | cohesity/management-sdk-python | train | 24 |
a857f8260317dfbd401fc19aa00ec30559a4fb1a | [
"packet = packets.TeltonikaConfiguration()\npacket.packetId = 1\npacket.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)\npacket.addParam(packets.CFG_SORTING, packets.CFG_SORTING_ASC)\npacket.addParam(packets.CFG_ACTIVE_DATA_LINK_TIMEOUT, 20)\npacket.addParam(packets.CFG_TARGET_SERVER_IP_ADDRESS, config['host'])\npacket.ad... | <|body_start_0|>
packet = packets.TeltonikaConfiguration()
packet.packetId = 1
packet.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)
packet.addParam(packets.CFG_SORTING, packets.CFG_SORTING_ASC)
packet.addParam(packets.CFG_ACTIVE_DATA_LINK_TIMEOUT, 20)
packet.addParam(packets.C... | TeltonkaCommandConfigure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
<|body_0|>
def getInitiationSmsBuffer(self, data):
"""Returns initiation sms buffer @param data: dict @return:"""
... | stack_v2_sparse_classes_36k_train_030651 | 7,719 | no_license | [
{
"docstring": "Returns Teltonika configuration packet @param config: config dict @return:",
"name": "getConfigurationPacket",
"signature": "def getConfigurationPacket(self, config)"
},
{
"docstring": "Returns initiation sms buffer @param data: dict @return:",
"name": "getInitiationSmsBuffer... | 6 | stack_v2_sparse_classes_30k_val_000438 | Implement the Python class `TeltonkaCommandConfigure` described below.
Class description:
Implement the TeltonkaCommandConfigure class.
Method signatures and docstrings:
- def getConfigurationPacket(self, config): Returns Teltonika configuration packet @param config: config dict @return:
- def getInitiationSmsBuffer(... | Implement the Python class `TeltonkaCommandConfigure` described below.
Class description:
Implement the TeltonkaCommandConfigure class.
Method signatures and docstrings:
- def getConfigurationPacket(self, config): Returns Teltonika configuration packet @param config: config dict @return:
- def getInitiationSmsBuffer(... | 4a4bc730252ece695b2773388812e2d59d4947ce | <|skeleton|>
class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
<|body_0|>
def getInitiationSmsBuffer(self, data):
"""Returns initiation sms buffer @param data: dict @return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeltonkaCommandConfigure:
def getConfigurationPacket(self, config):
"""Returns Teltonika configuration packet @param config: config dict @return:"""
packet = packets.TeltonikaConfiguration()
packet.packetId = 1
packet.addParam(packets.CFG_DEEP_SLEEP_MODE, 0)
packet.addP... | the_stack_v2_python_sparse | lib/handlers/teltonika/commands.py | maprox/pipe | train | 4 | |
95bb6c9dd3797fa7bf14c8f37551e0be6bcd3d3b | [
"ret = {}\nfor key in reversed(self):\n for unused_config_dir, config in reversed(self[key]):\n ret = OverrideConfig(ret, config)\nreturn ret",
"depends = []\nfor config_name in self:\n for config_dir, unused_config in self[config_name]:\n depends.append(os.path.join(config_dir, config_name + ... | <|body_start_0|>
ret = {}
for key in reversed(self):
for unused_config_dir, config in reversed(self[key]):
ret = OverrideConfig(ret, config)
return ret
<|end_body_0|>
<|body_start_1|>
depends = []
for config_name in self:
for config_dir, u... | Internal structure to store a list of raw configs. | _ConfigList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ConfigList:
"""Internal structure to store a list of raw configs."""
def Resolve(self):
"""Returns the final config after overriding."""
<|body_0|>
def CollectDepend(self):
"""Returns a list of all files loaded for this config list. Returns: a list of paths (str... | stack_v2_sparse_classes_36k_train_030652 | 23,547 | permissive | [
{
"docstring": "Returns the final config after overriding.",
"name": "Resolve",
"signature": "def Resolve(self)"
},
{
"docstring": "Returns a list of all files loaded for this config list. Returns: a list of paths (strings).",
"name": "CollectDepend",
"signature": "def CollectDepend(self... | 2 | null | Implement the Python class `_ConfigList` described below.
Class description:
Internal structure to store a list of raw configs.
Method signatures and docstrings:
- def Resolve(self): Returns the final config after overriding.
- def CollectDepend(self): Returns a list of all files loaded for this config list. Returns:... | Implement the Python class `_ConfigList` described below.
Class description:
Internal structure to store a list of raw configs.
Method signatures and docstrings:
- def Resolve(self): Returns the final config after overriding.
- def CollectDepend(self): Returns a list of all files loaded for this config list. Returns:... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class _ConfigList:
"""Internal structure to store a list of raw configs."""
def Resolve(self):
"""Returns the final config after overriding."""
<|body_0|>
def CollectDepend(self):
"""Returns a list of all files loaded for this config list. Returns: a list of paths (str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ConfigList:
"""Internal structure to store a list of raw configs."""
def Resolve(self):
"""Returns the final config after overriding."""
ret = {}
for key in reversed(self):
for unused_config_dir, config in reversed(self[key]):
ret = OverrideConfig(ret,... | the_stack_v2_python_sparse | py/utils/config_utils.py | bridder/factory | train | 0 |
b48f08a232b888de8ca7e2fb35cc77b28cc07676 | [
"self.dbid = dbid\nself.name = name\nself.owner = owner\nself.estateId = estateId\nself.productType = productType\nself.xloc = xloc\nself.yloc = yloc\nself.hostResource = hostResource\nself.state = state\nself.dbConfig = None",
"cnx = mysql.connector.connect(**dbconfig)\ncursor = cnx.cursor()\nfindHostedRegionsSq... | <|body_start_0|>
self.dbid = dbid
self.name = name
self.owner = owner
self.estateId = estateId
self.productType = productType
self.xloc = xloc
self.yloc = yloc
self.hostResource = hostResource
self.state = state
self.dbConfig = None
<|end_b... | Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region | RegionEntry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionEntry:
"""Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region"""
def __init__(self, dbid, name, owner, estateId, productType, xloc, yloc, hostResource, state):
"""Constructor"""
... | stack_v2_sparse_classes_36k_train_030653 | 3,939 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, dbid, name, owner, estateId, productType, xloc, yloc, hostResource, state)"
},
{
"docstring": "Uses the given resource ID to find all regions associated with it",
"name": "findRegionsAssignedToResource",
"... | 5 | stack_v2_sparse_classes_30k_train_015109 | Implement the Python class `RegionEntry` described below.
Class description:
Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region
Method signatures and docstrings:
- def __init__(self, dbid, name, owner, estateId, productType, ... | Implement the Python class `RegionEntry` described below.
Class description:
Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region
Method signatures and docstrings:
- def __init__(self, dbid, name, owner, estateId, productType, ... | ae3965d61c79985adb03c72be2a744c70a677bf5 | <|skeleton|>
class RegionEntry:
"""Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region"""
def __init__(self, dbid, name, owner, estateId, productType, xloc, yloc, hostResource, state):
"""Constructor"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegionEntry:
"""Represents a region entry in the maestro environment database. The presence of this information means that maestro expects to manage the region"""
def __init__(self, dbid, name, owner, estateId, productType, xloc, yloc, hostResource, state):
"""Constructor"""
self.dbid = d... | the_stack_v2_python_sparse | src/inworldz/maestro/environment/RegionEntry.py | mdickson/maestro | train | 0 |
52d2439979024932501afd97dcac96c9281b62d9 | [
"LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')\nresult = self.cytoband_collection.insert_many(cytobands)\nLOG.debug(f'Number of inserted documents:{len(result.inserted_ids)}')",
"if '38' in str(build):\n build = '38'\nelse:\n build = '37'\nmatch = {'$match': {'build': build}}\ngr... | <|body_start_0|>
LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')
result = self.cytoband_collection.insert_many(cytobands)
LOG.debug(f'Number of inserted documents:{len(result.inserted_ids)}')
<|end_body_0|>
<|body_start_1|>
if '38' in str(build):
bu... | Class to handle cytoband-related entries | CytobandHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
<|body_0|>
def cytoband_by_chrom(self, build='37'):
"""Returns... | stack_v2_sparse_classes_36k_train_030654 | 2,082 | permissive | [
{
"docstring": "Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects",
"name": "add_cytobands",
"signature": "def add_cytobands(self, cytobands)"
},
{
"docstring": "Returns a dictionary of cytobands with chromosomes as keys Args: build(str): \"37\" or \"... | 2 | stack_v2_sparse_classes_30k_train_012817 | Implement the Python class `CytobandHandler` described below.
Class description:
Class to handle cytoband-related entries
Method signatures and docstrings:
- def add_cytobands(self, cytobands): Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects
- def cytoband_by_chrom(self,... | Implement the Python class `CytobandHandler` described below.
Class description:
Class to handle cytoband-related entries
Method signatures and docstrings:
- def add_cytobands(self, cytobands): Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects
- def cytoband_by_chrom(self,... | 1e6a633ba0a83495047ee7b66db1ebf690ee465f | <|skeleton|>
class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
<|body_0|>
def cytoband_by_chrom(self, build='37'):
"""Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CytobandHandler:
"""Class to handle cytoband-related entries"""
def add_cytobands(self, cytobands):
"""Adds a list of cytoband objects to database Args: cytobands(list): a list of cytobands objects"""
LOG.debug(f'Inserting {len(cytobands)} cytoband intervals into database')
result... | the_stack_v2_python_sparse | scout/adapter/mongo/cytoband.py | Clinical-Genomics/scout | train | 143 |
60a03e5b5fe81c9dc1e08ca8ed48f6f3e3442d15 | [
"Analyzer.__init__(self, name, outQueue, config_dict, number)\nself.inEventQueue = inEventQueue\nself.inEventQueue.register_listener_method(self.notifyFromEventQ)\nself.inAlertQueue = inAlertQueue\nself.inAlertQueue.register_listener_method(self.notifyFromAlertQ)\nreturn",
"get_logger().debug('notifyFromEventQ ca... | <|body_start_0|>
Analyzer.__init__(self, name, outQueue, config_dict, number)
self.inEventQueue = inEventQueue
self.inEventQueue.register_listener_method(self.notifyFromEventQ)
self.inAlertQueue = inAlertQueue
self.inAlertQueue.register_listener_method(self.notifyFromAlertQ)
... | The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised. | AlertAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertAnalyzer:
"""The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised."""
def __init__(self, name, inEventQueue, inAlertQueue, outQueue, config_dict=None, number=0):
"""The constructor. name -- name of the analy... | stack_v2_sparse_classes_36k_train_030655 | 24,649 | no_license | [
{
"docstring": "The constructor. name -- name of the analyzer inQueue -- queue to listen to to get input from outQueue -- queue to send any alerts that are produced config_dict -- dictionary of configuration information (from config file) asynch -- should the analyzer run asynchronously",
"name": "__init__"... | 4 | null | Implement the Python class `AlertAnalyzer` described below.
Class description:
The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised.
Method signatures and docstrings:
- def __init__(self, name, inEventQueue, inAlertQueue, outQueue, config_dict=No... | Implement the Python class `AlertAnalyzer` described below.
Class description:
The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised.
Method signatures and docstrings:
- def __init__(self, name, inEventQueue, inAlertQueue, outQueue, config_dict=No... | eba6c1489b503fdcf040a126942643b355867bcd | <|skeleton|>
class AlertAnalyzer:
"""The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised."""
def __init__(self, name, inEventQueue, inAlertQueue, outQueue, config_dict=None, number=0):
"""The constructor. name -- name of the analy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlertAnalyzer:
"""The Analyzer class is the base class for modules that analyze events and/or alerts to determine if an alert should be raised."""
def __init__(self, name, inEventQueue, inAlertQueue, outQueue, config_dict=None, number=0):
"""The constructor. name -- name of the analyzer inQueue -... | the_stack_v2_python_sparse | src/ibm/teal/analyzer/analyzer.py | ppjsand/pyteal | train | 1 |
6cee6e2dbd7c9ee92196600fdd346f6b3afa8580 | [
"if file_resources is None:\n file_resources = {}\n file_resources['GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz'] = 'GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz'\n file_resources['GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt'] = 'https://storage.googleapis.c... | <|body_start_0|>
if file_resources is None:
file_resources = {}
file_resources['GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz'] = 'GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz'
file_resources['GTEx_Analysis_v8_Annotations_SampleAttribute... | Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz", "GTEx_Analysis_v8_Anno... | GTEx | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTEx:
"""Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm... | stack_v2_sparse_classes_36k_train_030656 | 19,914 | permissive | [
{
"docstring": "Args: path: file_resources: col_rename: blocksize: verbose:",
"name": "__init__",
"signature": "def __init__(self, path='https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/', file_resources=None, col_rename=None, blocksize=0, verbose=False, **kwargs)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_021441 | Implement the Python class `GTEx` described below.
Class description:
Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017... | Implement the Python class `GTEx` described below.
Class description:
Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017... | 35a0e00964c9b308f831263936f9507a69f52613 | <|skeleton|>
class GTEx:
"""Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GTEx:
"""Loads the database from https://www.gtexportal.org/home/ . Default path: "https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/" . Default file_resources: { "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct": "GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_median_tpm.gct.gz", "GT... | the_stack_v2_python_sparse | openomics/database/annotation.py | JonnyTran/OpenOmics | train | 8 |
13ca2ab3f3c99398ff018f03bb09bbded209500a | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('medinad', 'medinad')\napp1 = repo.medinad.app\ntickets = repo.medinad.tickets\n\ndef product(R, S):\n return [(t, u) for t in R for u in S]\n\ndef project(R, p):\n return [p(t) for t in R]\napp1_li... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('medinad', 'medinad')
app1 = repo.medinad.app
tickets = repo.medinad.tickets
def product(R, S):
return [(t, u) for t in R for ... | apptickets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class apptickets:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k_train_030657 | 5,306 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_008367 | Implement the Python class `apptickets` described below.
Class description:
Implement the apptickets class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | Implement the Python class `apptickets` described below.
Class description:
Implement the apptickets class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class apptickets:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class apptickets:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('medinad', 'medinad')
app1 = repo... | the_stack_v2_python_sparse | jtbloom_rfballes_medinad/medinad/apptickets.py | ROODAY/course-2017-fal-proj | train | 3 | |
7fbb463e4bb3a49eae4d633c246a094666ce1add | [
"self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price",
"output_dict = {}\noutput_dict['productCode'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['marketPrice'] = self.market_price\noutput_dict['ren... | <|body_start_0|>
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['productCode'] = self.product_code
output_dict['descrip... | Invetory class definiton | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""... | stack_v2_sparse_classes_36k_train_030658 | 1,035 | no_license | [
{
"docstring": ":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_003220 | Implement the Python class `Inventory` described below.
Class description:
Invetory class definiton
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): :param product_code: :type product_code: :param description: :type description: :param market_price: :type ... | Implement the Python class `Inventory` described below.
Class description:
Invetory class definiton
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): :param product_code: :type product_code: :param description: :type description: :param market_price: :type ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""
self... | the_stack_v2_python_sparse | students/vmedina/lesson_01/inventory_management/inventory_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
fcbce779d3c41f1629f52901ea12afafafcf35c4 | [
"decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, auth=admin_sdk.auth)\nuser_record = UserRecord.get_user(decoded_token['uid'], auth=admin_sdk.auth)\nif user_record.disabled:\n raise HandlerException(401, 'Account disabled')\nclaims = user_record.custom_claims\nif not claims or 'admin' no... | <|body_start_0|>
decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, auth=admin_sdk.auth)
user_record = UserRecord.get_user(decoded_token['uid'], auth=admin_sdk.auth)
if user_record.disabled:
raise HandlerException(401, 'Account disabled')
claims = user_r... | Service Auth Admin | AuthAdminService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthAdminService:
"""Service Auth Admin"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin"""
<|body_0|>
def create(self, body):
"""Create adm... | stack_v2_sparse_classes_36k_train_030659 | 6,454 | no_license | [
{
"docstring": "Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin",
"name": "authentication",
"signature": "def authentication(self, id_token)"
},
{
"docstring": "Create admin user account Args: body (dict): email (s... | 6 | null | Implement the Python class `AuthAdminService` described below.
Class description:
Service Auth Admin
Method signatures and docstrings:
- def authentication(self, id_token): Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin
- def create(se... | Implement the Python class `AuthAdminService` described below.
Class description:
Service Auth Admin
Method signatures and docstrings:
- def authentication(self, id_token): Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin
- def create(se... | 828cb0109415b293a38f5c8ea6c11ce4a469a8ea | <|skeleton|>
class AuthAdminService:
"""Service Auth Admin"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin"""
<|body_0|>
def create(self, body):
"""Create adm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthAdminService:
"""Service Auth Admin"""
def authentication(self, id_token):
"""Authentcation Args: id_token (str): id token session Returns: dict uid (str): User uid a (UserRecord): UserRecord b (User): Admin"""
decoded_token = UserRecord.verify_id_token(id_token, check_revoked=True, a... | the_stack_v2_python_sparse | src/services/auth_admin.py | andresbermeoq/server | train | 0 |
656622f471827d17677296e50835769e5d77a62f | [
"if field == 'current_password':\n if current_user.password != value and obj.password != value:\n abort(code=HTTPStatus.FORBIDDEN, message='Wrong password')\n else:\n state['current_password'] = value\n return True\nreturn PatchJSONParameters.test(obj, field, value, state)",
"log.debug(... | <|body_start_0|>
if field == 'current_password':
if current_user.password != value and obj.password != value:
abort(code=HTTPStatus.FORBIDDEN, message='Wrong password')
else:
state['current_password'] = value
return True
return Patc... | User details updating parameters following PATCH JSON RFC. | PatchUserDetailsParameters | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
<|body_0|>
def replace(cls, obj, field, value, stat... | stack_v2_sparse_classes_36k_train_030660 | 6,997 | permissive | [
{
"docstring": "Additional check for 'current_password' as User hasn't field 'current_password'",
"name": "test",
"signature": "def test(cls, obj, field, value, state)"
},
{
"docstring": "Some fields require extra permissions to be changed. Changing `is_active` and `is_staff` properties, current... | 2 | stack_v2_sparse_classes_30k_train_008751 | Implement the Python class `PatchUserDetailsParameters` described below.
Class description:
User details updating parameters following PATCH JSON RFC.
Method signatures and docstrings:
- def test(cls, obj, field, value, state): Additional check for 'current_password' as User hasn't field 'current_password'
- def repl... | Implement the Python class `PatchUserDetailsParameters` described below.
Class description:
User details updating parameters following PATCH JSON RFC.
Method signatures and docstrings:
- def test(cls, obj, field, value, state): Additional check for 'current_password' as User hasn't field 'current_password'
- def repl... | 821c9cae985751a129b3be1ad08b8ad295d0a3d8 | <|skeleton|>
class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
<|body_0|>
def replace(cls, obj, field, value, stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatchUserDetailsParameters:
"""User details updating parameters following PATCH JSON RFC."""
def test(cls, obj, field, value, state):
"""Additional check for 'current_password' as User hasn't field 'current_password'"""
if field == 'current_password':
if current_user.password ... | the_stack_v2_python_sparse | app/modules/users/parameters.py | Emily-Ke/houston | train | 0 |
9ca3adf43bd6d398de39d4cb662a00b5b7c5ed07 | [
"super().__init__(model, params)\nself._var_scope = 'encoder'\nself._lambda_end_d = 1.0\nself._n_classes = 0\nself._n_latent_dim = 16\nif 'n_classes' in params.keys():\n self._n_classes = params['n_classes']\nif 'lambda_d' in params.keys():\n self._lambda_enc_d = params['lambda_d']\nif 'latent_dim' in params.... | <|body_start_0|>
super().__init__(model, params)
self._var_scope = 'encoder'
self._lambda_end_d = 1.0
self._n_classes = 0
self._n_latent_dim = 16
if 'n_classes' in params.keys():
self._n_classes = params['n_classes']
if 'lambda_d' in params.keys():
... | debug implementation | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward network."""
<|body_1|>
def _loss(self, _data):
"""pr... | stack_v2_sparse_classes_36k_train_030661 | 9,168 | permissive | [
{
"docstring": "Args: model: parent model object. params: dict() of parameters.",
"name": "__init__",
"signature": "def __init__(self, model, params)"
},
{
"docstring": "forward network.",
"name": "_network",
"signature": "def _network(self, input)"
},
{
"docstring": "prepare the... | 3 | stack_v2_sparse_classes_30k_train_008858 | Implement the Python class `Encoder` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward network.
- def _loss(self, _data): prepare the loss ... | Implement the Python class `Encoder` described below.
Class description:
debug implementation
Method signatures and docstrings:
- def __init__(self, model, params): Args: model: parent model object. params: dict() of parameters.
- def _network(self, input): forward network.
- def _loss(self, _data): prepare the loss ... | 9546d7a01c2b3e17131f34aa1e916e514c052ea8 | <|skeleton|>
class Encoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
<|body_0|>
def _network(self, input):
"""forward network."""
<|body_1|>
def _loss(self, _data):
"""pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""debug implementation"""
def __init__(self, model, params):
"""Args: model: parent model object. params: dict() of parameters."""
super().__init__(model, params)
self._var_scope = 'encoder'
self._lambda_end_d = 1.0
self._n_classes = 0
self._n_lat... | the_stack_v2_python_sparse | networks/network_aae_v_lite.py | cosmoplankton-studio/cellular-probabilistic | train | 0 |
82016bd00b709c43963faa5ce50b353dc0649541 | [
"d = {}\nn = len(nums)\nif k == 10000 and t == 0:\n return False\nfor i in range(n):\n ns = {k for k in d.keys() if abs(nums[i] - k) <= t}\n for j in ns:\n if i - d[j] <= k:\n return True\n d[nums[i]] = i\nreturn False",
"n = len(nums)\nnums = sorted([(nums[i], i) for i in range(n)],... | <|body_start_0|>
d = {}
n = len(nums)
if k == 10000 and t == 0:
return False
for i in range(n):
ns = {k for k in d.keys() if abs(nums[i] - k) <= t}
for j in ns:
if i - d[j] <= k:
return True
d[nums[i]] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate2(s... | stack_v2_sparse_classes_36k_train_030662 | 2,528 | no_license | [
{
"docstring": "字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type k: int :type t: int :rtype: bool",
"name": "containsNearbyAlmostDuplicate",
"signature": "def containsNearbyAlmostDuplicate(self, nums, k, t)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_010976 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicate(self, nums, k, t): 字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyAlmostDuplicate(self, nums, k, t): 字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate2(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""字典键:nums[i] 值:nums[i]最近的索引 时间复杂度O(n^2) 40/41 遍历数组,找到字典中所有的与nums[i]差的绝对值不大于t的值,然后遍历一遍看值与i的绝对值是否<=k :type nums: List[int] :type k: int :type t: int :rtype: bool"""
d = {}
n = len(nums)
if k == 10000 and t == 0:
... | the_stack_v2_python_sparse | 220_存在重复元素 III.py | lovehhf/LeetCode | train | 0 | |
e5867135796bc7eabfea799bb107e126a6a7807f | [
"super(stgcn_autoencoder, self).__init__()\nself.time_step = time_step\nout_feat = in_feat\nself.drop_out = nn.Dropout(p=0.4)\nself.block1 = STGCNBlock(in_channels=in_feat, spatial_channels=in_feat + 1 * size_step, out_channels=in_feat + 4 * size_step, num_nodes=num_nodes)\nself.block2 = STGCNBlock(in_channels=in_f... | <|body_start_0|>
super(stgcn_autoencoder, self).__init__()
self.time_step = time_step
out_feat = in_feat
self.drop_out = nn.Dropout(p=0.4)
self.block1 = STGCNBlock(in_channels=in_feat, spatial_channels=in_feat + 1 * size_step, out_channels=in_feat + 4 * size_step, num_nodes=num_n... | Autoencoder with spatio-temporal graph convolutional layers. | stgcn_autoencoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stgcn_autoencoder:
"""Autoencoder with spatio-temporal graph convolutional layers."""
def __init__(self, num_nodes, in_feat, size_step, time_step):
""":param num_nodes: Number of nodes in the graph. :param num_features: Number of features at each node in each time step. :param num_ti... | stack_v2_sparse_classes_36k_train_030663 | 6,003 | no_license | [
{
"docstring": ":param num_nodes: Number of nodes in the graph. :param num_features: Number of features at each node in each time step. :param num_timesteps: Number of time steps fed into the network. :param size_step: Adjustable dimension of features at each layer",
"name": "__init__",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_008932 | Implement the Python class `stgcn_autoencoder` described below.
Class description:
Autoencoder with spatio-temporal graph convolutional layers.
Method signatures and docstrings:
- def __init__(self, num_nodes, in_feat, size_step, time_step): :param num_nodes: Number of nodes in the graph. :param num_features: Number ... | Implement the Python class `stgcn_autoencoder` described below.
Class description:
Autoencoder with spatio-temporal graph convolutional layers.
Method signatures and docstrings:
- def __init__(self, num_nodes, in_feat, size_step, time_step): :param num_nodes: Number of nodes in the graph. :param num_features: Number ... | a96b24d3034d3aa5eee149234552aa7dad002b68 | <|skeleton|>
class stgcn_autoencoder:
"""Autoencoder with spatio-temporal graph convolutional layers."""
def __init__(self, num_nodes, in_feat, size_step, time_step):
""":param num_nodes: Number of nodes in the graph. :param num_features: Number of features at each node in each time step. :param num_ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stgcn_autoencoder:
"""Autoencoder with spatio-temporal graph convolutional layers."""
def __init__(self, num_nodes, in_feat, size_step, time_step):
""":param num_nodes: Number of nodes in the graph. :param num_features: Number of features at each node in each time step. :param num_timesteps: Numb... | the_stack_v2_python_sparse | Spatio_Temporal idea/my_models.py | ClarkFu007/Graph-Impuation-Neural-Network | train | 0 |
6f78ad8546b39b7da59223244233131f9ed4b949 | [
"len_r = len(matrix)\nlen_c = len(matrix[0])\nrows = set()\ncols = set()\nfor r in range(len_r):\n for c in range(len_c):\n if matrix[r][c] == 0:\n rows.add(r)\n cols.add(c)\nfor r in rows:\n for c in range(len_c):\n matrix[r][c] = 0\nfor c in cols:\n for r in range(len_... | <|body_start_0|>
len_r = len(matrix)
len_c = len(matrix[0])
rows = set()
cols = set()
for r in range(len_r):
for c in range(len_c):
if matrix[r][c] == 0:
rows.add(r)
cols.add(c)
for r in rows:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户"""
<|body_0|>
def setZeroes4(self, matrix: List[List[int]]) -> None:
"""https://leetcode-cn.com/problems/set-mat... | stack_v2_sparse_classes_36k_train_030664 | 15,932 | no_license | [
{
"docstring": "执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "https://leetcode-cn.com/problems/set-matrix-zeroes/solution/ju-zhen-zhi-ling-by-le... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: 执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户
- def setZeroes4(self, matrix: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: 执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户
- def setZeroes4(self, matrix: List[... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户"""
<|body_0|>
def setZeroes4(self, matrix: List[List[int]]) -> None:
"""https://leetcode-cn.com/problems/set-mat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""执行用时: 64 ms , 在所有 Python3 提交中击败了 14.68% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 89.99% 的用户"""
len_r = len(matrix)
len_c = len(matrix[0])
rows = set()
cols = set()
for r in range(len_r):
... | the_stack_v2_python_sparse | 矩阵置零.py | nomboy/leetcode | train | 0 | |
0debc914d1f3b8a5aeecca1493d036788133d8df | [
"res = []\nnums.sort()\nfor i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n l, r = (i + 1, len(nums) - 1)\n while l < r:\n s = nums[i] + nums[l] + nums[r]\n if s < 0:\n l += 1\n elif s > 0:\n r -= 1\n else:\n ... | <|body_start_0|>
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = (i + 1, len(nums) - 1)
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum_myfirst(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
nu... | stack_v2_sparse_classes_36k_train_030665 | 1,959 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum_myfirst",
"signature": "def threeSum_myfirst(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021366 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum_myfirst(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum_myfirst(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solu... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum_myfirst(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = (i + 1, len(nums) - 1)
while l < ... | the_stack_v2_python_sparse | 15.3Sum.py | JerryRoc/leetcode | train | 0 | |
4ff764730c728ef2ccc511191136e97598dc36ca | [
"dp = [float('inf')] * (n + 1)\ndp[0] = 0\nfor i in range(n + 1):\n j = 1\n while i + j * j <= n:\n dp[i + j * j] = min(dp[i + j * j], dp[i] + 1)\n j += 1\nreturn dp[-1]",
"tmp = n\nwhile tmp & 3 == 0:\n tmp >>= 2\nif tmp % 8 == 7:\n return 4\nindex = int(math.sqrt(n))\nwhile index:\n ... | <|body_start_0|>
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(n + 1):
j = 1
while i + j * j <= n:
dp[i + j * j] = min(dp[i + j * j], dp[i] + 1)
j += 1
return dp[-1]
<|end_body_0|>
<|body_start_1|>
tmp = n
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def math_numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in r... | stack_v2_sparse_classes_36k_train_030666 | 1,460 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "math_numSquares",
"signature": "def math_numSquares(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def math_numSquares(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def math_numSquares(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares(self, n):
"""... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def math_numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(n + 1):
j = 1
while i + j * j <= n:
dp[i + j * j] = min(dp[i + j * j], dp[i] + 1)
j += 1
retu... | the_stack_v2_python_sparse | python/279.perfect-squares.py | tainenko/Leetcode2019 | train | 5 | |
9fdc64d07c882246d606747fc5145e77b62b3142 | [
"self.x = x\nself.y = y\nself.type = traffic_sign_type",
"if random.random() < fc_prob:\n while True:\n wrong_type = random.choice(list(TrafficSignType))\n if wrong_type != self.type and wrong_type != TrafficSignType.RSStop:\n self.type = wrong_type\n break",
"corrected_x ... | <|body_start_0|>
self.x = x
self.y = y
self.type = traffic_sign_type
<|end_body_0|>
<|body_start_1|>
if random.random() < fc_prob:
while True:
wrong_type = random.choice(list(TrafficSignType))
if wrong_type != self.type and wrong_type != Traff... | Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system. | Pole | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pole:
"""Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system."""
def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown):
"""Constructor. Input: x: x coordinate of pole. y: y coordinate of pole. traffic_s... | stack_v2_sparse_classes_36k_train_030667 | 7,558 | no_license | [
{
"docstring": "Constructor. Input: x: x coordinate of pole. y: y coordinate of pole. traffic_sign_type: TrafficSignType obj.",
"name": "__init__",
"signature": "def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown)"
},
{
"docstring": "Perturb the type with the given probability. I... | 3 | stack_v2_sparse_classes_30k_train_020004 | Implement the Python class `Pole` described below.
Class description:
Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system.
Method signatures and docstrings:
- def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown): Constructor. Input: x:... | Implement the Python class `Pole` described below.
Class description:
Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system.
Method signatures and docstrings:
- def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown): Constructor. Input: x:... | 4be7ed6446640ad432f92a11b841aa49a3c2dbae | <|skeleton|>
class Pole:
"""Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system."""
def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown):
"""Constructor. Input: x: x coordinate of pole. y: y coordinate of pole. traffic_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pole:
"""Class to represent a pole for detection and pole map. The internal data follows the right-handed z-up coordinate system."""
def __init__(self, x, y, traffic_sign_type=TrafficSignType.Unknown):
"""Constructor. Input: x: x coordinate of pole. y: y coordinate of pole. traffic_sign_type: Tra... | the_stack_v2_python_sparse | detection/utils.py | weiliangxie/carla-semantic-localization | train | 0 |
ad4410bc547c6d96397c6b2ba724c9e107ca6759 | [
"if channel_id not in ('for_you', 'chrono_following', 'popular', 'continue_watching') and (not re.match(USER_CHANNEL_ID_RE, channel_id)):\n raise ValueError('Invalid channel_id: {}'.format(channel_id))\nendpoint = 'igtv/channel/'\nparams = {'id': channel_id}\nparams.update(self.authenticated_params)\nif kwargs:\... | <|body_start_0|>
if channel_id not in ('for_you', 'chrono_following', 'popular', 'continue_watching') and (not re.match(USER_CHANNEL_ID_RE, channel_id)):
raise ValueError('Invalid channel_id: {}'.format(channel_id))
endpoint = 'igtv/channel/'
params = {'id': channel_id}
param... | For endpoints in ``/igtv/``. | IGTVEndpointsMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IGTVEndpointsMixin:
"""For endpoints in ``/igtv/``."""
def tvchannel(self, channel_id, **kwargs):
"""Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvguide`) or for a user 'user_12345' where user_id = '12345'... | stack_v2_sparse_classes_36k_train_030668 | 2,289 | permissive | [
{
"docstring": "Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvguide`) or for a user 'user_12345' where user_id = '12345'",
"name": "tvchannel",
"signature": "def tvchannel(self, channel_id, **kwargs)"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_train_014148 | Implement the Python class `IGTVEndpointsMixin` described below.
Class description:
For endpoints in ``/igtv/``.
Method signatures and docstrings:
- def tvchannel(self, channel_id, **kwargs): Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvg... | Implement the Python class `IGTVEndpointsMixin` described below.
Class description:
For endpoints in ``/igtv/``.
Method signatures and docstrings:
- def tvchannel(self, channel_id, **kwargs): Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvg... | 7474bf00d2e97c73630713f3f0cec20a1b56b021 | <|skeleton|>
class IGTVEndpointsMixin:
"""For endpoints in ``/igtv/``."""
def tvchannel(self, channel_id, **kwargs):
"""Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvguide`) or for a user 'user_12345' where user_id = '12345'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IGTVEndpointsMixin:
"""For endpoints in ``/igtv/``."""
def tvchannel(self, channel_id, **kwargs):
"""Get channel :param channel_id: One of 'for_you', 'chrono_following', 'popular', 'continue_watching' (as returned by :meth:`tvguide`) or for a user 'user_12345' where user_id = '12345'"""
i... | the_stack_v2_python_sparse | instabotnet/api/instagram_private_api/endpoints/igtv.py | remorses/instagram-botnet | train | 7 |
8fa48e3a55dc865083f28c0a4451e55b11942794 | [
"if not head or not head.next:\n return head\npre = self.reverse_list(head.next)\nhead.next.next = head\nhead.next = None\nreturn pre",
"cur, pre, temp = (head, None, None)\nwhile cur:\n temp = cur.next\n cur.next = pre\n pre = cur\n cur = temp\nreturn pre",
"cur, pre = (head, None)\nwhile cur:\n... | <|body_start_0|>
if not head or not head.next:
return head
pre = self.reverse_list(head.next)
head.next.next = head
head.next = None
return pre
<|end_body_0|>
<|body_start_1|>
cur, pre, temp = (head, None, None)
while cur:
temp = cur.next
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
"""反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点"""
<|body_0|>
def reverse_list2(self, head: ListNode) -> ListNode:
"""反转链表(非递归方式) Args: head: 头结点位置 Returns: 头节点"""
<|body_1|>
def reverse_list3(se... | stack_v2_sparse_classes_36k_train_030669 | 1,985 | permissive | [
{
"docstring": "反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点",
"name": "reverse_list",
"signature": "def reverse_list(self, head: ListNode) -> ListNode"
},
{
"docstring": "反转链表(非递归方式) Args: head: 头结点位置 Returns: 头节点",
"name": "reverse_list2",
"signature": "def reverse_list2(self, head: ListN... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head: ListNode) -> ListNode: 反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点
- def reverse_list2(self, head: ListNode) -> ListNode: 反转链表(非递归方式) Args: head: 头结点位置... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head: ListNode) -> ListNode: 反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点
- def reverse_list2(self, head: ListNode) -> ListNode: 反转链表(非递归方式) Args: head: 头结点位置... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
"""反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点"""
<|body_0|>
def reverse_list2(self, head: ListNode) -> ListNode:
"""反转链表(非递归方式) Args: head: 头结点位置 Returns: 头节点"""
<|body_1|>
def reverse_list3(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
"""反转链表(递归方式) Args: head: 头结点位置 Returns: 头节点"""
if not head or not head.next:
return head
pre = self.reverse_list(head.next)
head.next.next = head
head.next = None
return pre
def reve... | the_stack_v2_python_sparse | src/leetcodepython/list/reverse_list_206.py | zhangyu345293721/leetcode | train | 101 | |
d59b7a5f85c6a06f0deaf1343ac2b35a3fdd1997 | [
"self.num_units = num_units\nself.kernel_size = kernel_size\nself.dilation_rate = dilation_rate",
"with tf.variable_scope(scope or type(self).__name__):\n input_dim = int(inputs.get_shape()[2])\n stddev = 1 / input_dim ** 0.5\n w = tf.get_variable('filter', [self.kernel_size, input_dim, self.num_units], ... | <|body_start_0|>
self.num_units = num_units
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(scope or type(self).__name__):
input_dim = int(inputs.get_shape()[2])
stddev = 1 / input_dim ** 0.... | a 1-D atrous convolutional layer | AConv1dLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_36k_train_030670 | 11,183 | permissive | [
{
"docstring": "constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation",
"name": "__init__",
"signature": "def __init__(self, num_units, kernel_size, dilation_rate)"
},
{
"docstring": "Create the variables and do the forward co... | 2 | stack_v2_sparse_classes_30k_train_011594 | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | Implement the Python class `AConv1dLayer` described below.
Class description:
a 1-D atrous convolutional layer
Method signatures and docstrings:
- def __init__(self, num_units, kernel_size, dilation_rate): constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate ... | fb530cf617ff86fe8a249d4582dfe90a303da295 | <|skeleton|>
class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
<|body_0|>
def __call__(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AConv1dLayer:
"""a 1-D atrous convolutional layer"""
def __init__(self, num_units, kernel_size, dilation_rate):
"""constructor Args: num_units: the number of filters kernel_size: the size of the filters dilation_rate: the rate of dilation"""
self.num_units = num_units
self.kernel_... | the_stack_v2_python_sparse | nabu/neuralnetworks/classifiers/layer.py | DavidKarlas/nabu | train | 1 |
d7646ad0985c17aecf1ff81ccd4dbdf737c456db | [
"y_true = np.ones((2, 1, 200, 200))\ny_pred = np.ones((2, 1, 200, 200))\nvar_y_true = K.variable(y_true)\nvar_y_pred = K.variable(y_pred)\nout_loss = gm_model.dice_coef(var_y_true, var_y_pred)\nres = K.eval(out_loss)\nassert res == 1.0",
"y_true = np.ones((2, 1, 200, 200))\ny_pred = np.zeros((2, 1, 200, 200))\nva... | <|body_start_0|>
y_true = np.ones((2, 1, 200, 200))
y_pred = np.ones((2, 1, 200, 200))
var_y_true = K.variable(y_true)
var_y_pred = K.variable(y_pred)
out_loss = gm_model.dice_coef(var_y_true, var_y_pred)
res = K.eval(out_loss)
assert res == 1.0
<|end_body_0|>
<|... | This class will test the model module from deepseg_gm. | TestModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestModel:
"""This class will test the model module from deepseg_gm."""
def test_dice_coef_max(self):
"""Test the upper-bound of the dice coefficient."""
<|body_0|>
def test_dice_coef_min(self):
"""Test the lower-bound of the dice coefficient."""
<|body_1... | stack_v2_sparse_classes_36k_train_030671 | 4,860 | permissive | [
{
"docstring": "Test the upper-bound of the dice coefficient.",
"name": "test_dice_coef_max",
"signature": "def test_dice_coef_max(self)"
},
{
"docstring": "Test the lower-bound of the dice coefficient.",
"name": "test_dice_coef_min",
"signature": "def test_dice_coef_min(self)"
},
{
... | 4 | null | Implement the Python class `TestModel` described below.
Class description:
This class will test the model module from deepseg_gm.
Method signatures and docstrings:
- def test_dice_coef_max(self): Test the upper-bound of the dice coefficient.
- def test_dice_coef_min(self): Test the lower-bound of the dice coefficient... | Implement the Python class `TestModel` described below.
Class description:
This class will test the model module from deepseg_gm.
Method signatures and docstrings:
- def test_dice_coef_max(self): Test the upper-bound of the dice coefficient.
- def test_dice_coef_min(self): Test the lower-bound of the dice coefficient... | 81ebad505180ab18270eb926cca4a134996f8c45 | <|skeleton|>
class TestModel:
"""This class will test the model module from deepseg_gm."""
def test_dice_coef_max(self):
"""Test the upper-bound of the dice coefficient."""
<|body_0|>
def test_dice_coef_min(self):
"""Test the lower-bound of the dice coefficient."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestModel:
"""This class will test the model module from deepseg_gm."""
def test_dice_coef_max(self):
"""Test the upper-bound of the dice coefficient."""
y_true = np.ones((2, 1, 200, 200))
y_pred = np.ones((2, 1, 200, 200))
var_y_true = K.variable(y_true)
var_y_pre... | the_stack_v2_python_sparse | unit_testing/test_deepseg_gm.py | PaulBautin/spinalcordtoolbox | train | 1 |
6ebd1dc15c59fb4f5ed681520de79e52cef60200 | [
"super(BasePage, self).__init__(driver)\nself.driver = driver\nself.util = Util()",
"try:\n actual_title = self.get_title()\n return self.util.verify_text_contains(actual_title, title_of_page)\nexcept Exception as err:\n self.automation_logger.error('Failed to get page title: ' + str(err))"
] | <|body_start_0|>
super(BasePage, self).__init__(driver)
self.driver = driver
self.util = Util()
<|end_body_0|>
<|body_start_1|>
try:
actual_title = self.get_title()
return self.util.verify_text_contains(actual_title, title_of_page)
except Exception as err... | BasePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
<|body_0|>
def verify_page_title(self, title_of_page):
"""Verify the title of current page. :param title_of_page: Title of current page that needs to be... | stack_v2_sparse_classes_36k_train_030672 | 856 | no_license | [
{
"docstring": "Initializes the BasePage class. :param driver: Instance of the driver.",
"name": "__init__",
"signature": "def __init__(self, driver)"
},
{
"docstring": "Verify the title of current page. :param title_of_page: Title of current page that needs to be verified. :return: True / False... | 2 | stack_v2_sparse_classes_30k_train_017409 | Implement the Python class `BasePage` described below.
Class description:
Implement the BasePage class.
Method signatures and docstrings:
- def __init__(self, driver): Initializes the BasePage class. :param driver: Instance of the driver.
- def verify_page_title(self, title_of_page): Verify the title of current page.... | Implement the Python class `BasePage` described below.
Class description:
Implement the BasePage class.
Method signatures and docstrings:
- def __init__(self, driver): Initializes the BasePage class. :param driver: Instance of the driver.
- def verify_page_title(self, title_of_page): Verify the title of current page.... | 0eb90797548d405c619017d65f8b8fbd06113f09 | <|skeleton|>
class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
<|body_0|>
def verify_page_title(self, title_of_page):
"""Verify the title of current page. :param title_of_page: Title of current page that needs to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
super(BasePage, self).__init__(driver)
self.driver = driver
self.util = Util()
def verify_page_title(self, title_of_page):
"""Verify the title of curr... | the_stack_v2_python_sparse | Base/base_page.py | LiuKang1080/Selenium-Frameworks | train | 1 | |
31ded81585cf2b09e74127d58c5efdb81e109d47 | [
"super(ArtifactHandler, self).__init__(*args, **kwargs)\nself.artifacts_path = config.ARTIFACTS_DIR\nif not os.path.isdir(self.artifacts_path):\n os.mkdir(self.artifacts_path)\nrun_data = self.main_test.data.run_data\nif run_data is not None and run_data.run_name is not None:\n artifact_folder = os.path.join(... | <|body_start_0|>
super(ArtifactHandler, self).__init__(*args, **kwargs)
self.artifacts_path = config.ARTIFACTS_DIR
if not os.path.isdir(self.artifacts_path):
os.mkdir(self.artifacts_path)
run_data = self.main_test.data.run_data
if run_data is not None and run_data.run... | Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension to append to the artifact file, e.g. '.zip'. DEFAULT_PROJECT_FOLDER (str): default ... | ArtifactHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtifactHandler:
"""Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension to append to the artifact file, e.g. '.z... | stack_v2_sparse_classes_36k_train_030673 | 2,984 | permissive | [
{
"docstring": "Initialize the handler and check that the artifacts dir was set.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add the case dir to the artifact. Args: test (object): test item instance.",
"name": "stop_test",
"signature": "def... | 3 | null | Implement the Python class `ArtifactHandler` described below.
Class description:
Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension t... | Implement the Python class `ArtifactHandler` described below.
Class description:
Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension t... | c443bc1b99e02f047adfcab9943966f0023f652c | <|skeleton|>
class ArtifactHandler:
"""Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension to append to the artifact file, e.g. '.z... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArtifactHandler:
"""Artifact creating result handler. At the end of the test, this handler creates a zip of the work directory, and updates the run data. Attributes: artifacts_path (str): base dir to create the artifacts in. EXTENSTION (str): the extension to append to the artifact file, e.g. '.zip'. DEFAULT_... | the_stack_v2_python_sparse | src/rotest/core/result/handlers/artifact_handler.py | gregoil/rotest | train | 26 |
51995a46b676e987bc9b683704c3e2bea65d2a7d | [
"if len(s) < 1:\n return 0\nret = []\nlenS = 0\nfor i in s:\n if i not in ret:\n ret.append(i)\n else:\n ret.clear()\n ret.append(i)\n continue\n if len(ret) > lenS:\n lenS = len(ret)\nprint(ret)\nreturn lenS",
"l = len(s)\nif l < 2:\n return l\ndp = [1 for _ in r... | <|body_start_0|>
if len(s) < 1:
return 0
ret = []
lenS = 0
for i in s:
if i not in ret:
ret.append(i)
else:
ret.clear()
ret.append(i)
continue
if len(ret) > lenS:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) < 1:
return 0
ret ... | stack_v2_sparse_classes_36k_train_030674 | 1,738 | no_license | [
{
"docstring": ":param s: :return:",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring1",
"signature": "def lengthOfLongestSubstring1(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :param s: :return:
- def lengthOfLongestSubstring1(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :param s: :return:
- def lengthOfLongestSubstring1(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOfLonges... | d56fe73bfefa7ec0441d15780e45114535f92f43 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
if len(s) < 1:
return 0
ret = []
lenS = 0
for i in s:
if i not in ret:
ret.append(i)
else:
ret.clear()
ret.appen... | the_stack_v2_python_sparse | other/02lengthOfLongestSubstring.py | johnsonkee/swordToOffer | train | 0 | |
1ba6907acc4472f1a052f2d866b46f94431b86d4 | [
"polling_time = 0\nresult = cls.get_task_result(job_instance_id)\nwhile not result['is_finished']:\n if polling_time > POLLING_TIMEOUT:\n logger.error('user->[{}] called api->[get_task_result] but got JobExecuteTimeout.'.format(settings.BACKEND_JOB_OPERATOR))\n raise JobPollTimeout({'job_instance_i... | <|body_start_0|>
polling_time = 0
result = cls.get_task_result(job_instance_id)
while not result['is_finished']:
if polling_time > POLLING_TIMEOUT:
logger.error('user->[{}] called api->[get_task_result] but got JobExecuteTimeout.'.format(settings.BACKEND_JOB_OPERATOR)... | JobDemand | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobDemand:
def poll_task_result(cls, job_instance_id: int):
"""轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同"""
<|body_0|>
def get_task_result(cls, job_instance_id: int):
"""获取执行结果 :param job_instance_id: job任务id :return: example: { "success":... | stack_v2_sparse_classes_36k_train_030675 | 6,436 | permissive | [
{
"docstring": "轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同",
"name": "poll_task_result",
"signature": "def poll_task_result(cls, job_instance_id: int)"
},
{
"docstring": "获取执行结果 :param job_instance_id: job任务id :return: example: { \"success\": [ { 'ip': 127.0.0.1, 'bk_c... | 2 | stack_v2_sparse_classes_30k_train_001344 | Implement the Python class `JobDemand` described below.
Class description:
Implement the JobDemand class.
Method signatures and docstrings:
- def poll_task_result(cls, job_instance_id: int): 轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同
- def get_task_result(cls, job_instance_id: int): 获取执行结果 ... | Implement the Python class `JobDemand` described below.
Class description:
Implement the JobDemand class.
Method signatures and docstrings:
- def poll_task_result(cls, job_instance_id: int): 轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同
- def get_task_result(cls, job_instance_id: int): 获取执行结果 ... | 72d2104783443bff26c752c5bd934a013b302b6d | <|skeleton|>
class JobDemand:
def poll_task_result(cls, job_instance_id: int):
"""轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同"""
<|body_0|>
def get_task_result(cls, job_instance_id: int):
"""获取执行结果 :param job_instance_id: job任务id :return: example: { "success":... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobDemand:
def poll_task_result(cls, job_instance_id: int):
"""轮询直到任务完成 :param job_instance_id: job任务id :return: 与 get_task_result 同"""
polling_time = 0
result = cls.get_task_result(job_instance_id)
while not result['is_finished']:
if polling_time > POLLING_TIMEOUT:... | the_stack_v2_python_sparse | apps/node_man/periodic_tasks/utils.py | TencentBlueKing/bk-nodeman | train | 54 | |
37ea1b4411a171feb5ddc577dba5ca33b4f3a377 | [
"dimension = image.size\nlist_of_x = []\nlist_of_y = []\npixel_access_image = image.load()\nfor x in range(0, dimension[0]):\n for y in range(0, dimension[1]):\n if pixel_access_image[x, y] == color:\n list_of_x.append(x)\n list_of_y.append(y)\nleft_x = min(list_of_x)\nright_x = max(... | <|body_start_0|>
dimension = image.size
list_of_x = []
list_of_y = []
pixel_access_image = image.load()
for x in range(0, dimension[0]):
for y in range(0, dimension[1]):
if pixel_access_image[x, y] == color:
list_of_x.append(x)
... | Crop an image, so that only a rectangle with the pixels of the intended color remain | BoundedImageCropper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoundedImageCropper:
"""Crop an image, so that only a rectangle with the pixels of the intended color remain"""
def crop_bounded_image(image, color):
""":param image: an image to be cropped :param color: the color to serve as the criterion of cropping :type image: png, jpg, or other ... | stack_v2_sparse_classes_36k_train_030676 | 1,876 | permissive | [
{
"docstring": ":param image: an image to be cropped :param color: the color to serve as the criterion of cropping :type image: png, jpg, or other image files :type color: (R, G, B, A) (:type R, G, B, and A: int from 0 to 255)",
"name": "crop_bounded_image",
"signature": "def crop_bounded_image(image, c... | 2 | stack_v2_sparse_classes_30k_val_000687 | Implement the Python class `BoundedImageCropper` described below.
Class description:
Crop an image, so that only a rectangle with the pixels of the intended color remain
Method signatures and docstrings:
- def crop_bounded_image(image, color): :param image: an image to be cropped :param color: the color to serve as t... | Implement the Python class `BoundedImageCropper` described below.
Class description:
Crop an image, so that only a rectangle with the pixels of the intended color remain
Method signatures and docstrings:
- def crop_bounded_image(image, color): :param image: an image to be cropped :param color: the color to serve as t... | 8931c8859878692134f5113d4c6c3e17561f0196 | <|skeleton|>
class BoundedImageCropper:
"""Crop an image, so that only a rectangle with the pixels of the intended color remain"""
def crop_bounded_image(image, color):
""":param image: an image to be cropped :param color: the color to serve as the criterion of cropping :type image: png, jpg, or other ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoundedImageCropper:
"""Crop an image, so that only a rectangle with the pixels of the intended color remain"""
def crop_bounded_image(image, color):
""":param image: an image to be cropped :param color: the color to serve as the criterion of cropping :type image: png, jpg, or other image files :... | the_stack_v2_python_sparse | UpdatedSyntheticDataset/SyntheticDataset2/ImageOperations/bounded_image_cropper.py | FlintHill/SUAS-Competition | train | 5 |
5cff84b7117c41c348f0ef325cdf2951fdf99b78 | [
"try:\n json_data = request.json\n culturalObject = culturalobject_create(json_data)\n return (get_cultural_object_json(culturalObject), 201)\nexcept Exception as e:\n return ('Error:{0}'.format(e), 500)",
"try:\n culturalObjects = get_cultural_objects()\n return (get_cultural_object_json(cultur... | <|body_start_0|>
try:
json_data = request.json
culturalObject = culturalobject_create(json_data)
return (get_cultural_object_json(culturalObject), 201)
except Exception as e:
return ('Error:{0}'.format(e), 500)
<|end_body_0|>
<|body_start_1|>
try:... | Objects | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objects:
def post(self):
"""Create a new Cultural Object"""
<|body_0|>
def get(self):
"""Retrieve all Cultural Object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
json_data = request.json
culturalObject = culturalobje... | stack_v2_sparse_classes_36k_train_030677 | 3,320 | no_license | [
{
"docstring": "Create a new Cultural Object",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Retrieve all Cultural Object",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017375 | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def post(self): Create a new Cultural Object
- def get(self): Retrieve all Cultural Object | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def post(self): Create a new Cultural Object
- def get(self): Retrieve all Cultural Object
<|skeleton|>
class Objects:
def post(self):
"""Create a new Cultural Object... | a7a5f86fb7617f8c8d11526a6213f3d958a4a65d | <|skeleton|>
class Objects:
def post(self):
"""Create a new Cultural Object"""
<|body_0|>
def get(self):
"""Retrieve all Cultural Object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Objects:
def post(self):
"""Create a new Cultural Object"""
try:
json_data = request.json
culturalObject = culturalobject_create(json_data)
return (get_cultural_object_json(culturalObject), 201)
except Exception as e:
return ('Error:{0}'.... | the_stack_v2_python_sparse | controller/CulturalObjectController.py | monica-gatti/Vasari | train | 1 | |
99c3c1b966c4f3037e7b35909ea5c5a885bf9c03 | [
"session = DBSession()\nsession.merge(t_trans_detail)\nsession.commit()\nsession.close()",
"session = DBSession()\nif 'trans_sq' in kwargs:\n _trans_sq = kwargs['trans_sq']\nselect = session.query(T_trans_detail).filter(T_trans_detail.trans_sq == _trans_sq).first()\nprint(select)\nsession.close()\nreturn selec... | <|body_start_0|>
session = DBSession()
session.merge(t_trans_detail)
session.commit()
session.close()
<|end_body_0|>
<|body_start_1|>
session = DBSession()
if 'trans_sq' in kwargs:
_trans_sq = kwargs['trans_sq']
select = session.query(T_trans_detail).... | 交易model类 | T_trans_detail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
session = DBSession()
... | stack_v2_sparse_classes_36k_train_030678 | 8,115 | no_license | [
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "save",
"signature": "def save(t_trans_detail)"
},
{
"docstring": "新加/修改交易表 :param trans: :return:",
"name": "select",
"signature": "def select(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010344 | Implement the Python class `T_trans_detail` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(t_trans_detail): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return: | Implement the Python class `T_trans_detail` described below.
Class description:
交易model类
Method signatures and docstrings:
- def save(t_trans_detail): 新加/修改交易表 :param trans: :return:
- def select(self, **kwargs): 新加/修改交易表 :param trans: :return:
<|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_tr... | 1bc744a6d331b4b733f6b6658b8310eb0c30524e | <|skeleton|>
class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
<|body_0|>
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class T_trans_detail:
"""交易model类"""
def save(t_trans_detail):
"""新加/修改交易表 :param trans: :return:"""
session = DBSession()
session.merge(t_trans_detail)
session.commit()
session.close()
def select(self, **kwargs):
"""新加/修改交易表 :param trans: :return:"""
... | the_stack_v2_python_sparse | investment/transaction/models.py | cliicy/vtrade | train | 0 |
6d4816be6e6b1bad0a300be9ce0e33a5bfa25174 | [
"datas = self.datas.loc[currentIndexList[0]:currentIndexList[1], column]\nself.datas.loc[currentIndexList[0]:currentIndexList[1], column] = [f'{min(datas)} ~ {max(datas)}' for _ in datas]\nreturn True",
"datas = self._toList(column)\nresult = [category if data in replaceList else data for data in datas]\nself.dat... | <|body_start_0|>
datas = self.datas.loc[currentIndexList[0]:currentIndexList[1], column]
self.datas.loc[currentIndexList[0]:currentIndexList[1], column] = [f'{min(datas)} ~ {max(datas)}' for _ in datas]
return True
<|end_body_0|>
<|body_start_1|>
datas = self._toList(column)
res... | | 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정 | Generalization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generalization:
"""| 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정"""
def local(self, column: str, currentIndexList: list):
"""일반화 기술 중 로컬 일반화를 수행하는 함수 Args: column (str) ... | stack_v2_sparse_classes_36k_train_030679 | 1,737 | permissive | [
{
"docstring": "일반화 기술 중 로컬 일반화를 수행하는 함수 Args: column (str) : 로컬 일반화를 적용할 컬럼 currentIndexList (list) : 로컬 일반화를 적용할 Index 범위 Returns: bool : 기술 적용 성공 시 True 리턴",
"name": "local",
"signature": "def local(self, column: str, currentIndexList: list)"
},
{
"docstring": "일반화 기술 중 문자데이터 범주화를 수행하는 함수 Arg... | 2 | stack_v2_sparse_classes_30k_val_000543 | Implement the Python class `Generalization` described below.
Class description:
| 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정
Method signatures and docstrings:
- def local(self, column: str, currentIndex... | Implement the Python class `Generalization` described below.
Class description:
| 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정
Method signatures and docstrings:
- def local(self, column: str, currentIndex... | 069fa7e35a2e1edfff30dc2540d9b87f5db95dde | <|skeleton|>
class Generalization:
"""| 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정"""
def local(self, column: str, currentIndexList: list):
"""일반화 기술 중 로컬 일반화를 수행하는 함수 Args: column (str) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generalization:
"""| 일반화 기술 중 로컬 일반화, 문자데이터 범주화를 구현한 클래스 | 모든 메소드는 생성자에 원본 데이터를 인자 값으로 넣으면 원본 데이터를 수정한다. Args: datas (pandas.DataFrame) : 로컬 일반화 기술과 문자데이터 범주화 기술을 적용할 DataFrame 지정"""
def local(self, column: str, currentIndexList: list):
"""일반화 기술 중 로컬 일반화를 수행하는 함수 Args: column (str) : 로컬 일반화를 적용할... | the_stack_v2_python_sparse | DIL/generalization.py | LRTK-CODER/DIL-Project | train | 2 |
600b474162e535fa590fe388601d73e476261085 | [
"super().__init__()\nself.norm1 = nn.LayerNorm(embed_size)\nself.msa = _MSA(embed_size, num_heads)\nself.norm2 = nn.LayerNorm(embed_size)\nself.mlp = _MLP(in_feats=embed_size, out_feats=num_heads)",
"y = self.norm1(x)\ny = self.msa(y)\nx = x + y\ny = self.norm2(x)\ny = self.mlp(y)\nx = x + y\nreturn x"
] | <|body_start_0|>
super().__init__()
self.norm1 = nn.LayerNorm(embed_size)
self.msa = _MSA(embed_size, num_heads)
self.norm2 = nn.LayerNorm(embed_size)
self.mlp = _MLP(in_feats=embed_size, out_feats=num_heads)
<|end_body_0|>
<|body_start_1|>
y = self.norm1(x)
y = ... | _TransformerLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_030680 | 24,719 | permissive | [
{
"docstring": "A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module.",
"name": "__init__",
"signature": "def __init__(self, embed_size, num_heads)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_012517 | Implement the Python class `_TransformerLayer` described below.
Class description:
Implement the _TransformerLayer class.
Method signatures and docstrings:
- def __init__(self, embed_size, num_heads): A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_he... | Implement the Python class `_TransformerLayer` described below.
Class description:
Implement the _TransformerLayer class.
Method signatures and docstrings:
- def __init__(self, embed_size, num_heads): A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_he... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TransformerLayer:
def __init__(self, embed_size, num_heads):
"""A module that implements a single transformer layer. Args: embed_size (int): The size of the embedding vector. num_heads (int): The number of heads to use in the multi-head self-attention module."""
super().__init__()
sel... | the_stack_v2_python_sparse | GANDLF/models/unetr.py | mlcommons/GaNDLF | train | 45 | |
a7a1744a7049662192e1f54b0a073f663430e802 | [
"offer = self.offer or self.price or self.cost\nprice = self.price or self.cost\nif not offer or not price:\n return None\nreturn '%1.2f%%' % float((offer - price) * Decimal(-100.0) / price)",
"cls.objects.all().delete()\n\ndef int_(v):\n try:\n return int(v)\n except Exception:\n return No... | <|body_start_0|>
offer = self.offer or self.price or self.cost
price = self.price or self.cost
if not offer or not price:
return None
return '%1.2f%%' % float((offer - price) * Decimal(-100.0) / price)
<|end_body_0|>
<|body_start_1|>
cls.objects.all().delete()
... | Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada. | Replacement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
<|body_0|>
def load_xls(cls, xls_file)... | stack_v2_sparse_classes_36k_train_030681 | 4,826 | no_license | [
{
"docstring": "Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un \"sobrecuento\" :p)",
"name": "discount",
"signature": "def discount(self)"
},
{
"docstring": "Limpia y carga todo desde un xml.",
"name": "load_xls",
"signature": "def load_xls(cls, xls_file)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014706 | Implement the Python class `Replacement` described below.
Class description:
Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada.
Method signatures and docstrings:
- def discount(self): Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :... | Implement the Python class `Replacement` described below.
Class description:
Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada.
Method signatures and docstrings:
- def discount(self): Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :... | 1c38605197f41770df1e7b53efe14ff56bb0d5f2 | <|skeleton|>
class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
<|body_0|>
def load_xls(cls, xls_file)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Replacement:
"""Un repuesto y su informacion asociada. Por ahora solamente ponemos los datos, sin indexar ni nada."""
def discount(self):
"""Estima cual es el descuento (entre 0 y 99.99... - si es negativo es un "sobrecuento" :p)"""
offer = self.offer or self.price or self.cost
pr... | the_stack_v2_python_sparse | stock/models.py | luismasuelli/repuestazo | train | 0 |
05c454cc0e404301185a56345fdd26e6f5ccccfe | [
"sortArray = []\n\ndef inorder(node):\n if not node:\n return\n inorder(node.left)\n sortArray.append(node.val)\n inorder(node.right)\ninorder(root)\nminDist = float('inf')\nfor x in range(len(sortArray) - 1, 0, -1):\n minDist = min(minDist, sortArray[x] - sortArray[x - 1])\nreturn minDist",
... | <|body_start_0|>
sortArray = []
def inorder(node):
if not node:
return
inorder(node.left)
sortArray.append(node.val)
inorder(node.right)
inorder(root)
minDist = float('inf')
for x in range(len(sortArray) - 1, 0, -1)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDiffInBST(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDiffInBSTSol(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sortArray = []
def inorder(node):... | stack_v2_sparse_classes_36k_train_030682 | 2,795 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDiffInBST",
"signature": "def minDiffInBST(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDiffInBSTSol",
"signature": "def minDiffInBSTSol(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDiffInBST(self, root): :type root: TreeNode :rtype: int
- def minDiffInBSTSol(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDiffInBST(self, root): :type root: TreeNode :rtype: int
- def minDiffInBSTSol(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def minDiffI... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def minDiffInBST(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDiffInBSTSol(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDiffInBST(self, root):
""":type root: TreeNode :rtype: int"""
sortArray = []
def inorder(node):
if not node:
return
inorder(node.left)
sortArray.append(node.val)
inorder(node.right)
inorder(root)
... | the_stack_v2_python_sparse | tree/min_distance_between_binary_nodes.py | gerrycfchang/leetcode-python | train | 2 | |
80015c8bdebc4edb8333a4b9c45110dad45486a4 | [
"left, right = (0, len(nums) - 1)\nwhile left < right:\n mid = (left + right) // 2\n if nums[mid] < nums[right]:\n right = mid\n elif nums[mid] > nums[right]:\n left = mid + 1\nreturn nums[left]",
"len_nums = len(nums)\nif len_nums == 1:\n return nums[0]\nif nums[0] < nums[-1]:\n retu... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while left < right:
mid = (left + right) // 2
if nums[mid] < nums[right]:
right = mid
elif nums[mid] > nums[right]:
left = mid + 1
return nums[left]
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin4(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_030683 | 2,555 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin4",
"signature": "def findMin4(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin4(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin4(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype:... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin4(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
left, right = (0, len(nums) - 1)
while left < right:
mid = (left + right) // 2
if nums[mid] < nums[right]:
right = mid
elif nums[mid] > nums[right]:
... | the_stack_v2_python_sparse | LC153.py | Qiao-Liang/LeetCode | train | 0 | |
a45bd42e3b29a6af758443782d1d7d411982823b | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | DecoderBlock class for machine translation | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""DecoderBlock class for machine translation"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k_train_030684 | 12,086 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | stack_v2_sparse_classes_30k_train_009463 | Implement the Python class `DecoderBlock` described below.
Class description:
DecoderBlock class for machine translation
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `DecoderBlock` described below.
Class description:
DecoderBlock class for machine translation
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class DecoderBlock:
"""DecoderBlock class for machine translation"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""DecoderBlock class for machine translation"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Dec... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
bb3aa3b1dc2e0485a7af0c7dbda5dd526165e003 | [
"if not isinstance(conditioned_entity, Lever):\n raise ValueError('conditioned_entity must be of class Lever')\nassert len(timers) == len(textures) == 2\nsuper().__init__(timers, textures, **kwargs)\nself.conditioned_entity = conditioned_entity",
"super().activate(activating_entity)\nself.conditioned_entity.re... | <|body_start_0|>
if not isinstance(conditioned_entity, Lever):
raise ValueError('conditioned_entity must be of class Lever')
assert len(timers) == len(textures) == 2
super().__init__(timers, textures, **kwargs)
self.conditioned_entity = conditioned_entity
<|end_body_0|>
<|bo... | Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement. | ConditionedColorChanging | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionedColorChanging:
"""Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement."""
def __init__(self, conditioned_entity, timers, textures, **kwargs):
"""Args: conditioned_entity: Lever SceneElement. timers: list of Timers. textures: list o... | stack_v2_sparse_classes_36k_train_030685 | 4,157 | permissive | [
{
"docstring": "Args: conditioned_entity: Lever SceneElement. timers: list of Timers. textures: list of Textures. **kwargs: other params to configure entity. Refer to Entity class. Notes: The length of timers and textures should be 2.",
"name": "__init__",
"signature": "def __init__(self, conditioned_en... | 2 | stack_v2_sparse_classes_30k_train_000388 | Implement the Python class `ConditionedColorChanging` described below.
Class description:
Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement.
Method signatures and docstrings:
- def __init__(self, conditioned_entity, timers, textures, **kwargs): Args: conditioned_entity: Lev... | Implement the Python class `ConditionedColorChanging` described below.
Class description:
Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement.
Method signatures and docstrings:
- def __init__(self, conditioned_entity, timers, textures, **kwargs): Args: conditioned_entity: Lev... | 33321c690c1142c1f84308f952677619d33e4c1f | <|skeleton|>
class ConditionedColorChanging:
"""Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement."""
def __init__(self, conditioned_entity, timers, textures, **kwargs):
"""Args: conditioned_entity: Lever SceneElement. timers: list of Timers. textures: list o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionedColorChanging:
"""Flips the reward of an SceneElement based on timers. Intended to work with Lever SceneElement."""
def __init__(self, conditioned_entity, timers, textures, **kwargs):
"""Args: conditioned_entity: Lever SceneElement. timers: list of Timers. textures: list of Textures. *... | the_stack_v2_python_sparse | simple_playgrounds/playgrounds/scene_elements/elements/conditioning.py | Cindy0725/simple-playgrounds | train | 0 |
947a0a97259aabeda52ab8c6a063dc50170d1c02 | [
"gym.Wrapper.__init__(self, env)\nself._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype='uint8')\nself._skip = skip",
"total_reward = 0.0\ndone = None\nfor i in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n if i == self._skip - 2:\n self._obs_buffer[0] = obs\n... | <|body_start_0|>
gym.Wrapper.__init__(self, env)
self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype='uint8')
self._skip = skip
<|end_body_0|>
<|body_start_1|>
total_reward = 0.0
done = None
for i in range(self._skip):
obs, reward, done, inf... | MaxAndSkipEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxAndSkipEnv:
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
<|body_0|>
def _step(self, action):
"""Repeat action, sum reward, and max over last observations."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
gym.Wrapper.__i... | stack_v2_sparse_classes_36k_train_030686 | 5,252 | no_license | [
{
"docstring": "Return only every `skip`-th frame",
"name": "__init__",
"signature": "def __init__(self, env, skip=4)"
},
{
"docstring": "Repeat action, sum reward, and max over last observations.",
"name": "_step",
"signature": "def _step(self, action)"
}
] | 2 | null | Implement the Python class `MaxAndSkipEnv` described below.
Class description:
Implement the MaxAndSkipEnv class.
Method signatures and docstrings:
- def __init__(self, env, skip=4): Return only every `skip`-th frame
- def _step(self, action): Repeat action, sum reward, and max over last observations. | Implement the Python class `MaxAndSkipEnv` described below.
Class description:
Implement the MaxAndSkipEnv class.
Method signatures and docstrings:
- def __init__(self, env, skip=4): Return only every `skip`-th frame
- def _step(self, action): Repeat action, sum reward, and max over last observations.
<|skeleton|>
c... | 7b394fa87523803b3f4536b316df76cc44f8846e | <|skeleton|>
class MaxAndSkipEnv:
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
<|body_0|>
def _step(self, action):
"""Repeat action, sum reward, and max over last observations."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxAndSkipEnv:
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
gym.Wrapper.__init__(self, env)
self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype='uint8')
self._skip = skip
def _step(self, action):
"""Repeat action, sum r... | the_stack_v2_python_sparse | RL4/rl_mar2018_8_transfer_and_implicit/utils/envs.py | chriscremer/Other_Code | train | 7 | |
958c85f778b7c42a7298eb433bd1cbb640c5c08f | [
"for serializer in self.serializers:\n if serializer != 'annotation':\n try:\n deserialize(serializer, {})\n except SerializerDoesNotExist as error:\n assert str(error) == \"'{s} is a serialization-only serializer'\".format(s=serializer)",
"for serializer in self.serializers... | <|body_start_0|>
for serializer in self.serializers:
if serializer != 'annotation':
try:
deserialize(serializer, {})
except SerializerDoesNotExist as error:
assert str(error) == "'{s} is a serialization-only serializer'".format(... | SerializerTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerializerTests:
def test_deserialization(self):
"""Deserialization should raise for serialization only error."""
<|body_0|>
def test_empty_object(self):
"""If specified version is not implemented, serializer returns an empty dict."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_030687 | 1,334 | permissive | [
{
"docstring": "Deserialization should raise for serialization only error.",
"name": "test_deserialization",
"signature": "def test_deserialization(self)"
},
{
"docstring": "If specified version is not implemented, serializer returns an empty dict.",
"name": "test_empty_object",
"signatu... | 2 | null | Implement the Python class `SerializerTests` described below.
Class description:
Implement the SerializerTests class.
Method signatures and docstrings:
- def test_deserialization(self): Deserialization should raise for serialization only error.
- def test_empty_object(self): If specified version is not implemented, s... | Implement the Python class `SerializerTests` described below.
Class description:
Implement the SerializerTests class.
Method signatures and docstrings:
- def test_deserialization(self): Deserialization should raise for serialization only error.
- def test_empty_object(self): If specified version is not implemented, s... | 23d641af431741f28e0b1f06533be8528cd3000e | <|skeleton|>
class SerializerTests:
def test_deserialization(self):
"""Deserialization should raise for serialization only error."""
<|body_0|>
def test_empty_object(self):
"""If specified version is not implemented, serializer returns an empty dict."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SerializerTests:
def test_deserialization(self):
"""Deserialization should raise for serialization only error."""
for serializer in self.serializers:
if serializer != 'annotation':
try:
deserialize(serializer, {})
except Serialize... | the_stack_v2_python_sparse | apps/iiif/serializers/tests.py | ecds/readux | train | 20 | |
90d43a7b693fbf55f060706e1fdba5436b054ebe | [
"if context is None:\n context = {}\ndata = self.read(cr, uid, ids, context=context)[0]\nobj_account_move = self.pool.get('account.move')\nwf_service = netsvc.LocalService('workflow')\ndomain = [('state', '=', 'closed'), ('date', '>=', data['date_from']), ('date', '<=', data['date_to'])]\nif data['period_id']:\n... | <|body_start_0|>
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
obj_account_move = self.pool.get('account.move')
wf_service = netsvc.LocalService('workflow')
domain = [('state', '=', 'closed'), ('date', '>=', data['date_from']), ('... | This model to close moves in special period | account_close_period | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_close_period:
"""This model to close moves in special period"""
def get_moves(self, cr, uid, ids, context=None):
"""Get All moves belong not in draft, posted or reversed state @return: dictionary of values"""
<|body_0|>
def close_period(self, cr, uid, ids, contex... | stack_v2_sparse_classes_36k_train_030688 | 3,896 | no_license | [
{
"docstring": "Get All moves belong not in draft, posted or reversed state @return: dictionary of values",
"name": "get_moves",
"signature": "def get_moves(self, cr, uid, ids, context=None)"
},
{
"docstring": "Validate all accounts belong in consolidation account or not @return: dictionary of v... | 2 | stack_v2_sparse_classes_30k_train_017381 | Implement the Python class `account_close_period` described below.
Class description:
This model to close moves in special period
Method signatures and docstrings:
- def get_moves(self, cr, uid, ids, context=None): Get All moves belong not in draft, posted or reversed state @return: dictionary of values
- def close_p... | Implement the Python class `account_close_period` described below.
Class description:
This model to close moves in special period
Method signatures and docstrings:
- def get_moves(self, cr, uid, ids, context=None): Get All moves belong not in draft, posted or reversed state @return: dictionary of values
- def close_p... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_close_period:
"""This model to close moves in special period"""
def get_moves(self, cr, uid, ids, context=None):
"""Get All moves belong not in draft, posted or reversed state @return: dictionary of values"""
<|body_0|>
def close_period(self, cr, uid, ids, contex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_close_period:
"""This model to close moves in special period"""
def get_moves(self, cr, uid, ids, context=None):
"""Get All moves belong not in draft, posted or reversed state @return: dictionary of values"""
if context is None:
context = {}
data = self.read(cr... | the_stack_v2_python_sparse | v_7/Dongola/ntc/account_ntc/wizard/account_close_period.py | musabahmed/baba | train | 0 |
cd1796a91383b1fc95a63e53c2f8e0df47adef7a | [
"if not isinstance(income, pd.DataFrame) and (not income is None):\n raise TypeError('income must be None or a pandas DataFrame')\nif not isinstance(countries, pd.DataFrame) and (not countries is None):\n raise TypeError('countries must be None or a pandas DataFrame')\nself.income = income\nself.countries = c... | <|body_start_0|>
if not isinstance(income, pd.DataFrame) and (not income is None):
raise TypeError('income must be None or a pandas DataFrame')
if not isinstance(countries, pd.DataFrame) and (not countries is None):
raise TypeError('countries must be None or a pandas DataFrame')
... | Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables | EconVisualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EconVisualizer:
"""Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables"""
def __init__(self, income=None, countries=None):
""":param income: pandas.DataFrame or None of income data :param countries: pan... | stack_v2_sparse_classes_36k_train_030689 | 4,318 | no_license | [
{
"docstring": ":param income: pandas.DataFrame or None of income data :param countries: pandas.DataFrame or None of income data",
"name": "__init__",
"signature": "def __init__(self, income=None, countries=None)"
},
{
"docstring": "graph income from income and countries dataframes within list o... | 4 | null | Implement the Python class `EconVisualizer` described below.
Class description:
Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables
Method signatures and docstrings:
- def __init__(self, income=None, countries=None): :param income: pand... | Implement the Python class `EconVisualizer` described below.
Class description:
Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables
Method signatures and docstrings:
- def __init__(self, income=None, countries=None): :param income: pand... | f5bb1e51de4f84ab3dd62d3073aee4f56534afa1 | <|skeleton|>
class EconVisualizer:
"""Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables"""
def __init__(self, income=None, countries=None):
""":param income: pandas.DataFrame or None of income data :param countries: pan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EconVisualizer:
"""Economic Visualizer object. Can contain economic information and visualizes information from its variables or from external variables"""
def __init__(self, income=None, countries=None):
""":param income: pandas.DataFrame or None of income data :param countries: pandas.DataFrame... | the_stack_v2_python_sparse | lt1503/EconVisualizer/econ_visualizer.py | ds-ga-1007/assignment9 | train | 2 |
1db09ed4dd01d6df6eea676786d838462aac8dd4 | [
"res_model_rec = self.env['ir.model'].search([('model', '=', 'school.evaluation.template')])\nvals.update({'res_model_id': res_model_rec.id})\nres = super(RatingRating, self).create(vals)\nreturn res",
"for rate in self:\n if rate.res_model == 'school.evaluation.template':\n rate.res_name = rate.rating\... | <|body_start_0|>
res_model_rec = self.env['ir.model'].search([('model', '=', 'school.evaluation.template')])
vals.update({'res_model_id': res_model_rec.id})
res = super(RatingRating, self).create(vals)
return res
<|end_body_0|>
<|body_start_1|>
for rate in self:
if r... | Defining Rating. | RatingRating | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatingRating:
"""Defining Rating."""
def create(self, vals):
"""Set Document model name for rating."""
<|body_0|>
def _compute_res_name(self):
"""Override this method to set the alternate rec_name as rating"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_030690 | 9,050 | no_license | [
{
"docstring": "Set Document model name for rating.",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "Override this method to set the alternate rec_name as rating",
"name": "_compute_res_name",
"signature": "def _compute_res_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008605 | Implement the Python class `RatingRating` described below.
Class description:
Defining Rating.
Method signatures and docstrings:
- def create(self, vals): Set Document model name for rating.
- def _compute_res_name(self): Override this method to set the alternate rec_name as rating | Implement the Python class `RatingRating` described below.
Class description:
Defining Rating.
Method signatures and docstrings:
- def create(self, vals): Set Document model name for rating.
- def _compute_res_name(self): Override this method to set the alternate rec_name as rating
<|skeleton|>
class RatingRating:
... | 6a9793f3a15da9eed40bf840b1d9a46457c5fd55 | <|skeleton|>
class RatingRating:
"""Defining Rating."""
def create(self, vals):
"""Set Document model name for rating."""
<|body_0|>
def _compute_res_name(self):
"""Override this method to set the alternate rec_name as rating"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RatingRating:
"""Defining Rating."""
def create(self, vals):
"""Set Document model name for rating."""
res_model_rec = self.env['ir.model'].search([('model', '=', 'school.evaluation.template')])
vals.update({'res_model_id': res_model_rec.id})
res = super(RatingRating, self... | the_stack_v2_python_sparse | school_evaluation/models/school_evaluation.py | JayVora-SerpentCS/OdooEduERP | train | 121 |
4bc158f64a25b9e9a849c3a53991cdb942b8dff3 | [
"self.put_parser = reqparse.RequestParser()\nself.put_parser.add_argument('Name', type=str)\nself.put_parser.add_argument('Speed', type=str)\nself.put_parser.add_argument('Duplex', type=str)\nself.put_parser.add_argument('Status', type=str)\nsuper(SinglePort, self).__init__()",
"try:\n Port = models.Ports.quer... | <|body_start_0|>
self.put_parser = reqparse.RequestParser()
self.put_parser.add_argument('Name', type=str)
self.put_parser.add_argument('Speed', type=str)
self.put_parser.add_argument('Duplex', type=str)
self.put_parser.add_argument('Status', type=str)
super(SinglePort, s... | SinglePort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePort:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self, Switch_Id, Id):
"""affiche un des ports d'un switch de l'infrastructure"""
<|body_1|>
def put(self, Switch_Id, Id):
"""modif... | stack_v2_sparse_classes_36k_train_030691 | 2,352 | no_license | [
{
"docstring": "Constructeur: liste les champs attendus dans le corps HTML",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "affiche un des ports d'un switch de l'infrastructure",
"name": "get",
"signature": "def get(self, Switch_Id, Id)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_015551 | Implement the Python class `SinglePort` described below.
Class description:
Implement the SinglePort class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self, Switch_Id, Id): affiche un des ports d'un switch de l'infrastructure
- def put(... | Implement the Python class `SinglePort` described below.
Class description:
Implement the SinglePort class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self, Switch_Id, Id): affiche un des ports d'un switch de l'infrastructure
- def put(... | 8f107644a74fe46827ec5ed53d0457022bd1608b | <|skeleton|>
class SinglePort:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self, Switch_Id, Id):
"""affiche un des ports d'un switch de l'infrastructure"""
<|body_1|>
def put(self, Switch_Id, Id):
"""modif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SinglePort:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
self.put_parser = reqparse.RequestParser()
self.put_parser.add_argument('Name', type=str)
self.put_parser.add_argument('Speed', type=str)
self.put_parser.add_argument('Duple... | the_stack_v2_python_sparse | restapp/view_single_port_v2.py | ldurandadomia/Flask-Restful | train | 0 | |
dfbc6ec5d62f7a63d52bd6c329ba0a6f4a015049 | [
"row, col = (len(dungeon), len(dungeon[0]))\ndp = [[0] * col for _ in range(row)]\ndp[row - 1][col - 1] = 1\nfor i in range(row - 2, -1, -1):\n dp[i][col - 1] = max(1, dp[i + 1][col - 1] - dungeon[i + 1][col - 1])\nfor j in range(col - 2, -1, -1):\n dp[row - 1][j] = max(1, dp[row - 1][j + 1] - dungeon[row - 1... | <|body_start_0|>
row, col = (len(dungeon), len(dungeon[0]))
dp = [[0] * col for _ in range(row)]
dp[row - 1][col - 1] = 1
for i in range(row - 2, -1, -1):
dp[i][col - 1] = max(1, dp[i + 1][col - 1] - dungeon[i + 1][col - 1])
for j in range(col - 2, -1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_0|>
def online_On(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
row, col = (len(... | stack_v2_sparse_classes_36k_train_030692 | 1,499 | no_license | [
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "calculateMinimumHP",
"signature": "def calculateMinimumHP(self, dungeon)"
},
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "online_On",
"signature": "def online_On(self, dungeon)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012781 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def online_On(self, dungeon): :type dungeon: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def online_On(self, dungeon): :type dungeon: List[List[int]] :rtype: int
<|skeleton|>
class S... | 11c8fc663888b48b5417256aab1bf872190267ba | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_0|>
def online_On(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
row, col = (len(dungeon), len(dungeon[0]))
dp = [[0] * col for _ in range(row)]
dp[row - 1][col - 1] = 1
for i in range(row - 2, -1, -1):
dp[i][col - 1] = max(1... | the_stack_v2_python_sparse | Dungeon Game.py | lfdyf20/Leetcode | train | 1 | |
cb74a270e851a21debf6da1acadf6d7a02df060f | [
"auth = request.authorization\nif auth:\n user_email = auth.username\n user = get_user_by_email(user_email)\n user_id = user.id\nelse:\n user_id = current_user.id\n user_email = current_user.email\nlogger.debug(f'Creating new question for user {user_email}.')\nlogger.debug(request.json)\nqid = ''.joi... | <|body_start_0|>
auth = request.authorization
if auth:
user_email = auth.username
user = get_user_by_email(user_email)
user_id = user.id
else:
user_id = current_user.id
user_email = current_user.email
logger.debug(f'Creating new... | QuestionsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionsAPI:
def post(self):
"""Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache in: header description: flag indicating whether to update the cached knowledge graph required: false ... | stack_v2_sparse_classes_36k_train_030693 | 5,476 | no_license | [
{
"docstring": "Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache in: header description: flag indicating whether to update the cached knowledge graph required: false default: true type: string - name: Answer... | 2 | stack_v2_sparse_classes_30k_test_000227 | Implement the Python class `QuestionsAPI` described below.
Class description:
Implement the QuestionsAPI class.
Method signatures and docstrings:
- def post(self): Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache ... | Implement the Python class `QuestionsAPI` described below.
Class description:
Implement the QuestionsAPI class.
Method signatures and docstrings:
- def post(self): Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache ... | 23e3c72b364184d2a3fe23d8a5694a3a77872719 | <|skeleton|>
class QuestionsAPI:
def post(self):
"""Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache in: header description: flag indicating whether to update the cached knowledge graph required: false ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionsAPI:
def post(self):
"""Create new question --- tags: [question] parameters: - in: body name: question schema: $ref: '#/definitions/Question' required: true - name: RebuildCache in: header description: flag indicating whether to update the cached knowledge graph required: false default: true ... | the_stack_v2_python_sparse | manager/api/questions_api.py | wahello/robokop | train | 0 | |
15facf8c268b167a93cfcbaa1230ca456fefc46a | [
"self.capacity = capacity\nself.dequeue = LRUDeque(capacity)\nself.hashtable = dict()",
"if key in self.hashtable:\n self.dequeue.access(self.hashtable[key])\n return self.hashtable[key].val\nelse:\n return -1",
"if key in self.hashtable:\n self.dequeue.access(self.hashtable[key])\n self.hashtabl... | <|body_start_0|>
self.capacity = capacity
self.dequeue = LRUDeque(capacity)
self.hashtable = dict()
<|end_body_0|>
<|body_start_1|>
if key in self.hashtable:
self.dequeue.access(self.hashtable[key])
return self.hashtable[key].val
else:
return ... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_030694 | 2,048 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_val_000708 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 490c38a9478838ff23c9f910cc950633b1e3f994 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.dequeue = LRUDeque(capacity)
self.hashtable = dict()
def get(self, key):
""":rtype: int"""
if key in self.hashtable:
self.dequeue.access(self.hashtab... | the_stack_v2_python_sparse | LRU Cache/solution.py | normanyahq/LeetCodeSolution | train | 0 | |
64b1ff5f2c5bb258892ea2a60ce70cbc89c45d56 | [
"form = RegistrationForm()\ncontext = {'form': form}\nreturn render(request, 'accounts/register.html', context)",
"form = RegistrationForm(request.POST or None)\nif form.is_valid():\n first_name = form.cleaned_data['first_name']\n last_name = form.cleaned_data['last_name']\n phone_number = form.cleaned_d... | <|body_start_0|>
form = RegistrationForm()
context = {'form': form}
return render(request, 'accounts/register.html', context)
<|end_body_0|>
<|body_start_1|>
form = RegistrationForm(request.POST or None)
if form.is_valid():
first_name = form.cleaned_data['first_name'... | RegisterView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterView:
def get(self, request, *args, **kwargs):
"""Render the register template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Register for new user and after create profile for him and sending email. Try to move his cart items to new cart."""
... | stack_v2_sparse_classes_36k_train_030695 | 10,591 | no_license | [
{
"docstring": "Render the register template",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Register for new user and after create profile for him and sending email. Try to move his cart items to new cart.",
"name": "post",
"signature": "def po... | 2 | null | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Render the register template
- def post(self, request, *args, **kwargs): Register for new user and after create profile for him a... | Implement the Python class `RegisterView` described below.
Class description:
Implement the RegisterView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Render the register template
- def post(self, request, *args, **kwargs): Register for new user and after create profile for him a... | e5190c1cb7d2b786b90cce9c88734427ea371fb8 | <|skeleton|>
class RegisterView:
def get(self, request, *args, **kwargs):
"""Render the register template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Register for new user and after create profile for him and sending email. Try to move his cart items to new cart."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterView:
def get(self, request, *args, **kwargs):
"""Render the register template"""
form = RegistrationForm()
context = {'form': form}
return render(request, 'accounts/register.html', context)
def post(self, request, *args, **kwargs):
"""Register for new user... | the_stack_v2_python_sparse | shop/accounts/views.py | Anych/shop | train | 0 | |
13b0eed2dab0ff1bf0b6253d6586e39df5f6bf3c | [
"dicts = {}\nfor i, char in enumerate(order):\n dicts[char] = chr(ord('a') + i)\nnew_words = []\nfor word in words:\n lists = list(word)\n new_words.append(''.join([dicts[i] for i in lists]))\nreturn new_words == sorted(new_words)",
"def is_valid(a, b, alphabet):\n for i, char in enumerate(a):\n ... | <|body_start_0|>
dicts = {}
for i, char in enumerate(order):
dicts[char] = chr(ord('a') + i)
new_words = []
for word in words:
lists = list(word)
new_words.append(''.join([dicts[i] for i in lists]))
return new_words == sorted(new_words)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
<|body_0|>
def isAlienSorted_1(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 24MS"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_030696 | 3,046 | no_license | [
{
"docstring": ":type words: List[str] :type order: str :rtype: bool 48 ms",
"name": "isAlienSorted",
"signature": "def isAlienSorted(self, words, order)"
},
{
"docstring": ":type words: List[str] :type order: str :rtype: bool 24MS",
"name": "isAlienSorted_1",
"signature": "def isAlienSo... | 2 | stack_v2_sparse_classes_30k_train_007656 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool 48 ms
- def isAlienSorted_1(self, words, order): :type words: List[str] :type order: s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool 48 ms
- def isAlienSorted_1(self, words, order): :type words: List[str] :type order: s... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
<|body_0|>
def isAlienSorted_1(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 24MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
dicts = {}
for i, char in enumerate(order):
dicts[char] = chr(ord('a') + i)
new_words = []
for word in words:
lists = list(word)
... | the_stack_v2_python_sparse | VerifyingAnAlienDictionary_953.py | 953250587/leetcode-python | train | 2 | |
ec3866cec08471e03bec4059ad89725643ebe1f4 | [
"assert relpos.is_contiguous()\nassert key_features.is_contiguous()\nassert query_batch_cnt.is_contiguous()\nassert key_batch_cnt.is_contiguous()\nassert index_pair_batch.is_contiguous()\nassert index_pair.is_contiguous()\nassert lookup_table.is_contiguous()\nb = query_batch_cnt.shape[0]\ntotal_query_num, local_siz... | <|body_start_0|>
assert relpos.is_contiguous()
assert key_features.is_contiguous()
assert query_batch_cnt.is_contiguous()
assert key_batch_cnt.is_contiguous()
assert index_pair_batch.is_contiguous()
assert index_pair.is_contiguous()
assert lookup_table.is_contiguo... | Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead) | RelativePositionalEmbeddingKIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativePositionalEmbeddingKIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def ... | stack_v2_sparse_classes_36k_train_030697 | 11,582 | no_license | [
{
"docstring": ":param ctx: :param relpos: A float tensor with shape [total_query_num, local_size] :param key_features: A float tensor with shape [total_key_num, nhead, hdim] :param query_batch_cnt: A integer tensor with shape [bs], indicating the query amount for each batch. :param key_batch_cnt: A integer ten... | 2 | stack_v2_sparse_classes_30k_train_017449 | Implement the Python class `RelativePositionalEmbeddingKIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_que... | Implement the Python class `RelativePositionalEmbeddingKIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_que... | bbc78ca91e851f0f04459b1a8bbe96ab44bf41bc | <|skeleton|>
class RelativePositionalEmbeddingKIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelativePositionalEmbeddingKIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def forward(ctx, ... | the_stack_v2_python_sparse | EQNet/eqnet/ops/crpe/crpe_utils_v2.py | dvlab-research/DeepVision3D | train | 94 |
9398155f5aacdf66c825bb0100b99586c4b02eb5 | [
"self.rootOne = LinkedList(2)\nself.rootOne.next = LinkedList(4)\nself.rootOne.next.next = LinkedList(7)\nself.rootOne.next.next.next = LinkedList(1)\nself.rootTwo = LinkedList(9)\nself.rootTwo.next = LinkedList(4)\nself.rootTwo.next.next = LinkedList(5)\nself.outputRoot = LinkedList(1)\nself.outputRoot.next = Link... | <|body_start_0|>
self.rootOne = LinkedList(2)
self.rootOne.next = LinkedList(4)
self.rootOne.next.next = LinkedList(7)
self.rootOne.next.next.next = LinkedList(1)
self.rootTwo = LinkedList(9)
self.rootTwo.next = LinkedList(4)
self.rootTwo.next.next = LinkedList(5)... | Class with unittests for SumOfLinkedList.py | test_SumOfLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_SumOfLinkedList:
"""Class with unittests for SumOfLinkedList.py"""
def setUp(self):
"""Sets up input and output."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_030698 | 1,424 | no_license | [
{
"docstring": "Sets up input and output.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_SumOfLinkedList` described below.
Class description:
Class with unittests for SumOfLinkedList.py
Method signatures and docstrings:
- def setUp(self): Sets up input and output.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_SumOfLinkedList` described below.
Class description:
Class with unittests for SumOfLinkedList.py
Method signatures and docstrings:
- def setUp(self): Sets up input and output.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_SumOfLink... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_SumOfLinkedList:
"""Class with unittests for SumOfLinkedList.py"""
def setUp(self):
"""Sets up input and output."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_SumOfLinkedList:
"""Class with unittests for SumOfLinkedList.py"""
def setUp(self):
"""Sets up input and output."""
self.rootOne = LinkedList(2)
self.rootOne.next = LinkedList(4)
self.rootOne.next.next = LinkedList(7)
self.rootOne.next.next.next = LinkedList(1... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/SumOfLinkedList/test_SumOfLinkedList.py | JakubKazimierski/PythonPortfolio | train | 9 |
4698bf1af466e0200bd3d567e41ba79766ab80bc | [
"try:\n modification = kwargs['modification']\nexcept KeyError:\n modification = timezone.now()\ntry:\n expiry = kwargs['expiry']\nexcept KeyError:\n expiry = self.get('_session_expiry')\nif not expiry:\n return properties.SESSION_COOKIE_AGE\nif not isinstance(expiry, datetime):\n return expiry\nd... | <|body_start_0|>
try:
modification = kwargs['modification']
except KeyError:
modification = timezone.now()
try:
expiry = kwargs['expiry']
except KeyError:
expiry = self.get('_session_expiry')
if not expiry:
return proper... | SessionStore | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionStore:
def get_expiry_age(self, **kwargs):
"""Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session."""
<|body_0|>
def get_expiry_date(... | stack_v2_sparse_classes_36k_train_030699 | 2,021 | permissive | [
{
"docstring": "Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session.",
"name": "get_expiry_age",
"signature": "def get_expiry_age(self, **kwargs)"
},
{
"docstrin... | 2 | null | Implement the Python class `SessionStore` described below.
Class description:
Implement the SessionStore class.
Method signatures and docstrings:
- def get_expiry_age(self, **kwargs): Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments s... | Implement the Python class `SessionStore` described below.
Class description:
Implement the SessionStore class.
Method signatures and docstrings:
- def get_expiry_age(self, **kwargs): Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments s... | 2b5f3562584137c8c9f5392265db1ab8ee8acf75 | <|skeleton|>
class SessionStore:
def get_expiry_age(self, **kwargs):
"""Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session."""
<|body_0|>
def get_expiry_date(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionStore:
def get_expiry_age(self, **kwargs):
"""Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session."""
try:
modification = kwargs['modificati... | the_stack_v2_python_sparse | bluebottle/clients/session_backends.py | onepercentclub/bluebottle | train | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.