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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e96d7de05b50715e87df5270ef3fda7390c1046 | [
"while num >= 10:\n string = str(num)\n num = 0\n for i in range(len(string)):\n num += int(string[i])\nreturn num",
"if num == 0:\n return 0\nelif num % 9 == 0:\n return 9\nelse:\n return num % 9"
] | <|body_start_0|>
while num >= 10:
string = str(num)
num = 0
for i in range(len(string)):
num += int(string[i])
return num
<|end_body_0|>
<|body_start_1|>
if num == 0:
return 0
elif num % 9 == 0:
return 9
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def addDigits2(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while num >= 10:
string = str(num)
num =... | stack_v2_sparse_classes_36k_train_005300 | 673 | no_license | [
{
"docstring": ":type num: int :rtype: int",
"name": "addDigits",
"signature": "def addDigits(self, num)"
},
{
"docstring": ":type num: int :rtype: int",
"name": "addDigits2",
"signature": "def addDigits2(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits2(self, num): :type num: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits2(self, num): :type num: int :rtype: int
<|skeleton|>
class Solution:
def addDigits(self, num):
... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def addDigits2(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
while num >= 10:
string = str(num)
num = 0
for i in range(len(string)):
num += int(string[i])
return num
def addDigits2(self, num):
""":type num: int :r... | the_stack_v2_python_sparse | 258. Add Digits/addDigits.py | Macielyoung/LeetCode | train | 1 | |
1c275a28c3f069b29d5d97c7be91b0c180829058 | [
"self.sess = tf.Session()\nself.saver = tf.train.import_meta_graph(meta)\nself.saver.restore(self.sess, ckpt)\nself.graph = tf.get_default_graph()\nself.names = sorted([t.name for t in self.graph.as_graph_def().node])\nself.images = self.graph.get_tensor_by_name('images:0')\nself.conv26 = self.graph.get_tensor_by_n... | <|body_start_0|>
self.sess = tf.Session()
self.saver = tf.train.import_meta_graph(meta)
self.saver.restore(self.sess, ckpt)
self.graph = tf.get_default_graph()
self.names = sorted([t.name for t in self.graph.as_graph_def().node])
self.images = self.graph.get_tensor_by_nam... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def __init__(self, meta, ckpt):
"""This is how you can load a model in TF without reconstructing it. :-)"""
<|body_0|>
def _process(self, img):
"""We also need to process it in a similar way, unfortunately."""
<|body_1|>
def _resize(self, arr):
... | stack_v2_sparse_classes_36k_train_005301 | 5,322 | no_license | [
{
"docstring": "This is how you can load a model in TF without reconstructing it. :-)",
"name": "__init__",
"signature": "def __init__(self, meta, ckpt)"
},
{
"docstring": "We also need to process it in a similar way, unfortunately.",
"name": "_process",
"signature": "def _process(self, ... | 4 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def __init__(self, meta, ckpt): This is how you can load a model in TF without reconstructing it. :-)
- def _process(self, img): We also need to process it in a similar way, unfortunatel... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def __init__(self, meta, ckpt): This is how you can load a model in TF without reconstructing it. :-)
- def _process(self, img): We also need to process it in a similar way, unfortunatel... | 98907194ae996291f326d8199229415900653a9a | <|skeleton|>
class Test:
def __init__(self, meta, ckpt):
"""This is how you can load a model in TF without reconstructing it. :-)"""
<|body_0|>
def _process(self, img):
"""We also need to process it in a similar way, unfortunately."""
<|body_1|>
def _resize(self, arr):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def __init__(self, meta, ckpt):
"""This is how you can load a model in TF without reconstructing it. :-)"""
self.sess = tf.Session()
self.saver = tf.train.import_meta_graph(meta)
self.saver.restore(self.sess, ckpt)
self.graph = tf.get_default_graph()
self.... | the_stack_v2_python_sparse | main/example_load_network_easier.py | DanielTakeshi/IL_ROS_HSR | train | 12 | |
e83027ca573d48809c9b9d04f75180082f8a081c | [
"super(GroupedModelChoiceField, self).__init__(queryset, *args, **kwargs)\nself.group_by_field = group_by_field\nif group_label is None:\n self.group_label = lambda group: group\nelse:\n self.group_label = group_label",
"if hasattr(self, '_choices'):\n return self._choices\nreturn GroupedModelChoiceItera... | <|body_start_0|>
super(GroupedModelChoiceField, self).__init__(queryset, *args, **kwargs)
self.group_by_field = group_by_field
if group_label is None:
self.group_label = lambda group: group
else:
self.group_label = group_label
<|end_body_0|>
<|body_start_1|>
... | GroupedModelChoiceField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupedModelChoiceField:
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is the name of a field on the model group_label is a function to return a label for each choice group"""
<|body_0|>
def _get_choices(self):
"""... | stack_v2_sparse_classes_36k_train_005302 | 2,408 | permissive | [
{
"docstring": "group_by_field is the name of a field on the model group_label is a function to return a label for each choice group",
"name": "__init__",
"signature": "def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs)"
},
{
"docstring": "Exactly as per ModelChoiceF... | 2 | stack_v2_sparse_classes_30k_train_007626 | Implement the Python class `GroupedModelChoiceField` described below.
Class description:
Implement the GroupedModelChoiceField class.
Method signatures and docstrings:
- def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs): group_by_field is the name of a field on the model group_label is a... | Implement the Python class `GroupedModelChoiceField` described below.
Class description:
Implement the GroupedModelChoiceField class.
Method signatures and docstrings:
- def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs): group_by_field is the name of a field on the model group_label is a... | be04a9598c55c969ef130cc64ad27e7b3fe50465 | <|skeleton|>
class GroupedModelChoiceField:
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is the name of a field on the model group_label is a function to return a label for each choice group"""
<|body_0|>
def _get_choices(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupedModelChoiceField:
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is the name of a field on the model group_label is a function to return a label for each choice group"""
super(GroupedModelChoiceField, self).__init__(queryset, *args, **... | the_stack_v2_python_sparse | events/fields.py | WPI-LNL/lnldb | train | 8 | |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('semester_result', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Semester Result To Display'\ncontext['detail_text'] = ... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('semester_result', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['... | View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid. | ShowSemesterResultView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowSemesterResultView:
"""View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_005303 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_019158 | Implement the Python class `ShowSemesterResultView` described below.
Class description:
View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the succes... | Implement the Python class `ShowSemesterResultView` described below.
Class description:
View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the succes... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ShowSemesterResultView:
"""View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShowSemesterResultView:
"""View for choosing which semester result to display. Check that the user's account is still active. Redirects to semester_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_data
... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
cb68199199f518639e8d7314347556e2be7fa244 | [
"triplet = [nums[0], None, None]\nfor elem in nums[1:]:\n if not triplet[1] and elem < triplet[0]:\n triplet[0] = elem\n elif not triplet[1] or (not triplet[2] and triplet[0] < elem < triplet[1]):\n triplet[1] = elem\n elif not triplet[2] and elem > triplet[1]:\n print(triplet)\n ... | <|body_start_0|>
triplet = [nums[0], None, None]
for elem in nums[1:]:
if not triplet[1] and elem < triplet[0]:
triplet[0] = elem
elif not triplet[1] or (not triplet[2] and triplet[0] < elem < triplet[1]):
triplet[1] = elem
elif not tri... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums) -> bool:
"""the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions"""
<|body_0|>
def increasingTriplet(self, nums) -> bool:
"""trick: we can directly replace the small... | stack_v2_sparse_classes_36k_train_005304 | 2,078 | permissive | [
{
"docstring": "the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums) -> bool"
},
{
"docstring": "trick: we can directly replace the small when meet a value sma... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums) -> bool: the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions
- def increasingTriplet(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums) -> bool: the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions
- def increasingTriplet(... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def increasingTriplet(self, nums) -> bool:
"""the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions"""
<|body_0|>
def increasingTriplet(self, nums) -> bool:
"""trick: we can directly replace the small... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingTriplet(self, nums) -> bool:
"""the code is wrong, but it could be a reference of the right code. There is a hidden trick between two versions"""
triplet = [nums[0], None, None]
for elem in nums[1:]:
if not triplet[1] and elem < triplet[0]:
... | the_stack_v2_python_sparse | Leetcode/Intermediate/Array_and_string/334_Increasing_Triplet_Subsequence.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
86c1f23e06e2c877befa309e16ace41bf19f59c7 | [
"self.ec2 = AwsClient().connect('ec2', region_name)\ntry:\n self.ec2.describe_vpc_endpoints()\nexcept EndpointConnectionError:\n print('Ec2 endpoint resource is not available in this aws region')\n return",
"for endpoint in self.list_endpoints(older_than_seconds):\n try:\n self.ec2.delete_vpc_e... | <|body_start_0|>
self.ec2 = AwsClient().connect('ec2', region_name)
try:
self.ec2.describe_vpc_endpoints()
except EndpointConnectionError:
print('Ec2 endpoint resource is not available in this aws region')
return
<|end_body_0|>
<|body_start_1|>
for en... | Abstract endpoint nuke in a class. | NukeEndpoint | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NukeEndpoint:
"""Abstract endpoint nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize endpoint nuke."""
<|body_0|>
def nuke(self, older_than_seconds: float) -> None:
"""Endpoint deleting function. Deleting all aws endpoint with a time... | stack_v2_sparse_classes_36k_train_005305 | 1,923 | permissive | [
{
"docstring": "Initialize endpoint nuke.",
"name": "__init__",
"signature": "def __init__(self, region_name=None) -> None"
},
{
"docstring": "Endpoint deleting function. Deleting all aws endpoint with a timestamp greater than older_than_seconds. :param int older_than_seconds: The timestamp in s... | 3 | stack_v2_sparse_classes_30k_train_012428 | Implement the Python class `NukeEndpoint` described below.
Class description:
Abstract endpoint nuke in a class.
Method signatures and docstrings:
- def __init__(self, region_name=None) -> None: Initialize endpoint nuke.
- def nuke(self, older_than_seconds: float) -> None: Endpoint deleting function. Deleting all aws... | Implement the Python class `NukeEndpoint` described below.
Class description:
Abstract endpoint nuke in a class.
Method signatures and docstrings:
- def __init__(self, region_name=None) -> None: Initialize endpoint nuke.
- def nuke(self, older_than_seconds: float) -> None: Endpoint deleting function. Deleting all aws... | 25c4159e71935a9903a41540c168992586c5ba0c | <|skeleton|>
class NukeEndpoint:
"""Abstract endpoint nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize endpoint nuke."""
<|body_0|>
def nuke(self, older_than_seconds: float) -> None:
"""Endpoint deleting function. Deleting all aws endpoint with a time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NukeEndpoint:
"""Abstract endpoint nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize endpoint nuke."""
self.ec2 = AwsClient().connect('ec2', region_name)
try:
self.ec2.describe_vpc_endpoints()
except EndpointConnectionError:
... | the_stack_v2_python_sparse | package/nuke/network/endpoint.py | diodonfrost/terraform-aws-lambda-nuke | train | 20 |
eea24e4cdef7ddc1605764259cfdbf57b61415e2 | [
"self.text = text\nself.rect = pygame.Rect(pos, size)\nself.action = action\nself.params = params if params is not None else []\nself.enabled = enabled\nself._font = pygame.font.SysFont('comicsansms', 18)",
"color = (255, 255, 255)\ntext_color = (0, 0, 0) if self.enabled else (200, 200, 200)\nif self.rect.collide... | <|body_start_0|>
self.text = text
self.rect = pygame.Rect(pos, size)
self.action = action
self.params = params if params is not None else []
self.enabled = enabled
self._font = pygame.font.SysFont('comicsansms', 18)
<|end_body_0|>
<|body_start_1|>
color = (255, 2... | Class to assist in creation of buttons. | Button | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Button:
"""Class to assist in creation of buttons."""
def __init__(self, text, pos, size, action, params=None, enabled=True):
"""Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button ... | stack_v2_sparse_classes_36k_train_005306 | 6,310 | no_license | [
{
"docstring": "Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button (width, height). :parm action: Function to call when clicked. :parm params: Parameters to call action with when called. :parm enabled: Parame... | 3 | stack_v2_sparse_classes_30k_train_005395 | Implement the Python class `Button` described below.
Class description:
Class to assist in creation of buttons.
Method signatures and docstrings:
- def __init__(self, text, pos, size, action, params=None, enabled=True): Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place top... | Implement the Python class `Button` described below.
Class description:
Class to assist in creation of buttons.
Method signatures and docstrings:
- def __init__(self, text, pos, size, action, params=None, enabled=True): Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place top... | 4faeace5327e4e702ba57e8fdc59e313c29d1a42 | <|skeleton|>
class Button:
"""Class to assist in creation of buttons."""
def __init__(self, text, pos, size, action, params=None, enabled=True):
"""Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Button:
"""Class to assist in creation of buttons."""
def __init__(self, text, pos, size, action, params=None, enabled=True):
"""Initialize a single Button. :param text: Text to write on button. :parm pos: Position to place topleft corner of button (x, y). :parm size: Size of button (width, heigh... | the_stack_v2_python_sparse | src/gui/utils.py | antatranta/Waids-and-Wyverns | train | 0 |
f20ed0c35271315c81ba179f5f36dfcc56d7ab27 | [
"MOD = int(1000000000.0 + 7)\ncnt = Counter(arr)\nkeys = list(sorted(cnt.keys()))\n\n@lru_cache(None)\ndef comb(n, r):\n r = min(r, n - r)\n if r == 0:\n return 1\n return int(comb(n - 1, r - 1) * n / r) % MOD\n\ndef backtrack(i, t, cur):\n if t == 0 and sum(cur.values()) == 3:\n ret = 1\n... | <|body_start_0|>
MOD = int(1000000000.0 + 7)
cnt = Counter(arr)
keys = list(sorted(cnt.keys()))
@lru_cache(None)
def comb(n, r):
r = min(r, n - r)
if r == 0:
return 1
return int(comb(n - 1, r - 1) * n / r) % MOD
def ba... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
"""TLE. This can be a generic solution with some modification."""
<|body_0|>
def threeSumMulti(self, arr: List[int], target: int) -> int:
"""Time complexity: O(n^2) Space complexity: O(n)"""
... | stack_v2_sparse_classes_36k_train_005307 | 3,954 | no_license | [
{
"docstring": "TLE. This can be a generic solution with some modification.",
"name": "threeSumMulti",
"signature": "def threeSumMulti(self, arr: List[int], target: int) -> int"
},
{
"docstring": "Time complexity: O(n^2) Space complexity: O(n)",
"name": "threeSumMulti",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_006804 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumMulti(self, arr: List[int], target: int) -> int: TLE. This can be a generic solution with some modification.
- def threeSumMulti(self, arr: List[int], target: int) ->... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumMulti(self, arr: List[int], target: int) -> int: TLE. This can be a generic solution with some modification.
- def threeSumMulti(self, arr: List[int], target: int) ->... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
"""TLE. This can be a generic solution with some modification."""
<|body_0|>
def threeSumMulti(self, arr: List[int], target: int) -> int:
"""Time complexity: O(n^2) Space complexity: O(n)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
"""TLE. This can be a generic solution with some modification."""
MOD = int(1000000000.0 + 7)
cnt = Counter(arr)
keys = list(sorted(cnt.keys()))
@lru_cache(None)
def comb(n, r):
... | the_stack_v2_python_sparse | leetcode/solved/959_3Sum_With_Multiplicity/solution.py | sungminoh/algorithms | train | 0 | |
f62546fb6ca079571f40f83fb70b31a843a736e3 | [
"user_filename = os.path.realpath(user_filename)\nif not os.path.isfile(user_filename):\n raise FileNotFoundError('file does not exist: {}'.format(user_filename))\nwith open(user_filename) as f:\n data = f.read().strip()\nuser_ops = self._simple_string_match(data)\nreturn user_ops",
"processed_user_text = u... | <|body_start_0|>
user_filename = os.path.realpath(user_filename)
if not os.path.isfile(user_filename):
raise FileNotFoundError('file does not exist: {}'.format(user_filename))
with open(user_filename) as f:
data = f.read().strip()
user_ops = self._simple_string_ma... | A simple parser that works by string matching: Code uses an op if it is found anywhere in the text. | SimpleParser | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleParser:
"""A simple parser that works by string matching: Code uses an op if it is found anywhere in the text."""
def parse(self, user_filename):
"""Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file"""
... | stack_v2_sparse_classes_36k_train_005308 | 2,666 | permissive | [
{
"docstring": "Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file",
"name": "parse",
"signature": "def parse(self, user_filename)"
},
{
"docstring": "Find and return ops in the user code (provided as a string). :param use... | 2 | null | Implement the Python class `SimpleParser` described below.
Class description:
A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.
Method signatures and docstrings:
- def parse(self, user_filename): Find and return ops in the user file. :param user_filename: filename of ... | Implement the Python class `SimpleParser` described below.
Class description:
A simple parser that works by string matching: Code uses an op if it is found anywhere in the text.
Method signatures and docstrings:
- def parse(self, user_filename): Find and return ops in the user file. :param user_filename: filename of ... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class SimpleParser:
"""A simple parser that works by string matching: Code uses an op if it is found anywhere in the text."""
def parse(self, user_filename):
"""Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleParser:
"""A simple parser that works by string matching: Code uses an op if it is found anywhere in the text."""
def parse(self, user_filename):
"""Find and return ops in the user file. :param user_filename: filename of user code :return: a list of ops present in the file"""
user_f... | the_stack_v2_python_sparse | mindspore/lite/tools/dataset/cropper/parser.py | mindspore-ai/mindspore | train | 4,178 |
8ec6597d5796ab7a2256d297d46718de9915f5ba | [
"self._linode = li\nself._node_id = node_id\nself._attr_extra_state_attributes = {}\nself._attr_name = None",
"data = None\nself._linode.update()\nif self._linode.data is not None:\n for node in self._linode.data:\n if node.id == self._node_id:\n data = node\nif data is not None:\n self._a... | <|body_start_0|>
self._linode = li
self._node_id = node_id
self._attr_extra_state_attributes = {}
self._attr_name = None
<|end_body_0|>
<|body_start_1|>
data = None
self._linode.update()
if self._linode.data is not None:
for node in self._linode.data:... | Representation of a Linode droplet sensor. | LinodeBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinodeBinarySensor:
"""Representation of a Linode droplet sensor."""
def __init__(self, li, node_id):
"""Initialize a new Linode sensor."""
<|body_0|>
def update(self) -> None:
"""Update state of sensor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005309 | 2,638 | permissive | [
{
"docstring": "Initialize a new Linode sensor.",
"name": "__init__",
"signature": "def __init__(self, li, node_id)"
},
{
"docstring": "Update state of sensor.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_014805 | Implement the Python class `LinodeBinarySensor` described below.
Class description:
Representation of a Linode droplet sensor.
Method signatures and docstrings:
- def __init__(self, li, node_id): Initialize a new Linode sensor.
- def update(self) -> None: Update state of sensor. | Implement the Python class `LinodeBinarySensor` described below.
Class description:
Representation of a Linode droplet sensor.
Method signatures and docstrings:
- def __init__(self, li, node_id): Initialize a new Linode sensor.
- def update(self) -> None: Update state of sensor.
<|skeleton|>
class LinodeBinarySensor... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class LinodeBinarySensor:
"""Representation of a Linode droplet sensor."""
def __init__(self, li, node_id):
"""Initialize a new Linode sensor."""
<|body_0|>
def update(self) -> None:
"""Update state of sensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinodeBinarySensor:
"""Representation of a Linode droplet sensor."""
def __init__(self, li, node_id):
"""Initialize a new Linode sensor."""
self._linode = li
self._node_id = node_id
self._attr_extra_state_attributes = {}
self._attr_name = None
def update(self)... | the_stack_v2_python_sparse | homeassistant/components/linode/binary_sensor.py | home-assistant/core | train | 35,501 |
328333e39e08143d2f5baa92665b415619f10277 | [
"try:\n return trigger.after.source_content.identifier\nexcept AttributeError as exc:\n self.fail(exc, 'No source content identifier on post-event state')",
"exc_type = type(exc)\nif exc_type in (exceptions.BadResponse, exceptions.ConnectionFailed):\n raise Recoverable('Encountered %s; try again' % exc) ... | <|body_start_0|>
try:
return trigger.after.source_content.identifier
except AttributeError as exc:
self.fail(exc, 'No source content identifier on post-event state')
<|end_body_0|>
<|body_start_1|>
exc_type = type(exc)
if exc_type in (exceptions.BadResponse, exce... | Extract plain text from a compiled PDF. | PlainTextExtraction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlainTextExtraction:
"""Extract plain text from a compiled PDF."""
def source_id(self, trigger: Trigger) -> int:
"""Get the source ID for the submission content."""
<|body_0|>
def handle_plaintext_exception(self, exc: Exception) -> None:
"""Handle exceptions rais... | stack_v2_sparse_classes_36k_train_005310 | 8,823 | permissive | [
{
"docstring": "Get the source ID for the submission content.",
"name": "source_id",
"signature": "def source_id(self, trigger: Trigger) -> int"
},
{
"docstring": "Handle exceptions raised when calling the plain text service.",
"name": "handle_plaintext_exception",
"signature": "def hand... | 5 | stack_v2_sparse_classes_30k_train_012159 | Implement the Python class `PlainTextExtraction` described below.
Class description:
Extract plain text from a compiled PDF.
Method signatures and docstrings:
- def source_id(self, trigger: Trigger) -> int: Get the source ID for the submission content.
- def handle_plaintext_exception(self, exc: Exception) -> None: H... | Implement the Python class `PlainTextExtraction` described below.
Class description:
Extract plain text from a compiled PDF.
Method signatures and docstrings:
- def source_id(self, trigger: Trigger) -> int: Get the source ID for the submission content.
- def handle_plaintext_exception(self, exc: Exception) -> None: H... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class PlainTextExtraction:
"""Extract plain text from a compiled PDF."""
def source_id(self, trigger: Trigger) -> int:
"""Get the source ID for the submission content."""
<|body_0|>
def handle_plaintext_exception(self, exc: Exception) -> None:
"""Handle exceptions rais... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlainTextExtraction:
"""Extract plain text from a compiled PDF."""
def source_id(self, trigger: Trigger) -> int:
"""Get the source ID for the submission content."""
try:
return trigger.after.source_content.identifier
except AttributeError as exc:
self.fail(... | the_stack_v2_python_sparse | agent/agent/process/classification_and_content.py | arXiv/arxiv-submission-core | train | 14 |
849fdcf054bcb9eaa8599cf4a744c30dd3a3ffa9 | [
"self.code = '{}{}{}'.format(randint(0, 1), randint(0, 1), randint(0, 1))\nself.count = 0\nself.guessed_codes = []",
"story_tag.delete(1.0, END)\nCortexVault_story = \"You find yourself inside a metal hallway, black with red lights.\\nThere are wires everywhere. You are inside a complicated machine.\\nThe Doctor ... | <|body_start_0|>
self.code = '{}{}{}'.format(randint(0, 1), randint(0, 1), randint(0, 1))
self.count = 0
self.guessed_codes = []
<|end_body_0|>
<|body_start_1|>
story_tag.delete(1.0, END)
CortexVault_story = "You find yourself inside a metal hallway, black with red lights.\nTher... | Creates the second scene of the game, in the cortex vault | CortexVault | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CortexVault:
"""Creates the second scene of the game, in the cortex vault"""
def __init__(self):
"""creates game variables"""
<|body_0|>
def enter(self, story_tag, action_tag):
"""starts the cortex vault scene"""
<|body_1|>
def crack_code(self, story... | stack_v2_sparse_classes_36k_train_005311 | 5,127 | no_license | [
{
"docstring": "creates game variables",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "starts the cortex vault scene",
"name": "enter",
"signature": "def enter(self, story_tag, action_tag)"
},
{
"docstring": "You must crack a simple code to advance to t... | 5 | stack_v2_sparse_classes_30k_train_019745 | Implement the Python class `CortexVault` described below.
Class description:
Creates the second scene of the game, in the cortex vault
Method signatures and docstrings:
- def __init__(self): creates game variables
- def enter(self, story_tag, action_tag): starts the cortex vault scene
- def crack_code(self, story_tag... | Implement the Python class `CortexVault` described below.
Class description:
Creates the second scene of the game, in the cortex vault
Method signatures and docstrings:
- def __init__(self): creates game variables
- def enter(self, story_tag, action_tag): starts the cortex vault scene
- def crack_code(self, story_tag... | 32c8877191bb08da536c95e5613bca2f01aeaf8f | <|skeleton|>
class CortexVault:
"""Creates the second scene of the game, in the cortex vault"""
def __init__(self):
"""creates game variables"""
<|body_0|>
def enter(self, story_tag, action_tag):
"""starts the cortex vault scene"""
<|body_1|>
def crack_code(self, story... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CortexVault:
"""Creates the second scene of the game, in the cortex vault"""
def __init__(self):
"""creates game variables"""
self.code = '{}{}{}'.format(randint(0, 1), randint(0, 1), randint(0, 1))
self.count = 0
self.guessed_codes = []
def enter(self, story_tag, act... | the_stack_v2_python_sparse | TkDalek/cortex_vault.py | ginnypx1/IntoTheDalek | train | 2 |
d8c935d69c0e96a1ff5f5b4b86cf36c59801714f | [
"super().__init__()\nself.user32 = ctypes.WinDLL('user32')\nself.gdi32 = ctypes.WinDLL('gdi32')\nself._set_cfunctions()\nself._set_dpi_awareness()\nself._bbox = {'height': 0, 'width': 0}\nself._data = ctypes.create_string_buffer(0)\nsrcdc = self._get_srcdc()\nif not MSS.memdc:\n MSS.memdc = self.gdi32.CreateComp... | <|body_start_0|>
super().__init__()
self.user32 = ctypes.WinDLL('user32')
self.gdi32 = ctypes.WinDLL('gdi32')
self._set_cfunctions()
self._set_dpi_awareness()
self._bbox = {'height': 0, 'width': 0}
self._data = ctypes.create_string_buffer(0)
srcdc = self._... | Multiple ScreenShots implementation for Microsoft Windows. | MSS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
<|body_0|>
def _set_cfunctions(self):
"""Set all ctypes functions and attach them to attributes."""
<|body_1|>
def _set_dpi_... | stack_v2_sparse_classes_36k_train_005312 | 9,348 | permissive | [
{
"docstring": "Windows initialisations.",
"name": "__init__",
"signature": "def __init__(self, **_)"
},
{
"docstring": "Set all ctypes functions and attach them to attributes.",
"name": "_set_cfunctions",
"signature": "def _set_cfunctions(self)"
},
{
"docstring": "Set DPI aware ... | 6 | stack_v2_sparse_classes_30k_train_007829 | Implement the Python class `MSS` described below.
Class description:
Multiple ScreenShots implementation for Microsoft Windows.
Method signatures and docstrings:
- def __init__(self, **_): Windows initialisations.
- def _set_cfunctions(self): Set all ctypes functions and attach them to attributes.
- def _set_dpi_awar... | Implement the Python class `MSS` described below.
Class description:
Multiple ScreenShots implementation for Microsoft Windows.
Method signatures and docstrings:
- def __init__(self, **_): Windows initialisations.
- def _set_cfunctions(self): Set all ctypes functions and attach them to attributes.
- def _set_dpi_awar... | a64ad181b5087f0f0d6d246be0a722015cf447d0 | <|skeleton|>
class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
<|body_0|>
def _set_cfunctions(self):
"""Set all ctypes functions and attach them to attributes."""
<|body_1|>
def _set_dpi_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSS:
"""Multiple ScreenShots implementation for Microsoft Windows."""
def __init__(self, **_):
"""Windows initialisations."""
super().__init__()
self.user32 = ctypes.WinDLL('user32')
self.gdi32 = ctypes.WinDLL('gdi32')
self._set_cfunctions()
self._set_dpi_a... | the_stack_v2_python_sparse | venv/Lib/site-packages/mss/windows.py | Ramen-Shaman/Reco-PC-Server | train | 0 |
57b1e04975007a3ef7f568210e2df10349342df9 | [
"super().__init__(name, 's')\nself.parameters_dict = dict()\nself.value_list.append('Yes')",
"model = kwargs['model']\niteration = kwargs['iteration']\nself.parameters_dict[iteration] = model.get_parameter_vector().copy()"
] | <|body_start_0|>
super().__init__(name, 's')
self.parameters_dict = dict()
self.value_list.append('Yes')
<|end_body_0|>
<|body_start_1|>
model = kwargs['model']
iteration = kwargs['iteration']
self.parameters_dict[iteration] = model.get_parameter_vector().copy()
<|end_bo... | This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training. | Parameters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameters:
"""This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training."""
def __init__(self, name='Parameters'):
"""Initiali... | stack_v2_sparse_classes_36k_train_005313 | 20,983 | no_license | [
{
"docstring": "Initialise this Parameters column",
"name": "__init__",
"signature": "def __init__(self, name='Parameters')"
},
{
"docstring": "Store the parameters of the model",
"name": "update",
"signature": "def update(self, kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012841 | Implement the Python class `Parameters` described below.
Class description:
This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training.
Method signatures and docs... | Implement the Python class `Parameters` described below.
Class description:
This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training.
Method signatures and docs... | 389dbb3c4f84f8498ea879980b82e2cf543e5441 | <|skeleton|>
class Parameters:
"""This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training."""
def __init__(self, name='Parameters'):
"""Initiali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parameters:
"""This column is for storing the parameters of the model at different points during training. Once training is complete, this object can be used to plot functions of the model as its parameters evolve during training."""
def __init__(self, name='Parameters'):
"""Initialise this Param... | the_stack_v2_python_sparse | optimisers/columns.py | jakelevi1996/backprop2 | train | 0 |
59b0a26114af22dbfaee93ff23ee86ca39e2fdf5 | [
"probabilities = []\nlist_theoretical_amplitude = []\nbest_algorithms = []\nconfigurations = []\nlist_number_calls_made = []\nimprovements = []\nfor eta_group in self._eta_groups:\n self._global_eta_group = eta_group\n result = self._compute_theoretical_best_configuration()\n best_algorithms.append(result[... | <|body_start_0|>
probabilities = []
list_theoretical_amplitude = []
best_algorithms = []
configurations = []
list_number_calls_made = []
improvements = []
for eta_group in self._eta_groups:
self._global_eta_group = eta_group
result = self._... | Representation of the theoretical One Shot Optimization | TheoreticalOneShotEntangledOptimization | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheoreticalOneShotEntangledOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations:
"""Finds out the theoretical optimal entangled configuration for each pair of atte... | stack_v2_sparse_classes_36k_train_005314 | 3,912 | permissive | [
{
"docstring": "Finds out the theoretical optimal entangled configuration for each pair of attenuation levels",
"name": "compute_theoretical_optimal_results",
"signature": "def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations"
},
{
"docstring": "Find ... | 2 | stack_v2_sparse_classes_30k_train_016271 | Implement the Python class `TheoreticalOneShotEntangledOptimization` described below.
Class description:
Representation of the theoretical One Shot Optimization
Method signatures and docstrings:
- def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: Finds out the theoreti... | Implement the Python class `TheoreticalOneShotEntangledOptimization` described below.
Class description:
Representation of the theoretical One Shot Optimization
Method signatures and docstrings:
- def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: Finds out the theoreti... | ea37fca21fc4c8cf7ac6a39b3a6666e8a4fe5a19 | <|skeleton|>
class TheoreticalOneShotEntangledOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations:
"""Finds out the theoretical optimal entangled configuration for each pair of atte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TheoreticalOneShotEntangledOptimization:
"""Representation of the theoretical One Shot Optimization"""
def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations:
"""Finds out the theoretical optimal entangled configuration for each pair of attenuation level... | the_stack_v2_python_sparse | qcd/optimizations/theoreticaloneshotentangledoptimization.py | iamtxena/quantum-channel-discrimination | train | 0 |
af2b089179ebfdbf5dc6bc8b5cb01c0c7379711e | [
"with open(filename, mode=mode, encoding=encod) as f:\n eeg = f.read()\n U = np.array([float(i) for i in filter(lambda x: x, eeg.split('\\n'))])\n if shi == 0:\n return self.jinshishang(U)\n else:\n return self.jinshishangbiao(U)",
"U = np.array([float(i) for i in filter(lambda x: x, dat... | <|body_start_0|>
with open(filename, mode=mode, encoding=encod) as f:
eeg = f.read()
U = np.array([float(i) for i in filter(lambda x: x, eeg.split('\n'))])
if shi == 0:
return self.jinshishang(U)
else:
return self.jinshishangbiao(U)... | 打开文件流分析近似熵和基于二进制流分析 | FileApEn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileApEn:
"""打开文件流分析近似熵和基于二进制流分析"""
def anal_file(self, filename, mode='r', encod='utf-8', shi=0):
"""打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:"""
<|body_0|>
def anal_string(self, data: str, shi=0):
"""传入字符串形式的eeg数据 :param s... | stack_v2_sparse_classes_36k_train_005315 | 13,083 | no_license | [
{
"docstring": "打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:",
"name": "anal_file",
"signature": "def anal_file(self, filename, mode='r', encod='utf-8', shi=0)"
},
{
"docstring": "传入字符串形式的eeg数据 :param shi: :param data: :return:",
"name": "anal_string",
... | 2 | stack_v2_sparse_classes_30k_train_021323 | Implement the Python class `FileApEn` described below.
Class description:
打开文件流分析近似熵和基于二进制流分析
Method signatures and docstrings:
- def anal_file(self, filename, mode='r', encod='utf-8', shi=0): 打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:
- def anal_string(self, data: str, shi=0): 传... | Implement the Python class `FileApEn` described below.
Class description:
打开文件流分析近似熵和基于二进制流分析
Method signatures and docstrings:
- def anal_file(self, filename, mode='r', encod='utf-8', shi=0): 打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:
- def anal_string(self, data: str, shi=0): 传... | 086fea3b84480829e25668354799ca46ad68744e | <|skeleton|>
class FileApEn:
"""打开文件流分析近似熵和基于二进制流分析"""
def anal_file(self, filename, mode='r', encod='utf-8', shi=0):
"""打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:"""
<|body_0|>
def anal_string(self, data: str, shi=0):
"""传入字符串形式的eeg数据 :param s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileApEn:
"""打开文件流分析近似熵和基于二进制流分析"""
def anal_file(self, filename, mode='r', encod='utf-8', shi=0):
"""打开eeg的文件读取eeg数据 :param filename: :param mode: :param shi: :param encod: :return:"""
with open(filename, mode=mode, encoding=encod) as f:
eeg = f.read()
U = np.arra... | the_stack_v2_python_sparse | sleep_eeg_analysis/apen.py | muyi110/EmotionRecognition | train | 2 |
deb7d3afa3107ccd0a51883df744bc1e3b5100c4 | [
"if not root:\n return 0\nleft_height = self.max_depth_(root.left)\nright_height = self.max_depth_(root.right)\nreturn max(left_height, right_height) + 1",
"stack = []\nif root:\n stack.append((1, root))\ndepth = 0\nwhile stack:\n curr_depth, root = stack.pop()\n if root:\n depth = max(curr_dep... | <|body_start_0|>
if not root:
return 0
left_height = self.max_depth_(root.left)
right_height = self.max_depth_(root.right)
return max(left_height, right_height) + 1
<|end_body_0|>
<|body_start_1|>
stack = []
if root:
stack.append((1, root))
... | Tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tree:
def max_depth_(self, root: 'TreeNode') -> int:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
<|body_0|>
def max_depth(self, root: 'TreeNode') -> int:
"""Approach: Iteration / BST :param root: :return:"""
<|... | stack_v2_sparse_classes_36k_train_005316 | 1,062 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:",
"name": "max_depth_",
"signature": "def max_depth_(self, root: 'TreeNode') -> int"
},
{
"docstring": "Approach: Iteration / BST :param root: :return:",
"name": "max_depth",
"signature... | 2 | null | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def max_depth_(self, root: 'TreeNode') -> int: Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:
- def max_depth(self, root: 'TreeNode') -> int: Appr... | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def max_depth_(self, root: 'TreeNode') -> int: Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:
- def max_depth(self, root: 'TreeNode') -> int: Appr... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Tree:
def max_depth_(self, root: 'TreeNode') -> int:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
<|body_0|>
def max_depth(self, root: 'TreeNode') -> int:
"""Approach: Iteration / BST :param root: :return:"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tree:
def max_depth_(self, root: 'TreeNode') -> int:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param root: :return:"""
if not root:
return 0
left_height = self.max_depth_(root.left)
right_height = self.max_depth_(root.right)
return... | the_stack_v2_python_sparse | revisited_2021/tree/max_dept_of_bst.py | Shiv2157k/leet_code | train | 1 | |
e445912300bf78c0a1ba487a9cb69dbbcf6e74b6 | [
"if not nums:\n return -1\nl, r = (0, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[l] <= nums[m]:\n if nums[l] <= target < nums[m]:\n r = m - 1\n else:\n l = m + 1\n elif nums[m] < target <= nums[r]:\n ... | <|body_start_0|>
if not nums:
return -1
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[l] <= nums[m]:
if nums[l] <= target < nums[m]:
r = m - 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户"""
<|body_0|>
def search1(self, nums: List[int], target: int) -> int:
"""33 执行用时: 44 ms , 在所有 Python3 提交中击... | stack_v2_sparse_classes_36k_train_005317 | 4,457 | no_license | [
{
"docstring": "33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) -> int"
},
{
"docstring": "33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.48% 的用户 内存消耗: 15.2 MB , 在所有 Python3 提交中击... | 3 | stack_v2_sparse_classes_30k_train_012220 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: 33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户
- def search1(self, nums: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: 33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户
- def search1(self, nums: List... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def search(self, nums: List[int], target: int) -> int:
"""33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户"""
<|body_0|>
def search1(self, nums: List[int], target: int) -> int:
"""33 执行用时: 44 ms , 在所有 Python3 提交中击... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums: List[int], target: int) -> int:
"""33 执行用时: 44 ms , 在所有 Python3 提交中击败了 36.20% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 91.10% 的用户"""
if not nums:
return -1
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
... | the_stack_v2_python_sparse | 搜索旋转排序数组1&2.py | nomboy/leetcode | train | 0 | |
1e9265aeb881ff02b9d5435fff1c45af5f9b0a99 | [
"group = Group.objects.get(pk=self.kwargs['pk'])\nuser = self.request.user\nif group.member_list_published or user.is_superuser or group.owners.filter(pk=user.pk).exists():\n queryset = group.get_members_avatar_prioritized().exclude(pk__in=group.owners.all().only('pk'))\n if self.request.GET.get('q'):\n ... | <|body_start_0|>
group = Group.objects.get(pk=self.kwargs['pk'])
user = self.request.user
if group.member_list_published or user.is_superuser or group.owners.filter(pk=user.pk).exists():
queryset = group.get_members_avatar_prioritized().exclude(pk__in=group.owners.all().only('pk'))
... | View for listing of members of a group. | GroupMemberListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupMemberListView:
"""View for listing of members of a group."""
def get_queryset(self):
"""Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner."""
<|body_0|>
def get_context_data(self, **kwargs)... | stack_v2_sparse_classes_36k_train_005318 | 19,778 | permissive | [
{
"docstring": "Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Add the group to the context.",
"name": "get_context_data",
"s... | 2 | stack_v2_sparse_classes_30k_train_017220 | Implement the Python class `GroupMemberListView` described below.
Class description:
View for listing of members of a group.
Method signatures and docstrings:
- def get_queryset(self): Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner.
- def ... | Implement the Python class `GroupMemberListView` described below.
Class description:
View for listing of members of a group.
Method signatures and docstrings:
- def get_queryset(self): Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner.
- def ... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class GroupMemberListView:
"""View for listing of members of a group."""
def get_queryset(self):
"""Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner."""
<|body_0|>
def get_context_data(self, **kwargs)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupMemberListView:
"""View for listing of members of a group."""
def get_queryset(self):
"""Only get members of the current group. Group must have member_list_published or the user has to be superuser or a group owner."""
group = Group.objects.get(pk=self.kwargs['pk'])
user = se... | the_stack_v2_python_sparse | open_connect/groups/views.py | ofa/connect | train | 66 |
c570b89332ebcfa5b6aee651c4b0a0c773dac507 | [
"super().__init__(self.PROBLEM_NAME)\nself.root_node = root_node\nself.label1 = label1\nself.label2 = label2",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\npath1 = []\nself.path_to_node(self.root_node, path1, self.label1)\npath2 = []\nself.path_to_node(self.root_node, path2, self.label2)\ni = 0\nwh... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.root_node = root_node
self.label1 = label1
self.label2 = label2
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
path1 = []
self.path_to_node(self.root_node, path1,... | Find Distance Between Two Nodes | FindDistanceBetweenTwoNodes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindDistanceBetweenTwoNodes:
"""Find Distance Between Two Nodes"""
def __init__(self, root_node, label1, label2):
"""Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second node's label Returns: None Raises: None"""
<|body_0... | stack_v2_sparse_classes_36k_train_005319 | 2,695 | no_license | [
{
"docstring": "Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second node's label Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, root_node, label1, label2)"
},
{
"docstring": "Solve the problem Note: O(n) (... | 3 | stack_v2_sparse_classes_30k_train_016432 | Implement the Python class `FindDistanceBetweenTwoNodes` described below.
Class description:
Find Distance Between Two Nodes
Method signatures and docstrings:
- def __init__(self, root_node, label1, label2): Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second no... | Implement the Python class `FindDistanceBetweenTwoNodes` described below.
Class description:
Find Distance Between Two Nodes
Method signatures and docstrings:
- def __init__(self, root_node, label1, label2): Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second no... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class FindDistanceBetweenTwoNodes:
"""Find Distance Between Two Nodes"""
def __init__(self, root_node, label1, label2):
"""Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second node's label Returns: None Raises: None"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindDistanceBetweenTwoNodes:
"""Find Distance Between Two Nodes"""
def __init__(self, root_node, label1, label2):
"""Find Distance Between Two Nodes Args: root_node: node of the tree label1: First node's label label2: Second node's label Returns: None Raises: None"""
super().__init__(self... | the_stack_v2_python_sparse | python/problems/binary_tree/find_distance_between_two_nodes.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
abe34a11b4db2bc405d9c7957b01f83a911034b7 | [
"se = SequencingCenter.query.get(kf_id)\nif se is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))\nreturn SequencingCenterSchema().jsonify(se)",
"se = SequencingCenter.query.get(kf_id)\nif se is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))\n... | <|body_start_0|>
se = SequencingCenter.query.get(kf_id)
if se is None:
abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))
return SequencingCenterSchema().jsonify(se)
<|end_body_0|>
<|body_start_1|>
se = SequencingCenter.query.get(kf_id)
if se is ... | SequencingCenter REST API | SequencingCenterAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing sequencing_center. All... | stack_v2_sparse_classes_36k_train_005320 | 5,230 | permissive | [
{
"docstring": "Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing sequencing_center. Allows partial update of resource --- template: path: update_by_id.... | 3 | stack_v2_sparse_classes_30k_train_001604 | Implement the Python class `SequencingCenterAPI` described below.
Class description:
SequencingCenter REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter
- def patch(self, kf_id): Update an existing s... | Implement the Python class `SequencingCenterAPI` described below.
Class description:
SequencingCenter REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter
- def patch(self, kf_id): Update an existing s... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing sequencing_center. All... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
se = SequencingCenter.query.get(kf_id)
if se is None:
abort(404, 'could not find {} `... | the_stack_v2_python_sparse | dataservice/api/sequencing_center/resources.py | kids-first/kf-api-dataservice | train | 9 |
f2fd4144eaaf00d459e1a1979885f5374226819b | [
"freq = {}\nfor x in nums:\n freq[x] = freq.get(x, 0) + 1\nnum, counts = ([], [])\nfor x, count in freq.items():\n num.append(x)\n counts.append(count)\nnum_heap, count_heap = self.build_heap(num[:k], counts[:k], k)\nfor i in range(len(num) - k):\n if count_heap[0] >= counts[i + k]:\n continue\n ... | <|body_start_0|>
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
num, counts = ([], [])
for x, count in freq.items():
num.append(x)
counts.append(count)
num_heap, count_heap = self.build_heap(num[:k], counts[:k], k)
for i in range... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
<|body_0|>
def build_heap(self, num, counts, n):
"""构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005321 | 4,818 | no_license | [
{
"docstring": "使用堆的方法 :param nums: (list) :param k: (int) :return:",
"name": "top_k_frequent",
"signature": "def top_k_frequent(self, nums, k)"
},
{
"docstring": "构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)",
"name": "build_heap",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_test_000006 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def top_k_frequent(self, nums, k): 使用堆的方法 :param nums: (list) :param k: (int) :return:
- def build_heap(self, num, counts, n): 构建最小堆 :param num: (list) :param counts: (list) :p... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def top_k_frequent(self, nums, k): 使用堆的方法 :param nums: (list) :param k: (int) :return:
- def build_heap(self, num, counts, n): 构建最小堆 :param num: (list) :param counts: (list) :p... | 497c9717d783bb9f2d2675a3b254ec406582d849 | <|skeleton|>
class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
<|body_0|>
def build_heap(self, num, counts, n):
"""构建最小堆 :param num: (list) :param counts: (list) :param n: (int) :return: (list, list)"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def top_k_frequent(self, nums, k):
"""使用堆的方法 :param nums: (list) :param k: (int) :return:"""
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
num, counts = ([], [])
for x, count in freq.items():
num.append(x)
counts.ap... | the_stack_v2_python_sparse | 347.前K个高频元素/topKFrequent.py | boyshen/leetcode_Algorithm_problem | train | 0 | |
f408b1872c9387c42266362775206a45c9a56f43 | [
"if matching.matches_any(node, ESTIMATORS) or matching.matches_any(node, MODELS):\n return _version_args_needed(node)\nreturn False",
"framework, is_model = _framework_from_node(node)\nif matching.has_arg(node, FRAMEWORK_ARG):\n framework_version = parsing.arg_value(node, FRAMEWORK_ARG)\nelse:\n framewor... | <|body_start_0|>
if matching.matches_any(node, ESTIMATORS) or matching.matches_any(node, MODELS):
return _version_args_needed(node)
return False
<|end_body_0|>
<|body_start_1|>
framework, is_model = _framework_from_node(node)
if matching.has_arg(node, FRAMEWORK_ARG):
... | Ensures that ``framework_version`` is defined when instantiating a framework estimator. | FrameworkVersionEnforcer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrameworkVersionEnforcer:
"""Ensures that ``framework_version`` is defined when instantiating a framework estimator."""
def node_should_be_modified(self, node):
"""Checks if the ast.Call node instantiates a framework estimator or model. It doesn't specify the ``framework_version`` an... | stack_v2_sparse_classes_36k_train_005322 | 6,892 | permissive | [
{
"docstring": "Checks if the ast.Call node instantiates a framework estimator or model. It doesn't specify the ``framework_version`` and ``py_version`` parameter, as appropriate. This looks for the following formats: - ``TensorFlow`` - ``sagemaker.tensorflow.TensorFlow`` where \"TensorFlow\" can be Chainer, MX... | 2 | null | Implement the Python class `FrameworkVersionEnforcer` described below.
Class description:
Ensures that ``framework_version`` is defined when instantiating a framework estimator.
Method signatures and docstrings:
- def node_should_be_modified(self, node): Checks if the ast.Call node instantiates a framework estimator ... | Implement the Python class `FrameworkVersionEnforcer` described below.
Class description:
Ensures that ``framework_version`` is defined when instantiating a framework estimator.
Method signatures and docstrings:
- def node_should_be_modified(self, node): Checks if the ast.Call node instantiates a framework estimator ... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class FrameworkVersionEnforcer:
"""Ensures that ``framework_version`` is defined when instantiating a framework estimator."""
def node_should_be_modified(self, node):
"""Checks if the ast.Call node instantiates a framework estimator or model. It doesn't specify the ``framework_version`` an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrameworkVersionEnforcer:
"""Ensures that ``framework_version`` is defined when instantiating a framework estimator."""
def node_should_be_modified(self, node):
"""Checks if the ast.Call node instantiates a framework estimator or model. It doesn't specify the ``framework_version`` and ``py_versio... | the_stack_v2_python_sparse | src/sagemaker/cli/compatibility/v2/modifiers/framework_version.py | aws/sagemaker-python-sdk | train | 2,050 |
0bce7840dfef2323601c70fe40f26e8002036161 | [
"if week < 0:\n raise ValueError('Invalid week number')\nif second >= cls.SECONDS_PER_WEEK:\n raise ValueError('Bad second number')\nweekday, daysec = divmod(second + cls.GPS_LEAP_OFFSET, cls.SECONDS_PER_DAY)\ndaynum = week * cls.NUM_WEEKDAYS + weekday\ndays, seconds = xdatetime.TAIDaySecsToUTCDaySecs(daynum ... | <|body_start_0|>
if week < 0:
raise ValueError('Invalid week number')
if second >= cls.SECONDS_PER_WEEK:
raise ValueError('Bad second number')
weekday, daysec = divmod(second + cls.GPS_LEAP_OFFSET, cls.SECONDS_PER_DAY)
daynum = week * cls.NUM_WEEKDAYS + weekday
... | Date/time object. | datetime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class datetime:
"""Date/time object."""
def from_gps_week_sec(cls, week, second=0, nanosecond=0):
"""Create new datetime object from GPS week, second and nanosecond."""
<|body_0|>
def gps_week_sec_nano(self, roundofs=0):
"""Get GPS week, second, and nanosecond from dat... | stack_v2_sparse_classes_36k_train_005323 | 3,139 | no_license | [
{
"docstring": "Create new datetime object from GPS week, second and nanosecond.",
"name": "from_gps_week_sec",
"signature": "def from_gps_week_sec(cls, week, second=0, nanosecond=0)"
},
{
"docstring": "Get GPS week, second, and nanosecond from datetime object.",
"name": "gps_week_sec_nano",... | 2 | null | Implement the Python class `datetime` described below.
Class description:
Date/time object.
Method signatures and docstrings:
- def from_gps_week_sec(cls, week, second=0, nanosecond=0): Create new datetime object from GPS week, second and nanosecond.
- def gps_week_sec_nano(self, roundofs=0): Get GPS week, second, an... | Implement the Python class `datetime` described below.
Class description:
Date/time object.
Method signatures and docstrings:
- def from_gps_week_sec(cls, week, second=0, nanosecond=0): Create new datetime object from GPS week, second and nanosecond.
- def gps_week_sec_nano(self, roundofs=0): Get GPS week, second, an... | 1a6471dfbd7ec27f3d9f42b49173d18761a8f5aa | <|skeleton|>
class datetime:
"""Date/time object."""
def from_gps_week_sec(cls, week, second=0, nanosecond=0):
"""Create new datetime object from GPS week, second and nanosecond."""
<|body_0|>
def gps_week_sec_nano(self, roundofs=0):
"""Get GPS week, second, and nanosecond from dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class datetime:
"""Date/time object."""
def from_gps_week_sec(cls, week, second=0, nanosecond=0):
"""Create new datetime object from GPS week, second and nanosecond."""
if week < 0:
raise ValueError('Invalid week number')
if second >= cls.SECONDS_PER_WEEK:
raise ... | the_stack_v2_python_sparse | fwgnss/systems/xdatetime.py | fhgwright/fwgnss | train | 2 |
efbd14ddf746b8e02f333883b45079b4c14fb174 | [
"self.searchResults = searchResults\nself.keywords = keywords\nself.originalSearchResults = originalSearchResults",
"results = {}\nfor result in self.searchResults:\n results[result['url']] = result\nscoredResults = {}\nfor entityId in self.originalSearchResults:\n for query in self.originalSearchResults[en... | <|body_start_0|>
self.searchResults = searchResults
self.keywords = keywords
self.originalSearchResults = originalSearchResults
<|end_body_0|>
<|body_start_1|>
results = {}
for result in self.searchResults:
results[result['url']] = result
scoredResults = {}
... | Represents a baseline ranking of the original search results. | BaselineRanking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format:... | stack_v2_sparse_classes_36k_train_005324 | 4,766 | no_license | [
{
"docstring": "Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format: [ { 'url': <url> 'preview' : <preview snippet> 'title' : <title> 'description' : <meta description> 'pageRank' : <PageRank, between 0 and 10> 'content' : <page content... | 2 | stack_v2_sparse_classes_30k_train_021517 | Implement the Python class `BaselineRanking` described below.
Class description:
Represents a baseline ranking of the original search results.
Method signatures and docstrings:
- def __init__(self, searchResults, keywords, originalSearchResults): Creates a ranking object with the necessary parameters @param searchRes... | Implement the Python class `BaselineRanking` described below.
Class description:
Represents a baseline ranking of the original search results.
Method signatures and docstrings:
- def __init__(self, searchResults, keywords, originalSearchResults): Creates a ranking object with the necessary parameters @param searchRes... | d702e132994ccfb6fe51a82635d33d67c3a74f81 | <|skeleton|>
class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format: [ { 'url': <... | the_stack_v2_python_sparse | src/ranking/BaselineRanking.py | jtedesco/EntityQuerier | train | 1 |
b8d80c4ea87dcf56305a2d2fa76ef4223c9bf9ca | [
"self.model = BayesianOptimization(evaluate, params)\nself.best_params = None\nself.model_to_tune = model_to_tune",
"self.model.maximize(init_points=init_points, n_iter=n_iter, acq='ei')\nself.best_params = self.model.max['params']\nreturn self.best_params"
] | <|body_start_0|>
self.model = BayesianOptimization(evaluate, params)
self.best_params = None
self.model_to_tune = model_to_tune
<|end_body_0|>
<|body_start_1|>
self.model.maximize(init_points=init_points, n_iter=n_iter, acq='ei')
self.best_params = self.model.max['params']
... | BayesOpt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesOpt:
def __init__(self, model_to_tune, evaluate, params):
"""params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find the best"""
<|body_0|>
def tune(self, init_points, n_iter) -> dict:
"""Find... | stack_v2_sparse_classes_36k_train_005325 | 796 | permissive | [
{
"docstring": "params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find the best",
"name": "__init__",
"signature": "def __init__(self, model_to_tune, evaluate, params)"
},
{
"docstring": "Find the best hyperparameters for the... | 2 | stack_v2_sparse_classes_30k_val_000301 | Implement the Python class `BayesOpt` described below.
Class description:
Implement the BayesOpt class.
Method signatures and docstrings:
- def __init__(self, model_to_tune, evaluate, params): params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find... | Implement the Python class `BayesOpt` described below.
Class description:
Implement the BayesOpt class.
Method signatures and docstrings:
- def __init__(self, model_to_tune, evaluate, params): params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find... | 721049fec2d0a196885f7f6e47d2b5943accc0ce | <|skeleton|>
class BayesOpt:
def __init__(self, model_to_tune, evaluate, params):
"""params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find the best"""
<|body_0|>
def tune(self, init_points, n_iter) -> dict:
"""Find... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesOpt:
def __init__(self, model_to_tune, evaluate, params):
"""params --------- evaluate: function function for optimization params: dict dict of params where the BayesianOptimization find the best"""
self.model = BayesianOptimization(evaluate, params)
self.best_params = None
... | the_stack_v2_python_sparse | src/tuning/bayesian_optimization.py | nguyenanht/dq_travis | train | 0 | |
911c1af33c13bebc987992cd258ae301ceabdb92 | [
"specified_log_loc = options.get('collect_log_args', {})\nspecified_log_dict = specified_log_loc\nlog_loc = options.get('expected_log_location', '> /dev/null')\nsystems = options.get('systems', ['lms'])\nif specified_log_loc is None:\n collect_assets(systems, Env.DEVSTACK_SETTINGS)\nelse:\n collect_assets(sys... | <|body_start_0|>
specified_log_loc = options.get('collect_log_args', {})
specified_log_dict = specified_log_loc
log_loc = options.get('expected_log_location', '> /dev/null')
systems = options.get('systems', ['lms'])
if specified_log_loc is None:
collect_assets(systems... | Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collectstatic output * expected_log_location: the expected string to be used for piping co... | TestCollectAssets | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCollectAssets:
"""Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collectstatic output * expected_log_location:... | stack_v2_sparse_classes_36k_train_005326 | 14,737 | permissive | [
{
"docstring": "Ensure commands sent to the environment for collect_assets are as expected",
"name": "test_collect_assets",
"signature": "def test_collect_assets(self, options)"
},
{
"docstring": "When the method is called specifically with None for the collectstatic log dir, then it should run ... | 3 | null | Implement the Python class `TestCollectAssets` described below.
Class description:
Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collec... | Implement the Python class `TestCollectAssets` described below.
Class description:
Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collec... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class TestCollectAssets:
"""Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collectstatic output * expected_log_location:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCollectAssets:
"""Test the collectstatic process call. ddt data is organized thusly: * debug: whether or not collect_assets is called with the debug flag * specified_log_location: used when collect_assets is called with a specific log location for collectstatic output * expected_log_location: the expected... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/paver_tests/test_assets.py | luque/better-ways-of-thinking-about-software | train | 3 |
5e72e4259d496b329397730fa6d7b0a186c02d76 | [
"def flatten(lines):\n res = self.env['account_report_template.report_template_line']\n for l in lines:\n res.append(l)\n res += flatten(l.children_ids)\n return res\nfor temp in self:\n temp.all_line_ids = flatten(temp.line_ids)",
"rows = []\nenv = {}\nfor row in self.line_ids._to_rows(... | <|body_start_0|>
def flatten(lines):
res = self.env['account_report_template.report_template_line']
for l in lines:
res.append(l)
res += flatten(l.children_ids)
return res
for temp in self:
temp.all_line_ids = flatten(temp.l... | ReportTemplate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportTemplate:
def _get_all_lines(self):
"""All the template lines in the hierarchy in a depth-first order"""
<|body_0|>
def _to_table(self, domain):
"""We compile a template into a 'report_table.json_table' that we then use in QWeb"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_005327 | 9,769 | no_license | [
{
"docstring": "All the template lines in the hierarchy in a depth-first order",
"name": "_get_all_lines",
"signature": "def _get_all_lines(self)"
},
{
"docstring": "We compile a template into a 'report_table.json_table' that we then use in QWeb",
"name": "_to_table",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_013435 | Implement the Python class `ReportTemplate` described below.
Class description:
Implement the ReportTemplate class.
Method signatures and docstrings:
- def _get_all_lines(self): All the template lines in the hierarchy in a depth-first order
- def _to_table(self, domain): We compile a template into a 'report_table.jso... | Implement the Python class `ReportTemplate` described below.
Class description:
Implement the ReportTemplate class.
Method signatures and docstrings:
- def _get_all_lines(self): All the template lines in the hierarchy in a depth-first order
- def _to_table(self, domain): We compile a template into a 'report_table.jso... | fb3100785d4b171f123e0ee992f6853de26ec46e | <|skeleton|>
class ReportTemplate:
def _get_all_lines(self):
"""All the template lines in the hierarchy in a depth-first order"""
<|body_0|>
def _to_table(self, domain):
"""We compile a template into a 'report_table.json_table' that we then use in QWeb"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportTemplate:
def _get_all_lines(self):
"""All the template lines in the hierarchy in a depth-first order"""
def flatten(lines):
res = self.env['account_report_template.report_template_line']
for l in lines:
res.append(l)
res += flatten... | the_stack_v2_python_sparse | account_report_template/models/template.py | kumarinie/misc | train | 0 | |
71f4abc0ca14fcb655ecb0a03cf88813a8747380 | [
"record_query = select([AuthInfo]).where(and_(AuthInfo.LoginName == login_name, AuthInfo.Passwd == password))\nrecord = session.execute(record_query).fetchone()\nif not record:\n return (ResponseCode.Failed, None)\nreturn (ResponseCode.Succeed, record)",
"record = session.query(AuthInfo).filter(AuthInfo.AuthId... | <|body_start_0|>
record_query = select([AuthInfo]).where(and_(AuthInfo.LoginName == login_name, AuthInfo.Passwd == password))
record = session.execute(record_query).fetchone()
if not record:
return (ResponseCode.Failed, None)
return (ResponseCode.Succeed, record)
<|end_body_0... | AuthInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthInfo:
def get_auth_info_by_login_name_password(cls, session, login_name, password):
"""通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:"""
<|body_0|>
def get_auth_info_by_auth_id(cls, session, auth_id):
""":param session: :... | stack_v2_sparse_classes_36k_train_005328 | 1,684 | no_license | [
{
"docstring": "通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:",
"name": "get_auth_info_by_login_name_password",
"signature": "def get_auth_info_by_login_name_password(cls, session, login_name, password)"
},
{
"docstring": ":param session: :param auth_id... | 2 | stack_v2_sparse_classes_30k_train_005645 | Implement the Python class `AuthInfo` described below.
Class description:
Implement the AuthInfo class.
Method signatures and docstrings:
- def get_auth_info_by_login_name_password(cls, session, login_name, password): 通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:
- def get_a... | Implement the Python class `AuthInfo` described below.
Class description:
Implement the AuthInfo class.
Method signatures and docstrings:
- def get_auth_info_by_login_name_password(cls, session, login_name, password): 通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:
- def get_a... | 902e54bf143a0967dccd1b8884c3164317ff8568 | <|skeleton|>
class AuthInfo:
def get_auth_info_by_login_name_password(cls, session, login_name, password):
"""通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:"""
<|body_0|>
def get_auth_info_by_auth_id(cls, session, auth_id):
""":param session: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthInfo:
def get_auth_info_by_login_name_password(cls, session, login_name, password):
"""通过id 获取用户信息 :param password: :param login_name: :param session: :param user_id: :return:"""
record_query = select([AuthInfo]).where(and_(AuthInfo.LoginName == login_name, AuthInfo.Passwd == password))
... | the_stack_v2_python_sparse | wxrobot/helperServer/weixin_helper/common/db_model/user_db/auth_info.py | immortalChensm/python-project | train | 0 | |
d2fab9ca0cc3718d9c1d09da823c2187a3ad9aac | [
"post = create_a_post()\nwith self.assertRaises(TypeError):\n comment = Comment.create(post=post)",
"post = create_a_post()\nwith self.assertRaises(TypeError):\n Comment.create(body=\"This shouldn't work\")",
"post = create_a_post()\ncomment = Comment.create(body=\"I'm a comment without a parent\", post=p... | <|body_start_0|>
post = create_a_post()
with self.assertRaises(TypeError):
comment = Comment.create(post=post)
<|end_body_0|>
<|body_start_1|>
post = create_a_post()
with self.assertRaises(TypeError):
Comment.create(body="This shouldn't work")
<|end_body_1|>
<|b... | CommentModelTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentModelTests:
def test_create_comment_missing_kwarg_raises_type_error(self):
"""Not passing a required kwarg like body should raise type error"""
<|body_0|>
def test_create_comment_either_parent_or_post_must_be_kwarg(self):
"""If neither 'parent' nor 'post' are ... | stack_v2_sparse_classes_36k_train_005329 | 13,696 | permissive | [
{
"docstring": "Not passing a required kwarg like body should raise type error",
"name": "test_create_comment_missing_kwarg_raises_type_error",
"signature": "def test_create_comment_missing_kwarg_raises_type_error(self)"
},
{
"docstring": "If neither 'parent' nor 'post' are passed as kwarg keys,... | 5 | stack_v2_sparse_classes_30k_train_003613 | Implement the Python class `CommentModelTests` described below.
Class description:
Implement the CommentModelTests class.
Method signatures and docstrings:
- def test_create_comment_missing_kwarg_raises_type_error(self): Not passing a required kwarg like body should raise type error
- def test_create_comment_either_p... | Implement the Python class `CommentModelTests` described below.
Class description:
Implement the CommentModelTests class.
Method signatures and docstrings:
- def test_create_comment_missing_kwarg_raises_type_error(self): Not passing a required kwarg like body should raise type error
- def test_create_comment_either_p... | b7f177828efa57c1374fe0d8cea3a6a492ed1a47 | <|skeleton|>
class CommentModelTests:
def test_create_comment_missing_kwarg_raises_type_error(self):
"""Not passing a required kwarg like body should raise type error"""
<|body_0|>
def test_create_comment_either_parent_or_post_must_be_kwarg(self):
"""If neither 'parent' nor 'post' are ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentModelTests:
def test_create_comment_missing_kwarg_raises_type_error(self):
"""Not passing a required kwarg like body should raise type error"""
post = create_a_post()
with self.assertRaises(TypeError):
comment = Comment.create(post=post)
def test_create_comment_... | the_stack_v2_python_sparse | discussions/tests.py | jeury301/classmo | train | 0 | |
98a152319ddf2012901b851aee47a25d3c768f74 | [
"for i in range(rowIndex + 1):\n row = [1] * (i + 1)\n if i >= 2:\n for j in range(1, i):\n row[j] = tmp[j - 1] + tmp[j]\n tmp = row\nreturn tmp",
"row = [1] * (rowIndex + 1)\nif rowIndex >= 1:\n for i in range(1, rowIndex + 1):\n row[i] = row[i - 1] * (rowIndex + 1 - i) // i\... | <|body_start_0|>
for i in range(rowIndex + 1):
row = [1] * (i + 1)
if i >= 2:
for j in range(1, i):
row[j] = tmp[j - 1] + tmp[j]
tmp = row
return tmp
<|end_body_0|>
<|body_start_1|>
row = [1] * (rowIndex + 1)
if row... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow1(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(rowIndex + 1):
... | stack_v2_sparse_classes_36k_train_005330 | 672 | no_license | [
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow",
"signature": "def getRow(self, rowIndex)"
},
{
"docstring": ":type rowIndex: int :rtype: List[int]",
"name": "getRow1",
"signature": "def getRow1(self, rowIndex)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021214 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow1(self, rowIndex): :type rowIndex: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getRow(self, rowIndex): :type rowIndex: int :rtype: List[int]
- def getRow1(self, rowIndex): :type rowIndex: int :rtype: List[int]
<|skeleton|>
class Solution:
def getR... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_0|>
def getRow1(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getRow(self, rowIndex):
""":type rowIndex: int :rtype: List[int]"""
for i in range(rowIndex + 1):
row = [1] * (i + 1)
if i >= 2:
for j in range(1, i):
row[j] = tmp[j - 1] + tmp[j]
tmp = row
return tmp... | the_stack_v2_python_sparse | leetcode/119杨辉三角II.py | ShawDa/Coding | train | 0 | |
cb3e2f1d38afe768607bf299e3f1e02a6c98c07e | [
"if self.expires_at:\n delta = self.expires_at - self.now()\n if isinstance(delta, timedelta):\n delta = delta.total_seconds()\n return delta\nelse:\n return None",
"now = cls.now()\ndeleted = False\nfor obj in db.query(cls).filter(cls.expires_at != None).filter(cls.expires_at < now):\n app_... | <|body_start_0|>
if self.expires_at:
delta = self.expires_at - self.now()
if isinstance(delta, timedelta):
delta = delta.total_seconds()
return delta
else:
return None
<|end_body_0|>
<|body_start_1|>
now = cls.now()
deleted... | Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object | Expiring | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Expiring:
"""Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object"""
def expires_in(self):
"""Property returning expiration in seconds from now or None"""
<|body_0|>
def purge_expired(cls, db):
... | stack_v2_sparse_classes_36k_train_005331 | 36,586 | permissive | [
{
"docstring": "Property returning expiration in seconds from now or None",
"name": "expires_in",
"signature": "def expires_in(self)"
},
{
"docstring": "Purge expired API Tokens from the database",
"name": "purge_expired",
"signature": "def purge_expired(cls, db)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006631 | Implement the Python class `Expiring` described below.
Class description:
Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object
Method signatures and docstrings:
- def expires_in(self): Property returning expiration in seconds from now or None
... | Implement the Python class `Expiring` described below.
Class description:
Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object
Method signatures and docstrings:
- def expires_in(self): Property returning expiration in seconds from now or None
... | 7757dea8a463e75d8a540e85deee45c1635dd273 | <|skeleton|>
class Expiring:
"""Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object"""
def expires_in(self):
"""Property returning expiration in seconds from now or None"""
<|body_0|>
def purge_expired(cls, db):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Expiring:
"""Mixin for expiring entries Subclass must define at least expires_at property, which should be unix timestamp or datetime object"""
def expires_in(self):
"""Property returning expiration in seconds from now or None"""
if self.expires_at:
delta = self.expires_at - s... | the_stack_v2_python_sparse | jupyterhub/orm.py | jupyterhub/jupyterhub | train | 6,751 |
8bd438f3818dbdc9294e1390abca1626e5e615dc | [
"storages = Session.query(CloudStorage).all()\nfor storage in storages:\n users = Session.query(CloudStorageUser).filter(CloudStorageUser.storage_name == storage.storage_name)\n setattr(storage, 'users', list(users))\nreturn storages",
"input_dict = get_input_as_dict(request)\nif 'storage_name' not in input... | <|body_start_0|>
storages = Session.query(CloudStorage).all()
for storage in storages:
users = Session.query(CloudStorageUser).filter(CloudStorageUser.storage_name == storage.storage_name)
setattr(storage, 'users', list(users))
return storages
<|end_body_0|>
<|body_start... | Configuration of cloud storages | CloudConfigController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
<|body_0|>
def set_cloud_storage(self, start_response):
"""Add or modify a cloud storage entry"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_005332 | 6,616 | permissive | [
{
"docstring": "Get a list of cloud storages registered",
"name": "get_cloud_storages",
"signature": "def get_cloud_storages(self)"
},
{
"docstring": "Add or modify a cloud storage entry",
"name": "set_cloud_storage",
"signature": "def set_cloud_storage(self, start_response)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_005863 | Implement the Python class `CloudConfigController` described below.
Class description:
Configuration of cloud storages
Method signatures and docstrings:
- def get_cloud_storages(self): Get a list of cloud storages registered
- def set_cloud_storage(self, start_response): Add or modify a cloud storage entry
- def get_... | Implement the Python class `CloudConfigController` described below.
Class description:
Configuration of cloud storages
Method signatures and docstrings:
- def get_cloud_storages(self): Get a list of cloud storages registered
- def set_cloud_storage(self, start_response): Add or modify a cloud storage entry
- def get_... | 12a763986e1a0b6245e7adef044a2d4179e34734 | <|skeleton|>
class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
<|body_0|>
def set_cloud_storage(self, start_response):
"""Add or modify a cloud storage entry"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
storages = Session.query(CloudStorage).all()
for storage in storages:
users = Session.query(CloudStorageUser).filter(CloudStorageUse... | the_stack_v2_python_sparse | src/fts3rest/fts3rest/controllers/config/cloud.py | cern-fts/fts-rest | train | 2 |
da76c9284ce7a56a474eba518ed805ea542c56f0 | [
"super().__init__()\nself.style = ''\nself.controller = controller\nself.assets_gui = assets_gui\nself.arch_diagram_gui = arch_diagram_gui\nself.technologies_gui = technologies_gui\nself.data_flow_diagram_gui = data_flow_diagram_gui\nself.entry_points_gui = entry_points_gui\nself.ranking_gui = ranking_gui\nself.ini... | <|body_start_0|>
super().__init__()
self.style = ''
self.controller = controller
self.assets_gui = assets_gui
self.arch_diagram_gui = arch_diagram_gui
self.technologies_gui = technologies_gui
self.data_flow_diagram_gui = data_flow_diagram_gui
self.entry_po... | Deals with module gui which is generated from ThreatModel data | ThreatModelGui | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreatModelGui:
"""Deals with module gui which is generated from ThreatModel data"""
def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui):
"""Init"""
<|body_0|>
def initUI(self):
"""F... | stack_v2_sparse_classes_36k_train_005333 | 3,689 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui)"
},
{
"docstring": "Function to move GUI creation from __init__",
"name": "initUI",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_002333 | Implement the Python class `ThreatModelGui` described below.
Class description:
Deals with module gui which is generated from ThreatModel data
Method signatures and docstrings:
- def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui): Init
... | Implement the Python class `ThreatModelGui` described below.
Class description:
Deals with module gui which is generated from ThreatModel data
Method signatures and docstrings:
- def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui): Init
... | be32512d6d098a123599b2ac8f032bd003c28f63 | <|skeleton|>
class ThreatModelGui:
"""Deals with module gui which is generated from ThreatModel data"""
def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui):
"""Init"""
<|body_0|>
def initUI(self):
"""F... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreatModelGui:
"""Deals with module gui which is generated from ThreatModel data"""
def __init__(self, controller, assets_gui, arch_diagram_gui, technologies_gui, data_flow_diagram_gui, entry_points_gui, ranking_gui):
"""Init"""
super().__init__()
self.style = ''
self.con... | the_stack_v2_python_sparse | iotpentool/threatmodelgui.py | sarunasil/iotPenTool | train | 0 |
bd7829593ac3be50eafc356547d4d02ecefe805c | [
"super(Decoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_dim=target_vocab, output_dim=dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dro... | <|body_start_0|>
super(Decoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_dim=target_vocab, output_dim=dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [DecoderBlock(dm, h, hidden, drop_rate)... | create encoder for transformer | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""create encoder for transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully conne... | stack_v2_sparse_classes_36k_train_005334 | 3,185 | no_license | [
{
"docstring": "N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer target_vocab - the size of the target vocabulary max_seq_len - the maximum sequence length possible drop_rate - the dropout rate S... | 2 | null | Implement the Python class `Decoder` described below.
Class description:
create encoder for transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of hea... | Implement the Python class `Decoder` described below.
Class description:
create encoder for transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of hea... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class Decoder:
"""create encoder for transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully conne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""create encoder for transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""N - the number of blocks in the encoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer ta... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/10-transformer_decoder.py | icculp/holbertonschool-machine_learning | train | 0 |
51c5d020c2d28dcfe088718474fb2bc9c8a1c7ac | [
"try:\n sub_refs, name_map = self.construct_subprocess_ref_graph(data, root_id=root_id, root_name=root_name)\nexcept PipelineTemplate.DoesNotExist as e:\n return (False, str(e))\nnodes = list(sub_refs.keys())\nflows = []\nfor node in nodes:\n for ref in sub_refs[node]:\n if ref in nodes:\n ... | <|body_start_0|>
try:
sub_refs, name_map = self.construct_subprocess_ref_graph(data, root_id=root_id, root_name=root_name)
except PipelineTemplate.DoesNotExist as e:
return (False, str(e))
nodes = list(sub_refs.keys())
flows = []
for node in nodes:
... | TemplateManager | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateManager:
def subprocess_ref_validate(self, data, root_id=None, root_name=None):
"""验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息"""
<|body_0|>
def create_model(self, structure_data, **kwargs):
"""创建流程模板对象 @param structure_dat... | stack_v2_sparse_classes_36k_train_005335 | 28,914 | permissive | [
{
"docstring": "验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息",
"name": "subprocess_ref_validate",
"signature": "def subprocess_ref_validate(self, data, root_id=None, root_name=None)"
},
{
"docstring": "创建流程模板对象 @param structure_data: pipeline 结构数据 @param kwargs... | 6 | null | Implement the Python class `TemplateManager` described below.
Class description:
Implement the TemplateManager class.
Method signatures and docstrings:
- def subprocess_ref_validate(self, data, root_id=None, root_name=None): 验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息
- def create_... | Implement the Python class `TemplateManager` described below.
Class description:
Implement the TemplateManager class.
Method signatures and docstrings:
- def subprocess_ref_validate(self, data, root_id=None, root_name=None): 验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息
- def create_... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class TemplateManager:
def subprocess_ref_validate(self, data, root_id=None, root_name=None):
"""验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息"""
<|body_0|>
def create_model(self, structure_data, **kwargs):
"""创建流程模板对象 @param structure_dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateManager:
def subprocess_ref_validate(self, data, root_id=None, root_name=None):
"""验证子流程引用是否合法 @param data: @param root_id: @param root_name: @return: 引用是否合法,相关信息"""
try:
sub_refs, name_map = self.construct_subprocess_ref_graph(data, root_id=root_id, root_name=root_name)
... | the_stack_v2_python_sparse | pipeline/models.py | TencentBlueKing/bk-itsm | train | 100 | |
20824c108905a0d786a0d1cbd44a5e249d31d131 | [
"source = Path(source)\nif source.is_dir():\n return ReportFileLoader.load_dir(source)\nreturn ReportFileLoader.load_file(source)",
"zstatus, zfs = ReportFileBuilder.build_zipfs(path, StringIO())\nif not zstatus.success():\n error_msg = '; '.join(zstatus.get_errors())\n raise ReportFileLoaderError(\"Erro... | <|body_start_0|>
source = Path(source)
if source.is_dir():
return ReportFileLoader.load_dir(source)
return ReportFileLoader.load_file(source)
<|end_body_0|>
<|body_start_1|>
zstatus, zfs = ReportFileBuilder.build_zipfs(path, StringIO())
if not zstatus.success():
... | ReportFileLoader | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportFileLoader:
def load(source: str) -> ReportFile:
"""Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile"""
<|body_0|>
def load_dir(path: str) -> ReportFile:
"""Generate ReportFile from a directory with a valid report tem... | stack_v2_sparse_classes_36k_train_005336 | 2,603 | permissive | [
{
"docstring": "Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile",
"name": "load",
"signature": "def load(source: str) -> ReportFile"
},
{
"docstring": "Generate ReportFile from a directory with a valid report template :param path: template path :retur... | 4 | stack_v2_sparse_classes_30k_train_020156 | Implement the Python class `ReportFileLoader` described below.
Class description:
Implement the ReportFileLoader class.
Method signatures and docstrings:
- def load(source: str) -> ReportFile: Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile
- def load_dir(path: str) -> Rep... | Implement the Python class `ReportFileLoader` described below.
Class description:
Implement the ReportFileLoader class.
Method signatures and docstrings:
- def load(source: str) -> ReportFile: Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile
- def load_dir(path: str) -> Rep... | 50341161951fd2f9cc3fbb4dcdf2dc1eeae5922a | <|skeleton|>
class ReportFileLoader:
def load(source: str) -> ReportFile:
"""Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile"""
<|body_0|>
def load_dir(path: str) -> ReportFile:
"""Generate ReportFile from a directory with a valid report tem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportFileLoader:
def load(source: str) -> ReportFile:
"""Load ReportFile from a source (either directory or a ZPT) :param source: :return: ReportFile"""
source = Path(source)
if source.is_dir():
return ReportFileLoader.load_dir(source)
return ReportFileLoader.load_... | the_stack_v2_python_sparse | zipreport/report/loader.py | prashanthhulimajjigi-agi/zipreport | train | 0 | |
f382f24c18c81e7fca39440e5fa55080e1c486a0 | [
"from fractions import gcd\nvals = collections.Counter(deck).values()\nreturn reduce(gcd, vals) >= 2",
"def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\nvals = collections.Counter(deck).values()\nreturn reduce(gcd, vals) > 1",
"n = len(deck)\nvals = collections.Counter(deck).values()\... | <|body_start_0|>
from fractions import gcd
vals = collections.Counter(deck).values()
return reduce(gcd, vals) >= 2
<|end_body_0|>
<|body_start_1|>
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
vals = collections.Counter(deck).val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_0|>
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_1|>
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: boo... | stack_v2_sparse_classes_36k_train_005337 | 1,001 | no_license | [
{
"docstring": ":type deck: List[int] :rtype: bool",
"name": "hasGroupsSizeX",
"signature": "def hasGroupsSizeX(self, deck)"
},
{
"docstring": ":type deck: List[int] :rtype: bool",
"name": "hasGroupsSizeX",
"signature": "def hasGroupsSizeX(self, deck)"
},
{
"docstring": ":type de... | 3 | stack_v2_sparse_classes_30k_train_020862 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def hasGroupsSizeX(self, deck): :type de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def hasGroupsSizeX(self, deck): :type deck: List[int] :rtype: bool
- def hasGroupsSizeX(self, deck): :type de... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_0|>
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
<|body_1|>
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: boo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
from fractions import gcd
vals = collections.Counter(deck).values()
return reduce(gcd, vals) >= 2
def hasGroupsSizeX(self, deck):
""":type deck: List[int] :rtype: bool"""
def... | the_stack_v2_python_sparse | 0914_X_of_a_Kind_in_a_Deck_of_Cards.py | bingli8802/leetcode | train | 0 | |
2f16857757436ee0ed5446150ca5f15ffa21eb4e | [
"self.CLASS_NAMES = class_name\nself.cfg = get_cfg()\nself.cfg.merge_from_file(model_zoo.get_config_file('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'))\nself.cfg.merge_from_file(cfg_path)\nself.cfg.MODEL.RETINANET.SCORE_THRESH_TEST = confidence_threshold\nself.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confi... | <|body_start_0|>
self.CLASS_NAMES = class_name
self.cfg = get_cfg()
self.cfg.merge_from_file(model_zoo.get_config_file('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'))
self.cfg.merge_from_file(cfg_path)
self.cfg.MODEL.RETINANET.SCORE_THRESH_TEST = confidence_threshold
... | pcna_detectronEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pcna_detectronEvaluator:
def __init__(self, cfg_path, dataset_ann_path, dataset_path, out_dir, class_name=['G1/G2', 'S', 'M', 'E'], confidence_threshold=0.5):
"""Evaluate Detectron2 performance using COCO matrix Args: cfg_path (str): path to config file. dataset_ann_path (str): path to t... | stack_v2_sparse_classes_36k_train_005338 | 9,136 | permissive | [
{
"docstring": "Evaluate Detectron2 performance using COCO matrix Args: cfg_path (str): path to config file. dataset_ann_path (str): path to the testing dataset annotation `json` file. dataset_path (str): path to testing dataset, must in format of pcnaDeep: separate dic and mcy folders. out_dir (str): output di... | 2 | stack_v2_sparse_classes_30k_val_000219 | Implement the Python class `pcna_detectronEvaluator` described below.
Class description:
Implement the pcna_detectronEvaluator class.
Method signatures and docstrings:
- def __init__(self, cfg_path, dataset_ann_path, dataset_path, out_dir, class_name=['G1/G2', 'S', 'M', 'E'], confidence_threshold=0.5): Evaluate Detec... | Implement the Python class `pcna_detectronEvaluator` described below.
Class description:
Implement the pcna_detectronEvaluator class.
Method signatures and docstrings:
- def __init__(self, cfg_path, dataset_ann_path, dataset_path, out_dir, class_name=['G1/G2', 'S', 'M', 'E'], confidence_threshold=0.5): Evaluate Detec... | 16f8128167c143dfd9cb6cf25046725a5cf1273a | <|skeleton|>
class pcna_detectronEvaluator:
def __init__(self, cfg_path, dataset_ann_path, dataset_path, out_dir, class_name=['G1/G2', 'S', 'M', 'E'], confidence_threshold=0.5):
"""Evaluate Detectron2 performance using COCO matrix Args: cfg_path (str): path to config file. dataset_ann_path (str): path to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pcna_detectronEvaluator:
def __init__(self, cfg_path, dataset_ann_path, dataset_path, out_dir, class_name=['G1/G2', 'S', 'M', 'E'], confidence_threshold=0.5):
"""Evaluate Detectron2 performance using COCO matrix Args: cfg_path (str): path to config file. dataset_ann_path (str): path to the testing dat... | the_stack_v2_python_sparse | deprecated/deep_cell_functions/evaluate.py | kuanyoow/PCNAdeep | train | 0 | |
946c0e46b7e3e6b2a39f7d7686a6a31e7051d7df | [
"super(LSTM, self).__init__()\nself.hidden_size = d_model\nself.lstm = nn.LSTM(input_size=input_size, hidden_size=d_model, num_layers=layers, batch_first=True)\nself.fc1 = nn.Linear(d_model, d_model)\nself.fc2 = nn.Linear(d_model, out_len)\nself.drop_out = nn.Dropout(dropout)\nself.device = device\nself.num_layers ... | <|body_start_0|>
super(LSTM, self).__init__()
self.hidden_size = d_model
self.lstm = nn.LSTM(input_size=input_size, hidden_size=d_model, num_layers=layers, batch_first=True)
self.fc1 = nn.Linear(d_model, d_model)
self.fc2 = nn.Linear(d_model, out_len)
self.drop_out = nn.D... | An implementation of LSTM for forecasting. | LSTM | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTM:
"""An implementation of LSTM for forecasting."""
def __init__(self, input_size, out_len, d_model=512, layers=3, dropout=0.0, device=torch.device('cuda:0')):
"""Initializes a LSTM instance. Args: input_size: Input features dimension out_len: Forecasting horizon d_model: Hidden l... | stack_v2_sparse_classes_36k_train_005339 | 4,262 | permissive | [
{
"docstring": "Initializes a LSTM instance. Args: input_size: Input features dimension out_len: Forecasting horizon d_model: Hidden layer dimension layers: Number of LSTM layers. dropout: Fraction of neurons affected by Dropout (default=0.0). device: Device used by the model",
"name": "__init__",
"sign... | 2 | stack_v2_sparse_classes_30k_val_000376 | Implement the Python class `LSTM` described below.
Class description:
An implementation of LSTM for forecasting.
Method signatures and docstrings:
- def __init__(self, input_size, out_len, d_model=512, layers=3, dropout=0.0, device=torch.device('cuda:0')): Initializes a LSTM instance. Args: input_size: Input features... | Implement the Python class `LSTM` described below.
Class description:
An implementation of LSTM for forecasting.
Method signatures and docstrings:
- def __init__(self, input_size, out_len, d_model=512, layers=3, dropout=0.0, device=torch.device('cuda:0')): Initializes a LSTM instance. Args: input_size: Input features... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class LSTM:
"""An implementation of LSTM for forecasting."""
def __init__(self, input_size, out_len, d_model=512, layers=3, dropout=0.0, device=torch.device('cuda:0')):
"""Initializes a LSTM instance. Args: input_size: Input features dimension out_len: Forecasting horizon d_model: Hidden l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTM:
"""An implementation of LSTM for forecasting."""
def __init__(self, input_size, out_len, d_model=512, layers=3, dropout=0.0, device=torch.device('cuda:0')):
"""Initializes a LSTM instance. Args: input_size: Input features dimension out_len: Forecasting horizon d_model: Hidden layer dimensio... | the_stack_v2_python_sparse | ime/models/lstm.py | Jimmy-INL/google-research | train | 1 |
826b5649672caae0a1d1585c40fadce37deec65e | [
"idx = (len(nums) + idx) % len(nums)\nif idx + 1 >= len(nums):\n return True\nreturn nums[idx] >= nums[idx + 1]",
"i, j = (idx, len(nums) - 1)\nwhile i < j:\n nums[i], nums[j] = (nums[j], nums[i])\n i += 1\n j -= 1",
"idx = (len(nums) + idx) % len(nums)\nfor i in range(len(nums) - 1, idx, -1):\n ... | <|body_start_0|>
idx = (len(nums) + idx) % len(nums)
if idx + 1 >= len(nums):
return True
return nums[idx] >= nums[idx + 1]
<|end_body_0|>
<|body_start_1|>
i, j = (idx, len(nums) - 1)
while i < j:
nums[i], nums[j] = (nums[j], nums[i])
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _isMaxPermutation(self, nums, idx=0):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def _reverse(self, nums, idx):
""":type nums: List[int] :type idx: int >>> s = Solution() >>> nums = [1, 5, 4, 3, 2] >>> s._reverse(nums, 1) >>> nums [1, 2, 3, 4, ... | stack_v2_sparse_classes_36k_train_005340 | 3,460 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "_isMaxPermutation",
"signature": "def _isMaxPermutation(self, nums, idx=0)"
},
{
"docstring": ":type nums: List[int] :type idx: int >>> s = Solution() >>> nums = [1, 5, 4, 3, 2] >>> s._reverse(nums, 1) >>> nums [1, 2, 3, 4, 5]",
"... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isMaxPermutation(self, nums, idx=0): :type nums: List[int] :rtype: bool
- def _reverse(self, nums, idx): :type nums: List[int] :type idx: int >>> s = Solution() >>> nums = [... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _isMaxPermutation(self, nums, idx=0): :type nums: List[int] :rtype: bool
- def _reverse(self, nums, idx): :type nums: List[int] :type idx: int >>> s = Solution() >>> nums = [... | d2e8b2dca40fc955045eb62e576c776bad8ee5f1 | <|skeleton|>
class Solution:
def _isMaxPermutation(self, nums, idx=0):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def _reverse(self, nums, idx):
""":type nums: List[int] :type idx: int >>> s = Solution() >>> nums = [1, 5, 4, 3, 2] >>> s._reverse(nums, 1) >>> nums [1, 2, 3, 4, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _isMaxPermutation(self, nums, idx=0):
""":type nums: List[int] :rtype: bool"""
idx = (len(nums) + idx) % len(nums)
if idx + 1 >= len(nums):
return True
return nums[idx] >= nums[idx + 1]
def _reverse(self, nums, idx):
""":type nums: List[in... | the_stack_v2_python_sparse | next-permutation/next-permutation.py | childe/leetcode | train | 2 | |
53daf1bca2cdedacec58cf4647a92cf320b4f619 | [
"p = AlgorithmData(p)\nq = AlgorithmData(q)\nreturn np.sum((p[:, 0] - q[:, 0]) ** 2)",
"p = AlgorithmData(p)\nq = AlgorithmData(q)\nreturn np.sqrt(np.mean((p[:, 0] - q[:, 0]) ** 2))",
"p = AlgorithmData(p)\nq = AlgorithmData(q)\nreturn np.mean((p[:, 0] - q[:, 0]) ** 2)"
] | <|body_start_0|>
p = AlgorithmData(p)
q = AlgorithmData(q)
return np.sum((p[:, 0] - q[:, 0]) ** 2)
<|end_body_0|>
<|body_start_1|>
p = AlgorithmData(p)
q = AlgorithmData(q)
return np.sqrt(np.mean((p[:, 0] - q[:, 0]) ** 2))
<|end_body_1|>
<|body_start_2|>
p = Alg... | ErrorCalc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorCalc:
def sse(p, q):
"""Sum Square Error The calculation formula is: $\\sum_{i=0}^n (p_i-q_i)^2 $."""
<|body_0|>
def rms(p, q):
"""Root Mean Squires The calculation formula is: $\\sqrt{ rac{1}{n}\\sum_{i=0}^n (p_i-q_i)^2} $."""
<|body_1|>
def sme(p,... | stack_v2_sparse_classes_36k_train_005341 | 1,362 | no_license | [
{
"docstring": "Sum Square Error The calculation formula is: $\\\\sum_{i=0}^n (p_i-q_i)^2 $.",
"name": "sse",
"signature": "def sse(p, q)"
},
{
"docstring": "Root Mean Squires The calculation formula is: $\\\\sqrt{ rac{1}{n}\\\\sum_{i=0}^n (p_i-q_i)^2} $.",
"name": "rms",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_021021 | Implement the Python class `ErrorCalc` described below.
Class description:
Implement the ErrorCalc class.
Method signatures and docstrings:
- def sse(p, q): Sum Square Error The calculation formula is: $\\sum_{i=0}^n (p_i-q_i)^2 $.
- def rms(p, q): Root Mean Squires The calculation formula is: $\\sqrt{ rac{1}{n}\\sum... | Implement the Python class `ErrorCalc` described below.
Class description:
Implement the ErrorCalc class.
Method signatures and docstrings:
- def sse(p, q): Sum Square Error The calculation formula is: $\\sum_{i=0}^n (p_i-q_i)^2 $.
- def rms(p, q): Root Mean Squires The calculation formula is: $\\sqrt{ rac{1}{n}\\sum... | dfc30621bf330c300bca75103e7f8bca8b7a8d58 | <|skeleton|>
class ErrorCalc:
def sse(p, q):
"""Sum Square Error The calculation formula is: $\\sum_{i=0}^n (p_i-q_i)^2 $."""
<|body_0|>
def rms(p, q):
"""Root Mean Squires The calculation formula is: $\\sqrt{ rac{1}{n}\\sum_{i=0}^n (p_i-q_i)^2} $."""
<|body_1|>
def sme(p,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorCalc:
def sse(p, q):
"""Sum Square Error The calculation formula is: $\\sum_{i=0}^n (p_i-q_i)^2 $."""
p = AlgorithmData(p)
q = AlgorithmData(q)
return np.sum((p[:, 0] - q[:, 0]) ** 2)
def rms(p, q):
"""Root Mean Squires The calculation formula is: $\\sqrt{ rac... | the_stack_v2_python_sparse | AI Project/Project/AI/Chapter6ErrorCalc.py | IlanHindy/AI-Learn | train | 0 | |
53a22aec55869d8fcd1a53c8453f8e409d9f478d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details. | DatabaseServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseServiceServicer:
"""A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details."""
def Get(self, request, context):
"""Retrieves information about the specified database."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_005342 | 8,800 | permissive | [
{
"docstring": "Retrieves information about the specified database.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of databases in a cluster.",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"docstring":... | 4 | null | Implement the Python class `DatabaseServiceServicer` described below.
Class description:
A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details.
Method signatures and docstrings:
- def Get(self, request, context): Retrieves information... | Implement the Python class `DatabaseServiceServicer` described below.
Class description:
A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details.
Method signatures and docstrings:
- def Get(self, request, context): Retrieves information... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class DatabaseServiceServicer:
"""A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details."""
def Get(self, request, context):
"""Retrieves information about the specified database."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseServiceServicer:
"""A set of methods for managing MySQL databases in a cluster. See [the documentation](/docs/managed-mysql/operations/databases) for details."""
def Get(self, request, context):
"""Retrieves information about the specified database."""
context.set_code(grpc.Status... | the_stack_v2_python_sparse | yandex/cloud/mdb/mysql/v1/database_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
a7b47a5a44788ad09de86c3227d85f8ec52e2ce8 | [
"super().__init__(*args, **kwargs)\nself.invite_only = invite_only\nself.show_invisible = show_invisible",
"existing_groups: Iterable[Group]\ninput_value: Optional[str]\nif value:\n if not self.multivalued:\n value = [value]\n value = [v for v in value if v]\n input_value = ','.join((force_str(v) ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.invite_only = invite_only
self.show_invisible = show_invisible
<|end_body_0|>
<|body_start_1|>
existing_groups: Iterable[Group]
input_value: Optional[str]
if value:
if not self.multivalued:
... | A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible review groups. * Added support for Python type hint... | RelatedGroupWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible revie... | stack_v2_sparse_classes_36k_train_005343 | 16,804 | permissive | [
{
"docstring": "Initialize the RelatedGroupWidget. Version Changed: 5.0.6: Added the ``show_invisible`` argument. Args: invite_only (bool, optional): Whether or not to limit results to accessible review groups that are invite-only. show_invisible (bool, optional): Whether to include accessible invisible review ... | 3 | stack_v2_sparse_classes_30k_val_001064 | Implement the Python class `RelatedGroupWidget` described below.
Class description:
A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option ... | Implement the Python class `RelatedGroupWidget` described below.
Class description:
A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option ... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible revie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelatedGroupWidget:
"""A form widget allowing people to select one or more Group objects. This widget offers both the ability to see which groups are already in the list, as well as interactive search and filtering. Version Changed: 5.0.6: * Added an option for enabling specifying invisible review groups. * A... | the_stack_v2_python_sparse | reviewboard/admin/form_widgets.py | reviewboard/reviewboard | train | 1,141 |
75ca7e6efd65bc041187450c85762d1a1bb98f87 | [
"user = User.objects.get(email=email)\ntoken = Token.objects.get(user_id=user.id)\nurl = 'https://' if self.request.is_secure() else 'http://'\nurl += get_current_site(self.request).domain\nurl += '/en/activate/' + str(user.id) + '/' + str(token) + '/'\nreturn url",
"contact_list = [env_var('DEFAULT_TO_EMAIL')]\n... | <|body_start_0|>
user = User.objects.get(email=email)
token = Token.objects.get(user_id=user.id)
url = 'https://' if self.request.is_secure() else 'http://'
url += get_current_site(self.request).domain
url += '/en/activate/' + str(user.id) + '/' + str(token) + '/'
return ... | SendEmailViewMixin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailViewMixin:
def activation_url(self, email):
"""Function will get the User ID and Token and generate a URL."""
<|body_0|>
def send_activation(self, email):
"""Function will send to the inputted email the URL that needs to be accessed to activate the account."... | stack_v2_sparse_classes_36k_train_005344 | 2,444 | permissive | [
{
"docstring": "Function will get the User ID and Token and generate a URL.",
"name": "activation_url",
"signature": "def activation_url(self, email)"
},
{
"docstring": "Function will send to the inputted email the URL that needs to be accessed to activate the account.",
"name": "send_activa... | 2 | stack_v2_sparse_classes_30k_train_001779 | Implement the Python class `SendEmailViewMixin` described below.
Class description:
Implement the SendEmailViewMixin class.
Method signatures and docstrings:
- def activation_url(self, email): Function will get the User ID and Token and generate a URL.
- def send_activation(self, email): Function will send to the inp... | Implement the Python class `SendEmailViewMixin` described below.
Class description:
Implement the SendEmailViewMixin class.
Method signatures and docstrings:
- def activation_url(self, email): Function will get the User ID and Token and generate a URL.
- def send_activation(self, email): Function will send to the inp... | 053973b5ff0b997c52bfaca8daf8e07db64a877c | <|skeleton|>
class SendEmailViewMixin:
def activation_url(self, email):
"""Function will get the User ID and Token and generate a URL."""
<|body_0|>
def send_activation(self, email):
"""Function will send to the inputted email the URL that needs to be accessed to activate the account."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendEmailViewMixin:
def activation_url(self, email):
"""Function will get the User ID and Token and generate a URL."""
user = User.objects.get(email=email)
token = Token.objects.get(user_id=user.id)
url = 'https://' if self.request.is_secure() else 'http://'
url += get_... | the_stack_v2_python_sparse | api/views/authentication/emailactivation.py | smegurus/smegurus-django | train | 1 | |
0f0042bac6280e2f134fee52d022bc8c142dd402 | [
"nums = map(int, str(n))\nll = len(nums)\nans = []\n\ndef dfs(pos, prev, fr, flag):\n e = 9\n if pos >= ll:\n return\n to = 9\n if flag:\n to = nums[pos]\n for i in xrange(fr, to + 1):\n x = prev + i\n ans.append(x)\n newflag = 0\n if i <= nums[pos]:\n ... | <|body_start_0|>
nums = map(int, str(n))
ll = len(nums)
ans = []
def dfs(pos, prev, fr, flag):
e = 9
if pos >= ll:
return
to = 9
if flag:
to = nums[pos]
for i in xrange(fr, to + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrderWA2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|... | stack_v2_sparse_classes_36k_train_005345 | 3,020 | no_license | [
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrderWA",
"signature": "def lexicalOrderWA(self, n)"
},
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrderWA2",
"signature": "def lexicalOrderWA2(self, n)"
},
{
"docstring": ":type n: int :rtype:... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrderWA(self, n): :type n: int :rtype: List[int]
- def lexicalOrderWA2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder(self, n): :type n: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrderWA(self, n): :type n: int :rtype: List[int]
- def lexicalOrderWA2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder(self, n): :type n: int :rtype: List[... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrderWA2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
nums = map(int, str(n))
ll = len(nums)
ans = []
def dfs(pos, prev, fr, flag):
e = 9
if pos >= ll:
return
to = 9
if flag:
... | the_stack_v2_python_sparse | python/leetcode.386.py | CalvinNeo/LeetCode | train | 3 | |
c5381e70c13bc5a1690ce7c828e7e43f921a569a | [
"num_samples = pred.size(0)\nif num_samples != len(labels):\n raise ValueError(f'Number of samples should be equal to that of labels, but got {num_samples} samples and {len(labels)} labels.')\nlosses = torch.zeros(num_samples, device=pred.device)\nslopes = torch.zeros(num_samples, device=pred.device)\nfor i in r... | <|body_start_0|>
num_samples = pred.size(0)
if num_samples != len(labels):
raise ValueError(f'Number of samples should be equal to that of labels, but got {num_samples} samples and {len(labels)} labels.')
losses = torch.zeros(num_samples, device=pred.device)
slopes = torch.ze... | This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM). | OHEMHingeLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OHEMHingeLoss:
"""This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM)."""
def forward(ctx, pred, labels, is_positive, ohem_ratio, group_size):
"""Calculate OHEM hinge loss. Args: pre... | stack_v2_sparse_classes_36k_train_005346 | 2,666 | permissive | [
{
"docstring": "Calculate OHEM hinge loss. Args: pred (torch.Tensor): Predicted completeness score. labels (torch.Tensor): Groundtruth class label. is_positive (int): Set to 1 when proposals are positive and set to -1 when proposals are incomplete. ohem_ratio (float): Ratio of hard examples. group_size (int): N... | 2 | null | Implement the Python class `OHEMHingeLoss` described below.
Class description:
This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM).
Method signatures and docstrings:
- def forward(ctx, pred, labels, is_positive, ohem... | Implement the Python class `OHEMHingeLoss` described below.
Class description:
This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM).
Method signatures and docstrings:
- def forward(ctx, pred, labels, is_positive, ohem... | 582b78fd6c3240500d5cacd292339d7d1ddbb056 | <|skeleton|>
class OHEMHingeLoss:
"""This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM)."""
def forward(ctx, pred, labels, is_positive, ohem_ratio, group_size):
"""Calculate OHEM hinge loss. Args: pre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OHEMHingeLoss:
"""This class is the core implementation for the completeness loss in paper. It compute class-wise hinge loss and performs online hard example mining (OHEM)."""
def forward(ctx, pred, labels, is_positive, ohem_ratio, group_size):
"""Calculate OHEM hinge loss. Args: pred (torch.Tens... | the_stack_v2_python_sparse | mmaction/models/losses/ohem_hinge_loss.py | open-mmlab/mmaction2 | train | 3,498 |
8c28fd46b2929ecb87809299e1a9b4479448f58f | [
"super(HierarchicalAttentionNetwork, self).__init__()\nif pretrained_weights is not None:\n initializer = tf.keras.initializers.Constant(pretrained_weights)\nelse:\n initializer = 'uniform'\nself.dropout_embedding = dropout_embedding\nself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim, embed... | <|body_start_0|>
super(HierarchicalAttentionNetwork, self).__init__()
if pretrained_weights is not None:
initializer = tf.keras.initializers.Constant(pretrained_weights)
else:
initializer = 'uniform'
self.dropout_embedding = dropout_embedding
self.embeddin... | Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf | HierarchicalAttentionNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HierarchicalAttentionNetwork:
"""Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf"""
def __init__(self, vocab_size, embedding_dim, gru_uni... | stack_v2_sparse_classes_36k_train_005347 | 3,655 | permissive | [
{
"docstring": "Hierarchical Attention Network class constructor.",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, gru_units, attention_units, classifier_units, pretrained_weights=None, mask_zero=True, dropout_embedding=0.0)"
},
{
"docstring": "Model forward meth... | 4 | stack_v2_sparse_classes_30k_train_017606 | Implement the Python class `HierarchicalAttentionNetwork` described below.
Class description:
Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf
Method signatures and... | Implement the Python class `HierarchicalAttentionNetwork` described below.
Class description:
Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf
Method signatures and... | 9ecaf76444316da202e41042acd5993d9e6a682a | <|skeleton|>
class HierarchicalAttentionNetwork:
"""Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf"""
def __init__(self, vocab_size, embedding_dim, gru_uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HierarchicalAttentionNetwork:
"""Hierarchical Attention Network implementation. Reference : * Hierarchical Attention Networks for Document Classification : https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf"""
def __init__(self, vocab_size, embedding_dim, gru_units, attention... | the_stack_v2_python_sparse | attention_embedder/src/han.py | hehlinge42/nlp_consulting_project | train | 0 |
dd6c817209b7053dd265ac4a929759ab1900a1cd | [
"from __builtin__ import xrange\ncnt = 1\nrpc_idx = len(chars) - 1\nfor i in xrange(len(chars) - 2, -1, -1):\n if chars[i] == chars[i + 1]:\n cnt += 1\n continue\n if cnt == 1:\n chars[rpc_idx] = chars[i + 1]\n else:\n scnt = str(cnt)\n scnt_idx = len(scnt) - 1\n f... | <|body_start_0|>
from __builtin__ import xrange
cnt = 1
rpc_idx = len(chars) - 1
for i in xrange(len(chars) - 2, -1, -1):
if chars[i] == chars[i + 1]:
cnt += 1
continue
if cnt == 1:
chars[rpc_idx] = chars[i + 1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?"""
<|body_0|>
def rewrite(self, chars):
""":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?"""
<|body_... | stack_v2_sparse_classes_36k_train_005348 | 3,877 | no_license | [
{
"docstring": ":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?",
"name": "compress",
"signature": "def compress(self, chars)"
},
{
"docstring": ":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?",
"name": "rewrite",
"si... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?
- def rewrite(self, chars): :type chars: List[str] :rtype: int Could... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?
- def rewrite(self, chars): :type chars: List[str] :rtype: int Could... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?"""
<|body_0|>
def rewrite(self, chars):
""":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int Could you solve it using only O(1) extra space?"""
from __builtin__ import xrange
cnt = 1
rpc_idx = len(chars) - 1
for i in xrange(len(chars) - 2, -1, -1):
if chars[i] == chars[i + 1]... | the_stack_v2_python_sparse | co_lyft/443_String_Compression.py | vsdrun/lc_public | train | 6 | |
6dbbf34b08a0889690a98890dfe0b9a8ce610b0b | [
"self.context_length = self.config.context_path.num_blocks\nself.double_channel = self.config.context_path.num_double_channel\nself.context_num_stage = self.config.context_path.num_stage\nself.spatial_length = self.config.spatial_path.num_blocks\nself.spatial_num_stages = self.config.spatial_path.num_stages",
"ar... | <|body_start_0|>
self.context_length = self.config.context_path.num_blocks
self.double_channel = self.config.context_path.num_double_channel
self.context_num_stage = self.config.context_path.num_stage
self.spatial_length = self.config.spatial_path.num_blocks
self.spatial_num_stag... | Random algorithm of SegmentationNas. | SegmentationRandom | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
<|body_0|>
def random_context_generator(self, length=10, num_reduction=3, n... | stack_v2_sparse_classes_36k_train_005349 | 3,505 | permissive | [
{
"docstring": "Construct the SegmentationRandom class. :param search_space: Config of the search space",
"name": "__init__",
"signature": "def __init__(self, search_space=None)"
},
{
"docstring": "Generate a random code of BiSeNet's context path. :param length: Length of the BiSeNet's context p... | 4 | null | Implement the Python class `SegmentationRandom` described below.
Class description:
Random algorithm of SegmentationNas.
Method signatures and docstrings:
- def __init__(self, search_space=None): Construct the SegmentationRandom class. :param search_space: Config of the search space
- def random_context_generator(sel... | Implement the Python class `SegmentationRandom` described below.
Class description:
Random algorithm of SegmentationNas.
Method signatures and docstrings:
- def __init__(self, search_space=None): Construct the SegmentationRandom class. :param search_space: Config of the search space
- def random_context_generator(sel... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
<|body_0|>
def random_context_generator(self, length=10, num_reduction=3, n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentationRandom:
"""Random algorithm of SegmentationNas."""
def __init__(self, search_space=None):
"""Construct the SegmentationRandom class. :param search_space: Config of the search space"""
self.context_length = self.config.context_path.num_blocks
self.double_channel = self.... | the_stack_v2_python_sparse | vega/algorithms/nas/segmentation_ea/segmentation_random.py | huawei-noah/vega | train | 850 |
46f6323152812c2a896c080b548a898beb68a64d | [
"@configurable\ndef dummy_func(x: str='hi', y: int=1) -> int:\n return (x, y)\nself.assertEqual(dummy_func(), ('hi', 1))\nself.assertEqual(dummy_func('bye', 2), ('bye', 2))\nself.assertEqual(dummy_func(x='bye', y=2), ('bye', 2))",
"@configurable('dummy', 'no')\ndef dummy_func(x: str='hi', y: int=1) -> int:\n ... | <|body_start_0|>
@configurable
def dummy_func(x: str='hi', y: int=1) -> int:
return (x, y)
self.assertEqual(dummy_func(), ('hi', 1))
self.assertEqual(dummy_func('bye', 2), ('bye', 2))
self.assertEqual(dummy_func(x='bye', y=2), ('bye', 2))
<|end_body_0|>
<|body_start_... | Tests for configurable decorator. | TestConfigurable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConfigurable:
"""Tests for configurable decorator."""
def test_configurable_minimal(self):
"""Test configurable with no parameters"""
<|body_0|>
def test_configurable_named(self):
"""Test configurable with no parameters"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_005350 | 1,798 | permissive | [
{
"docstring": "Test configurable with no parameters",
"name": "test_configurable_minimal",
"signature": "def test_configurable_minimal(self)"
},
{
"docstring": "Test configurable with no parameters",
"name": "test_configurable_named",
"signature": "def test_configurable_named(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_017901 | Implement the Python class `TestConfigurable` described below.
Class description:
Tests for configurable decorator.
Method signatures and docstrings:
- def test_configurable_minimal(self): Test configurable with no parameters
- def test_configurable_named(self): Test configurable with no parameters | Implement the Python class `TestConfigurable` described below.
Class description:
Tests for configurable decorator.
Method signatures and docstrings:
- def test_configurable_minimal(self): Test configurable with no parameters
- def test_configurable_named(self): Test configurable with no parameters
<|skeleton|>
clas... | 581608cfc4d9b485182c6f5f40dd2ab7540cec66 | <|skeleton|>
class TestConfigurable:
"""Tests for configurable decorator."""
def test_configurable_minimal(self):
"""Test configurable with no parameters"""
<|body_0|>
def test_configurable_named(self):
"""Test configurable with no parameters"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestConfigurable:
"""Tests for configurable decorator."""
def test_configurable_minimal(self):
"""Test configurable with no parameters"""
@configurable
def dummy_func(x: str='hi', y: int=1) -> int:
return (x, y)
self.assertEqual(dummy_func(), ('hi', 1))
... | the_stack_v2_python_sparse | projects/coda/probing/_src/configurable_test.py | nala-cub/coda | train | 2 |
d6ed850c2215bd27f976d8f3ce2cda6bbe8d4a17 | [
"self.d = len(a)\nassert len(b) == self.d\nassert len(orders) == self.d\nself.a = np.array(a, dtype=float)\nself.b = np.array(b, dtype=float)\nself.orders = np.array(orders, dtype=int)\nself.__mcoeffs__ = None\nif values is not None:\n self.set_values(values)",
"mvalues = np.array(mvalues, dtype=float)\nn_sp =... | <|body_start_0|>
self.d = len(a)
assert len(b) == self.d
assert len(orders) == self.d
self.a = np.array(a, dtype=float)
self.b = np.array(b, dtype=float)
self.orders = np.array(orders, dtype=int)
self.__mcoeffs__ = None
if values is not None:
s... | CubicSplines | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubicSplines:
def __init__(self, a, b, orders, values=None):
"""Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid."""
<|body_0|>
def set_values(self, mvalues):
"""Change values on the nodes of the functions to approximate."""
... | stack_v2_sparse_classes_36k_train_005351 | 7,068 | permissive | [
{
"docstring": "Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid.",
"name": "__init__",
"signature": "def __init__(self, a, b, orders, values=None)"
},
{
"docstring": "Change values on the nodes of the functions to approximate.",
"name": "set_values",
... | 5 | stack_v2_sparse_classes_30k_train_004746 | Implement the Python class `CubicSplines` described below.
Class description:
Implement the CubicSplines class.
Method signatures and docstrings:
- def __init__(self, a, b, orders, values=None): Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid.
- def set_values(self, mvalues): ... | Implement the Python class `CubicSplines` described below.
Class description:
Implement the CubicSplines class.
Method signatures and docstrings:
- def __init__(self, a, b, orders, values=None): Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid.
- def set_values(self, mvalues): ... | 19b2cd3882003c19b7aeb7c35fca5cdad3fe1d5e | <|skeleton|>
class CubicSplines:
def __init__(self, a, b, orders, values=None):
"""Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid."""
<|body_0|>
def set_values(self, mvalues):
"""Change values on the nodes of the functions to approximate."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CubicSplines:
def __init__(self, a, b, orders, values=None):
"""Creates a cubic multi-spline interpolator for many functions on a regular cartesian grid."""
self.d = len(a)
assert len(b) == self.d
assert len(orders) == self.d
self.a = np.array(a, dtype=float)
se... | the_stack_v2_python_sparse | interpolation/splines/splines.py | EconForge/interpolation.py | train | 116 | |
28082e881cd4a9ea3e32d5330da77882be12ba43 | [
"super(CloseButton, self).__init__()\nclose_button_style = \" \\n style 'close_button' {\\n xthickness = 0\\n ythickness = 0\\n }\\n widget '*.close_button' style 'close_button'\\n \"\ngtk.rc_parse_string(close_button_style)\nself.set_name('widge... | <|body_start_0|>
super(CloseButton, self).__init__()
close_button_style = " \n style 'close_button' {\n xthickness = 0\n ythickness = 0\n }\n widget '*.close_button' style 'close_button'\n "
gtk.rc_parse_string(close_button_st... | CloseButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloseButton:
def __init__(self):
"""Constructor."""
<|body_0|>
def __add_icon_to_button(self):
"""Add the close image to this button."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CloseButton, self).__init__()
close_button_style = " ... | stack_v2_sparse_classes_36k_train_005352 | 2,000 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add the close image to this button.",
"name": "__add_icon_to_button",
"signature": "def __add_icon_to_button(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000804 | Implement the Python class `CloseButton` described below.
Class description:
Implement the CloseButton class.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def __add_icon_to_button(self): Add the close image to this button. | Implement the Python class `CloseButton` described below.
Class description:
Implement the CloseButton class.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def __add_icon_to_button(self): Add the close image to this button.
<|skeleton|>
class CloseButton:
def __init__(self):
"""... | c21ddf8aba58dc83d58a8db960d58d91ee2e5c74 | <|skeleton|>
class CloseButton:
def __init__(self):
"""Constructor."""
<|body_0|>
def __add_icon_to_button(self):
"""Add the close image to this button."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloseButton:
def __init__(self):
"""Constructor."""
super(CloseButton, self).__init__()
close_button_style = " \n style 'close_button' {\n xthickness = 0\n ythickness = 0\n }\n widget '*.close_button' style 'close_button'\n... | the_stack_v2_python_sparse | tf/widgets/closebutton.py | yurimalheiros/textflow | train | 1 | |
f40b8f34f2a169be74060fc8d366a81ec66084d8 | [
"self.download_files_path = download_files_path\nself.error = error\nself.proxy_entity_connector_params = proxy_entity_connector_params\nself.restore_files_result_vec = restore_files_result_vec\nself.slave_task_start_time_usecs = slave_task_start_time_usecs\nself.target_type = target_type\nself.teardown_error = tea... | <|body_start_0|>
self.download_files_path = download_files_path
self.error = error
self.proxy_entity_connector_params = proxy_entity_connector_params
self.restore_files_result_vec = restore_files_result_vec
self.slave_task_start_time_usecs = slave_task_start_time_usecs
se... | Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location Extn ============================================================================= vmware... | RestoreFilesInfoProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreFilesInfoProto:
"""Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location Extn ===================================... | stack_v2_sparse_classes_36k_train_005353 | 5,822 | permissive | [
{
"docstring": "Constructor for the RestoreFilesInfoProto class",
"name": "__init__",
"signature": "def __init__(self, download_files_path=None, error=None, proxy_entity_connector_params=None, restore_files_result_vec=None, slave_task_start_time_usecs=None, target_type=None, teardown_error=None, mtype=N... | 2 | null | Implement the Python class `RestoreFilesInfoProto` described below.
Class description:
Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location E... | Implement the Python class `RestoreFilesInfoProto` described below.
Class description:
Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location E... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreFilesInfoProto:
"""Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location Extn ===================================... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreFilesInfoProto:
"""Implementation of the 'RestoreFilesInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. RestoreFilesInfoProto extension Location Extn ================================================... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_files_info_proto.py | cohesity/management-sdk-python | train | 24 |
69ceede057d8c67800715a4b7ad011a513320405 | [
"import tensorflow as tf\nexecutors = []\nif not subgraphs_only:\n xgraph = AddExplicitOutputLayers(out_tensor_names, layout='NHWC')(xgraph)\n executors.append((base_name, base_name, TfGenerator.runtime_factory.build_runtime(xgraph, batch_size=batch_size, placeholder=placeholder)))\nelse:\n for Xp in TfGen... | <|body_start_0|>
import tensorflow as tf
executors = []
if not subgraphs_only:
xgraph = AddExplicitOutputLayers(out_tensor_names, layout='NHWC')(xgraph)
executors.append((base_name, base_name, TfGenerator.runtime_factory.build_runtime(xgraph, batch_size=batch_size, placeh... | Responsible for generating tensorflow model from xgraph data structure | TfGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TfGenerator:
"""Responsible for generating tensorflow model from xgraph data structure"""
def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, placeholder: bool=False, out_dir: str=os.getcwd(), out_tensor_names: List[str]=None,... | stack_v2_sparse_classes_36k_train_005354 | 6,918 | permissive | [
{
"docstring": "Generate one or multiple tensorflow pb file from an xgraph and return dictionary of the base_name/partitions mapping to the pb files",
"name": "generate",
"signature": "def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, p... | 2 | null | Implement the Python class `TfGenerator` described below.
Class description:
Responsible for generating tensorflow model from xgraph data structure
Method signatures and docstrings:
- def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, placeholder: boo... | Implement the Python class `TfGenerator` described below.
Class description:
Responsible for generating tensorflow model from xgraph data structure
Method signatures and docstrings:
- def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, placeholder: boo... | 8ce8a385a155f3ffdd84ce61501ca870cfb4a905 | <|skeleton|>
class TfGenerator:
"""Responsible for generating tensorflow model from xgraph data structure"""
def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, placeholder: bool=False, out_dir: str=os.getcwd(), out_tensor_names: List[str]=None,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TfGenerator:
"""Responsible for generating tensorflow model from xgraph data structure"""
def generate(cls, xgraph: XGraph, base_name: str, subgraphs_only: bool=False, layout: str='NCHW', batch_size: int=-1, placeholder: bool=False, out_dir: str=os.getcwd(), out_tensor_names: List[str]=None, **kwargs):
... | the_stack_v2_python_sparse | python/pyxir/generator/tensorflow.py | Xilinx/pyxir | train | 34 |
12492e47e30ceeb472638c84bc3c17c54aa0f22e | [
"opts = setup_options()\nopt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', delete=False)\nopts.write_to_stream(opt_file)\nopt_file.close()\nproblem = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'mock_problems', 'all_parsers_set'))\nrun([problem], options_file=opt_file.name, debu... | <|body_start_0|>
opts = setup_options()
opt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', delete=False)
opts.write_to_stream(opt_file)
opt_file.close()
problem = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'mock_problems', 'all_parsers_set'))
... | Regression tests for the Fitbenchmarking software with all fitting software packages | TestRegressionAll | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent_all(self):
"""Regression testing t... | stack_v2_sparse_classes_36k_train_005355 | 8,084 | permissive | [
{
"docstring": "Create an options file, run it, and get the results.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Regression testing that the results of fitting a set of problems containing all problem types against a single minimizer from each of the supported s... | 3 | stack_v2_sparse_classes_30k_train_010234 | Implement the Python class `TestRegressionAll` described below.
Class description:
Regression tests for the Fitbenchmarking software with all fitting software packages
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent_all(self):... | Implement the Python class `TestRegressionAll` described below.
Class description:
Regression tests for the Fitbenchmarking software with all fitting software packages
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent_all(self):... | edae46c0361568bc537de2425d603e7b271eabe7 | <|skeleton|>
class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent_all(self):
"""Regression testing t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRegressionAll:
"""Regression tests for the Fitbenchmarking software with all fitting software packages"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
opts = setup_options()
opt_file = tempfile.NamedTemporaryFile(suffix='.ini', mode='w', dele... | the_stack_v2_python_sparse | fitbenchmarking/systests/test_regression.py | dsotiropoulos/fitbenchmarking | train | 0 |
475a8050663b18d111fb0452546557fa92e174c1 | [
"if word1 == word2 or len(word1) != len(word2):\n return False\ndiffnum = 0\nwd1, wd2 = ('', '')\nfor idx, ch in enumerate(word1):\n if ch != word2[idx]:\n diffnum += 1\n if diffnum > 2:\n return False\n wd1 += ch\n wd2 += word2[idx]\nreturn diffnum == 2 and wd1 == wd2[:... | <|body_start_0|>
if word1 == word2 or len(word1) != len(word2):
return False
diffnum = 0
wd1, wd2 = ('', '')
for idx, ch in enumerate(word1):
if ch != word2[idx]:
diffnum += 1
if diffnum > 2:
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def metaWord(self, word1, word2):
"""Only one swap solution"""
<|body_0|>
def metaWordMultipleSwap(self, word1, word2):
"""Check if can swap at most n times to make word2 be word1 n = len(word1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005356 | 2,550 | no_license | [
{
"docstring": "Only one swap solution",
"name": "metaWord",
"signature": "def metaWord(self, word1, word2)"
},
{
"docstring": "Check if can swap at most n times to make word2 be word1 n = len(word1)",
"name": "metaWordMultipleSwap",
"signature": "def metaWordMultipleSwap(self, word1, wo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def metaWord(self, word1, word2): Only one swap solution
- def metaWordMultipleSwap(self, word1, word2): Check if can swap at most n times to make word2 be word1 n = len(word1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def metaWord(self, word1, word2): Only one swap solution
- def metaWordMultipleSwap(self, word1, word2): Check if can swap at most n times to make word2 be word1 n = len(word1)
... | 4d340a45fb2e9459d47cbe179ebfa7a82e5f1b8c | <|skeleton|>
class Solution:
def metaWord(self, word1, word2):
"""Only one swap solution"""
<|body_0|>
def metaWordMultipleSwap(self, word1, word2):
"""Check if can swap at most n times to make word2 be word1 n = len(word1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def metaWord(self, word1, word2):
"""Only one swap solution"""
if word1 == word2 or len(word1) != len(word2):
return False
diffnum = 0
wd1, wd2 = ('', '')
for idx, ch in enumerate(word1):
if ch != word2[idx]:
diffnum += ... | the_stack_v2_python_sparse | Google_interview/MetaWord.py | llgeek/leetcode | train | 1 | |
9abbb516d5fa52ead1845cfc888b466131d9d205 | [
"super(Embedding, self).__init__()\nself.embed = nn.Embedding(num_classes, embedding_dim, padding_idx=ignore_index)\nself.dropout = nn.Dropout(p=dropout)",
"y = self.embed(y)\ny = self.dropout(y)\nreturn y"
] | <|body_start_0|>
super(Embedding, self).__init__()
self.embed = nn.Embedding(num_classes, embedding_dim, padding_idx=ignore_index)
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
y = self.embed(y)
y = self.dropout(y)
return y
<|end_body_1|>
| Embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float... | stack_v2_sparse_classes_36k_train_005357 | 4,283 | no_license | [
{
"docstring": "Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float, optional): the probability to drop nodes of the embedding ignore_index (int, optional):",
"n... | 2 | stack_v2_sparse_classes_30k_train_014096 | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and ... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and ... | b6b60a338d65bb369d0034f423feb09db10db8b7 | <|skeleton|>
class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedding:
def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1):
"""Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float, optional): t... | the_stack_v2_python_sparse | models/pytorch/linear.py | carolinebear/pytorch_end2end_speech_recognition | train | 0 | |
88e7b9bb003d1eaf160b2ae840cb25f7b587cdc9 | [
"nums.sort()\nn = len(nums)\nres = []\n\ndef helper(i, tmp):\n res.append(tmp)\n for j in range(i, n):\n if j > i and nums[j] == nums[j - 1]:\n continue\n helper(j + 1, tmp + [nums[j]])\nhelper(0, [])\nreturn res",
"nums.sort()\nn = len(nums)\nres = []\n\ndef helper(i, tmp):\n if... | <|body_start_0|>
nums.sort()
n = len(nums)
res = []
def helper(i, tmp):
res.append(tmp)
for j in range(i, n):
if j > i and nums[j] == nums[j - 1]:
continue
helper(j + 1, tmp + [nums[j]])
helper(0, [])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def subsetsWithDup(self, nums):
""":type nums:... | stack_v2_sparse_classes_36k_train_005358 | 1,955 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def subsetsWithDup(self, nums):
""":type nums:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
n = len(nums)
res = []
def helper(i, tmp):
res.append(tmp)
for j in range(i, n):
if j > i and nums[j] == nums[j - 1]:
... | the_stack_v2_python_sparse | 0090_Subsets_II.py | bingli8802/leetcode | train | 0 | |
fd8c7c5eaf409a616faa419c351c99a95f78e6c8 | [
"import itertools\nret = 0\nfor a, b, c in itertools.permutations(A, 3):\n if a < b + c and b < a + c and (c < a + b):\n ret = max(ret, a + b + c)\nreturn ret",
"ret = 0\nA = sorted(A, reverse=True)\nfor i in range(0, len(A)):\n a = A[i]\n for j in range(i + 1, len(A)):\n b = A[j]\n ... | <|body_start_0|>
import itertools
ret = 0
for a, b, c in itertools.permutations(A, 3):
if a < b + c and b < a + c and (c < a + b):
ret = max(ret, a + b + c)
return ret
<|end_body_0|>
<|body_start_1|>
ret = 0
A = sorted(A, reverse=True)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestPerimeter(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def largestPerimeter(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import itertools
ret = 0
for a,... | stack_v2_sparse_classes_36k_train_005359 | 1,183 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "largestPerimeter",
"signature": "def largestPerimeter(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "largestPerimeter",
"signature": "def largestPerimeter(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013988 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestPerimeter(self, A): :type A: List[int] :rtype: int
- def largestPerimeter(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestPerimeter(self, A): :type A: List[int] :rtype: int
- def largestPerimeter(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def largestPerime... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def largestPerimeter(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def largestPerimeter(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestPerimeter(self, A):
""":type A: List[int] :rtype: int"""
import itertools
ret = 0
for a, b, c in itertools.permutations(A, 3):
if a < b + c and b < a + c and (c < a + b):
ret = max(ret, a + b + c)
return ret
def larg... | the_stack_v2_python_sparse | largest-perimeter-triangle/solution.py | uxlsl/leetcode_practice | train | 0 | |
7bbe54736cfa713b18a953dd3302500bf6faf161 | [
"n = len(nums)\nf, g = ([0] * n, [0] * n)\nf[0], g[0] = (nums[0], nums[0])\nfor i in range(1, n):\n f[i] = max(max(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i])\n g[i] = min(min(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i])\nreturn max(f)",
"m = 1\nres = nums[0]\nfor i in nums:\n m *= i\n if r... | <|body_start_0|>
n = len(nums)
f, g = ([0] * n, [0] * n)
f[0], g[0] = (nums[0], nums[0])
for i in range(1, n):
f[i] = max(max(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i])
g[i] = min(min(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i])
return max(f)
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
"""动态规划 :param nums: :return:"""
<|body_0|>
def maxProduct2(self, nums):
"""暴力解法 求最大值,可以看成求被0拆分的各个子数组的最大值。 当一个数组中没有0存在,则分为两种情况: 1.负数为偶数个,则整个数组的各个值相乘为最大值; 2.负数为奇数个,则从左边开始,乘到最后一个负数停止有一个“最大值”,从右边也有一个“最大值”,比较,得出最大值。 :param nums: :ret... | stack_v2_sparse_classes_36k_train_005360 | 3,279 | no_license | [
{
"docstring": "动态规划 :param nums: :return:",
"name": "maxProduct",
"signature": "def maxProduct(self, nums)"
},
{
"docstring": "暴力解法 求最大值,可以看成求被0拆分的各个子数组的最大值。 当一个数组中没有0存在,则分为两种情况: 1.负数为偶数个,则整个数组的各个值相乘为最大值; 2.负数为奇数个,则从左边开始,乘到最后一个负数停止有一个“最大值”,从右边也有一个“最大值”,比较,得出最大值。 :param nums: :return:",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): 动态规划 :param nums: :return:
- def maxProduct2(self, nums): 暴力解法 求最大值,可以看成求被0拆分的各个子数组的最大值。 当一个数组中没有0存在,则分为两种情况: 1.负数为偶数个,则整个数组的各个值相乘为最大值; 2.负数为奇数个,则从左边开... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): 动态规划 :param nums: :return:
- def maxProduct2(self, nums): 暴力解法 求最大值,可以看成求被0拆分的各个子数组的最大值。 当一个数组中没有0存在,则分为两种情况: 1.负数为偶数个,则整个数组的各个值相乘为最大值; 2.负数为奇数个,则从左边开... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
"""动态规划 :param nums: :return:"""
<|body_0|>
def maxProduct2(self, nums):
"""暴力解法 求最大值,可以看成求被0拆分的各个子数组的最大值。 当一个数组中没有0存在,则分为两种情况: 1.负数为偶数个,则整个数组的各个值相乘为最大值; 2.负数为奇数个,则从左边开始,乘到最后一个负数停止有一个“最大值”,从右边也有一个“最大值”,比较,得出最大值。 :param nums: :ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, nums):
"""动态规划 :param nums: :return:"""
n = len(nums)
f, g = ([0] * n, [0] * n)
f[0], g[0] = (nums[0], nums[0])
for i in range(1, n):
f[i] = max(max(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i])
g[i] = min(min(f... | the_stack_v2_python_sparse | 152_乘积最大子序列.py | lovehhf/LeetCode | train | 0 | |
cf8ad7922cb70a6d2afaa818d62998ace58c1142 | [
"app.setStyle('Fusion')\nwith open(self._STYLESHEET) as stylesheet:\n app.setStyleSheet(stylesheet.read())",
"darkPalette = QPalette()\ndarkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))\ndarkPalette.setColor(QPalette.Button, QColor(53, 53, 53))\ndarkPalette.setColor(QPalette.Light, QColor(180, 1... | <|body_start_0|>
app.setStyle('Fusion')
with open(self._STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read())
<|end_body_0|>
<|body_start_1|>
darkPalette = QPalette()
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPal... | DarkStyle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
<|body_0|>
def apply_style(self, app):
"""Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ... | stack_v2_sparse_classes_36k_train_005361 | 5,792 | permissive | [
{
"docstring": "Apply base theme to the application. Args: app (QApplication): QApplication instance.",
"name": "_apply_base_theme",
"signature": "def _apply_base_theme(self, app)"
},
{
"docstring": "Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance... | 2 | stack_v2_sparse_classes_30k_train_002300 | Implement the Python class `DarkStyle` described below.
Class description:
Implement the DarkStyle class.
Method signatures and docstrings:
- def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance.
- def apply_style(self, app): Apply Dark Theme to the Qt... | Implement the Python class `DarkStyle` described below.
Class description:
Implement the DarkStyle class.
Method signatures and docstrings:
- def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance.
- def apply_style(self, app): Apply Dark Theme to the Qt... | 7a79feab40ec801198ea5d519948ccbfd0203df3 | <|skeleton|>
class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
<|body_0|>
def apply_style(self, app):
"""Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
app.setStyle('Fusion')
with open(self._STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read())
def apply_style(self, app):
... | the_stack_v2_python_sparse | folderplay/gui/styles.py | hurlenko/folderplay | train | 1 | |
bc5961805e73c9597574886d68e362772364fe45 | [
"self.kv_table = create_kv_table(capacity=capacity, value_len=value_len, key_type=np.int64, value_type=np.float32, kwargs=kwargs, solver=solver)\nself.wait_get_id = None\nself.wait_add_id = None\nself.value = Tensor([1], np.float32)\nself.grad = Tensor([1], np.float32)",
"assert isinstance(key, Tensor)\nassert is... | <|body_start_0|>
self.kv_table = create_kv_table(capacity=capacity, value_len=value_len, key_type=np.int64, value_type=np.float32, kwargs=kwargs, solver=solver)
self.wait_get_id = None
self.wait_add_id = None
self.value = Tensor([1], np.float32)
self.grad = Tensor([1], np.float32... | The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding. | Embedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
<|body_0|>
def get(self, key, next_ke... | stack_v2_sparse_classes_36k_train_005362 | 2,349 | permissive | [
{
"docstring": "The constructor of Embedding",
"name": "__init__",
"signature": "def __init__(self, capacity, value_len, kwargs={}, solver='adam')"
},
{
"docstring": "get current key's value and pre-get the next key. Parameters ---------- key: The current iteration id key, which is Tensor instan... | 3 | stack_v2_sparse_classes_30k_train_003084 | Implement the Python class `Embedding` described below.
Class description:
The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding.
Method signatures and docstrings:
- def __init__(self, capacity, value_len, kwargs={}, solver='adam'): The constructor of Embedd... | Implement the Python class `Embedding` described below.
Class description:
The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding.
Method signatures and docstrings:
- def __init__(self, capacity, value_len, kwargs={}, solver='adam'): The constructor of Embedd... | 3333a669c59ce2e525945f814a54784dafc6191b | <|skeleton|>
class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
<|body_0|>
def get(self, key, next_ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedding:
"""The embedding model param manager, which is used for managing and synchronizing the variables in sparse embedding."""
def __init__(self, capacity, value_len, kwargs={}, solver='adam'):
"""The constructor of Embedding"""
self.kv_table = create_kv_table(capacity=capacity, valu... | the_stack_v2_python_sparse | binding/python/ddls/topi/embedding.py | kiminh/ddls | train | 0 |
dae4d394219df204507c79475d1475a8fef54d4c | [
"logging.info('Building component: %s', self.spec.name)\nstride = state.current_batch_size * self.training_beam_size\nwith tf.variable_scope(self.name, reuse=True):\n state.handle, fixed_embeddings = fetch_differentiable_fixed_embeddings(self, state, stride)\nlinked_embeddings = [fetch_linked_embedding(self, net... | <|body_start_0|>
logging.info('Building component: %s', self.spec.name)
stride = state.current_batch_size * self.training_beam_size
with tf.variable_scope(self.name, reuse=True):
state.handle, fixed_embeddings = fetch_differentiable_fixed_embeddings(self, state, stride)
linke... | A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does not work during inference. 2. Linked features may not be recurrent and are 'untranslated'. For now, lin... | BulkFeatureExtractorComponentBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkFeatureExtractorComponentBuilder:
"""A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does not work during inference. 2. Linked fe... | stack_v2_sparse_classes_36k_train_005363 | 18,694 | permissive | [
{
"docstring": "Extracts features and advances a batch using the oracle path. Args: state: MasterState from the 'AdvanceMaster' op that advances the underlying master to this component. network_states: dictionary of component NetworkState objects Returns: state handle: final state after advancing cost: regulari... | 2 | null | Implement the Python class `BulkFeatureExtractorComponentBuilder` described below.
Class description:
A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does ... | Implement the Python class `BulkFeatureExtractorComponentBuilder` described below.
Class description:
A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does ... | 7f8c93c96a7ab5e150f217b7c369bec9d4b8bb81 | <|skeleton|>
class BulkFeatureExtractorComponentBuilder:
"""A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does not work during inference. 2. Linked fe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BulkFeatureExtractorComponentBuilder:
"""A component builder to bulk extract features. Both fixed and linked features are supported, with some restrictions: 1. Fixed features may not be recurrent. Fixed features are extracted along the gold path, which does not work during inference. 2. Linked features may no... | the_stack_v2_python_sparse | syntaxnet/dragnn/python/bulk_component.py | sshleifer/object_detection_kitti | train | 35 |
b3af6bc7ad2593f680e8cd64776897ab564a1f3a | [
"if name in self.events:\n for event in self.events[name]:\n await event(*args, **kwargs)",
"def inner(func):\n self.add_event(func, name)\n return func\nreturn inner",
"name = func.__name__ if not name else name\nif not asyncio.iscoroutinefunction(func):\n raise TypeError('Listeners must be ... | <|body_start_0|>
if name in self.events:
for event in self.events[name]:
await event(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
def inner(func):
self.add_event(func, name)
return func
return inner
<|end_body_1|>
<|body_start_2|>
... | An event manager that manages events for managers. | EventManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventManager:
"""An event manager that manages events for managers."""
async def call_event(self, name: str, *args, **kwargs) -> None:
"""Calls the event name with the arguments :param name: The event name. :type name: str :param args: The arguments. :param kwargs: The key arguments.... | stack_v2_sparse_classes_36k_train_005364 | 13,700 | permissive | [
{
"docstring": "Calls the event name with the arguments :param name: The event name. :type name: str :param args: The arguments. :param kwargs: The key arguments. :return: None :rtype: None",
"name": "call_event",
"signature": "async def call_event(self, name: str, *args, **kwargs) -> None"
},
{
... | 4 | stack_v2_sparse_classes_30k_val_000187 | Implement the Python class `EventManager` described below.
Class description:
An event manager that manages events for managers.
Method signatures and docstrings:
- async def call_event(self, name: str, *args, **kwargs) -> None: Calls the event name with the arguments :param name: The event name. :type name: str :par... | Implement the Python class `EventManager` described below.
Class description:
An event manager that manages events for managers.
Method signatures and docstrings:
- async def call_event(self, name: str, *args, **kwargs) -> None: Calls the event name with the arguments :param name: The event name. :type name: str :par... | 284fd0fe170d24922cd225ed64617bec4353fece | <|skeleton|>
class EventManager:
"""An event manager that manages events for managers."""
async def call_event(self, name: str, *args, **kwargs) -> None:
"""Calls the event name with the arguments :param name: The event name. :type name: str :param args: The arguments. :param kwargs: The key arguments.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventManager:
"""An event manager that manages events for managers."""
async def call_event(self, name: str, *args, **kwargs) -> None:
"""Calls the event name with the arguments :param name: The event name. :type name: str :param args: The arguments. :param kwargs: The key arguments. :return: Non... | the_stack_v2_python_sparse | discordSuperUtils/base.py | mahmoudzuine/discord-super-utils | train | 0 |
bd47cb4327463b386e295fd066f2d1930aeb14fe | [
"super(ATOCCommunicationNet, self).__init__()\nassert thought_size % 2 == 0\nself._thought_size = thought_size\nself._comm_hidden_size = thought_size // 2\nself._bi_lstm = nn.LSTM(self._thought_size, self._comm_hidden_size, bidirectional=True)",
"self._bi_lstm.flatten_parameters()\nx = data\nif isinstance(data, D... | <|body_start_0|>
super(ATOCCommunicationNet, self).__init__()
assert thought_size % 2 == 0
self._thought_size = thought_size
self._comm_hidden_size = thought_size // 2
self._bi_lstm = nn.LSTM(self._thought_size, self._comm_hidden_size, bidirectional=True)
<|end_body_0|>
<|body_s... | Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward | ATOCCommunicationNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought... | stack_v2_sparse_classes_36k_train_005365 | 18,821 | permissive | [
{
"docstring": "Overview: init method of the communication network Arguments: - thought_size (:obj:`int`): the size of input thought .. note:: communication hidden size should be half of the actor_hidden_size because of the bi-direction lstm",
"name": "__init__",
"signature": "def __init__(self, thought... | 2 | null | Implement the Python class `ATOCCommunicationNet` described below.
Class description:
Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, thought_size: int) -> None: Overview: init... | Implement the Python class `ATOCCommunicationNet` described below.
Class description:
Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward
Method signatures and docstrings:
- def __init__(self, thought_size: int) -> None: Overview: init... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ATOCCommunicationNet:
"""Overview: atoc commnication net is a bi-direction LSTM, so it can integrate all the thoughts in the group Interface: __init__, forward"""
def __init__(self, thought_size: int) -> None:
"""Overview: init method of the communication network Arguments: - thought_size (:obj:`... | the_stack_v2_python_sparse | ding/model/template/atoc.py | shengxuesun/DI-engine | train | 1 |
4f8f8882dff8b6615d3b58435b94f47e839bacc7 | [
"if hasattr(cls, '_factory'):\n parameter_configs = []\n for pc in proto.parameters:\n parameter_configs.append(proto_converters.ParameterConfigConverter.from_proto(pc))\n return cls._factory(parameter_configs=parameter_configs)\nresult = cls()\nfor pc in proto.parameters:\n result.add(proto_conv... | <|body_start_0|>
if hasattr(cls, '_factory'):
parameter_configs = []
for pc in proto.parameters:
parameter_configs.append(proto_converters.ParameterConfigConverter.from_proto(pc))
return cls._factory(parameter_configs=parameter_configs)
result = cls()
... | A Selector for all, or part of a SearchSpace. | SearchSpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchSpace:
"""A Selector for all, or part of a SearchSpace."""
def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace':
"""Extracts a SearchSpace object from a StudyConfig proto."""
<|body_0|>
def parameter_protos(self) -> List[study_pb2.StudySpec.ParameterSpe... | stack_v2_sparse_classes_36k_train_005366 | 18,489 | permissive | [
{
"docstring": "Extracts a SearchSpace object from a StudyConfig proto.",
"name": "from_proto",
"signature": "def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace'"
},
{
"docstring": "Returns the search space as a List of ParameterConfig protos.",
"name": "parameter_protos",
"... | 2 | stack_v2_sparse_classes_30k_train_008597 | Implement the Python class `SearchSpace` described below.
Class description:
A Selector for all, or part of a SearchSpace.
Method signatures and docstrings:
- def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': Extracts a SearchSpace object from a StudyConfig proto.
- def parameter_protos(self) -> List[... | Implement the Python class `SearchSpace` described below.
Class description:
A Selector for all, or part of a SearchSpace.
Method signatures and docstrings:
- def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace': Extracts a SearchSpace object from a StudyConfig proto.
- def parameter_protos(self) -> List[... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class SearchSpace:
"""A Selector for all, or part of a SearchSpace."""
def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace':
"""Extracts a SearchSpace object from a StudyConfig proto."""
<|body_0|>
def parameter_protos(self) -> List[study_pb2.StudySpec.ParameterSpe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchSpace:
"""A Selector for all, or part of a SearchSpace."""
def from_proto(cls, proto: study_pb2.StudySpec) -> 'SearchSpace':
"""Extracts a SearchSpace object from a StudyConfig proto."""
if hasattr(cls, '_factory'):
parameter_configs = []
for pc in proto.para... | the_stack_v2_python_sparse | google/cloud/aiplatform/vizier/pyvizier/study_config.py | googleapis/python-aiplatform | train | 418 |
8f628d9883f132531e7589e207ab2ae7091bff3e | [
"if len(arg_str) < 1:\n raise gdb.GdbError(\"ERROR: '%s' requires an argument.\" % name)\n return False\nelse:\n return True",
"try:\n return gdb.parse_and_eval('(%s *)0' % type_str).type.target()\nexcept RuntimeError:\n try:\n return gdb.lookup_type(type_str)\n except RuntimeError:\n ... | <|body_start_0|>
if len(arg_str) < 1:
raise gdb.GdbError("ERROR: '%s' requires an argument." % name)
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
try:
return gdb.parse_and_eval('(%s *)0' % type_str).type.target()
except R... | Internal class which provides utilities for the main command classes. | ExploreUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExploreUtils:
"""Internal class which provides utilities for the main command classes."""
def check_args(name, arg_str):
"""Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The name of the explore command. arg_str: The argument strin... | stack_v2_sparse_classes_36k_train_005367 | 26,692 | permissive | [
{
"docstring": "Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The name of the explore command. arg_str: The argument string passed to the explore command. Returns: True if adequate arguments are passed, false otherwise. Raises: gdb.GdbError if adequate argum... | 3 | stack_v2_sparse_classes_30k_train_000814 | Implement the Python class `ExploreUtils` described below.
Class description:
Internal class which provides utilities for the main command classes.
Method signatures and docstrings:
- def check_args(name, arg_str): Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The... | Implement the Python class `ExploreUtils` described below.
Class description:
Internal class which provides utilities for the main command classes.
Method signatures and docstrings:
- def check_args(name, arg_str): Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The... | b90664de0bd4c1897a9f1f5d9e360a9631d38b34 | <|skeleton|>
class ExploreUtils:
"""Internal class which provides utilities for the main command classes."""
def check_args(name, arg_str):
"""Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The name of the explore command. arg_str: The argument strin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExploreUtils:
"""Internal class which provides utilities for the main command classes."""
def check_args(name, arg_str):
"""Utility to check if adequate number of arguments are passed to an explore command. Arguments: name: The name of the explore command. arg_str: The argument string passed to t... | the_stack_v2_python_sparse | toolchain/riscv/Linux/share/gdb/python/gdb/command/explore.py | bouffalolab/bl_iot_sdk | train | 244 |
fe34104f377d589cd2ce6f37b44d38c5f3128346 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TeamFunSettings()",
"from .giphy_rating_type import GiphyRatingType\nfrom .giphy_rating_type import GiphyRatingType\nfields: Dict[str, Callable[[Any], None]] = {'allowCustomMemes': lambda n: setattr(self, 'allow_custom_memes', n.get_bo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TeamFunSettings()
<|end_body_0|>
<|body_start_1|>
from .giphy_rating_type import GiphyRatingType
from .giphy_rating_type import GiphyRatingType
fields: Dict[str, Callable[[Any], ... | TeamFunSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamFunSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamFunSettings:
"""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 Ret... | stack_v2_sparse_classes_36k_train_005368 | 3,578 | 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: TeamFunSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `TeamFunSettings` described below.
Class description:
Implement the TeamFunSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamFunSettings: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `TeamFunSettings` described below.
Class description:
Implement the TeamFunSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamFunSettings: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeamFunSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamFunSettings:
"""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 Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamFunSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamFunSettings:
"""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: TeamFunS... | the_stack_v2_python_sparse | msgraph/generated/models/team_fun_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e4e887d2eb53be8eea6d859965d5ba2b03863b32 | [
"def action(event):\n print(event)\nreturn Reactor(action)",
"def action(event):\n getattr(obj, function_name)(*args, **kwargs)\nreturn Reactor(action)",
"def action(event):\n logger.log(loglevel, str(event))\nreturn Reactor(action)",
"import requests\n\ndef action(event):\n resp = requests.post(u... | <|body_start_0|>
def action(event):
print(event)
return Reactor(action)
<|end_body_0|>
<|body_start_1|>
def action(event):
getattr(obj, function_name)(*args, **kwargs)
return Reactor(action)
<|end_body_1|>
<|body_start_2|>
def action(event):
... | A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances | ReactorFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
<|bod... | stack_v2_sparse_classes_36k_train_005369 | 2,372 | permissive | [
{
"docstring": "Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`",
"name": "stdout",
"signature": "def stdout(cls)"
},
{
"docstring": "Factory method returning a reactor that calls a method on an object. Args: obj (object): the tar... | 4 | stack_v2_sparse_classes_30k_train_011689 | Implement the Python class `ReactorFactory` described below.
Class description:
A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances
Method signatures and docstrings:
- def stdout(cls): Factory method returning a reactor that prints events to stdout. Returns:... | Implement the Python class `ReactorFactory` described below.
Class description:
A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances
Method signatures and docstrings:
- def stdout(cls): Factory method returning a reactor that prints events to stdout. Returns:... | d90da85473208fa50484d1cd3b06ce70aeb03e06 | <|skeleton|>
class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
def action(event):... | the_stack_v2_python_sparse | baroque/defaults/reactors.py | baroquehq/baroque | train | 5 |
edd55279d4257561b6a95741631e4fdb1cd5e253 | [
"res = BaseResponse()\nall_coupon = models.Coupon.objects.all()\ncoupon_dict = {}\nfor item in all_coupon:\n coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title': item.title, 'brief': item.brief, 'equal_money': item.equal_money, 'off_percent': item.off_percent, 'coupon_type': item.coupon_t... | <|body_start_0|>
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
coupon_dict = {}
for item in all_coupon:
coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title': item.title, 'brief': item.brief, 'equal_money': item.equal_money, 'off_percent'... | 优惠券发放接口 | CouponDistributionView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|body_0|>
def post(self, request):
"""领取优惠券"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
... | stack_v2_sparse_classes_36k_train_005370 | 47,779 | permissive | [
{
"docstring": "查看优惠券",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "领取优惠券",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007838 | Implement the Python class `CouponDistributionView` described below.
Class description:
优惠券发放接口
Method signatures and docstrings:
- def get(self, request): 查看优惠券
- def post(self, request): 领取优惠券 | Implement the Python class `CouponDistributionView` described below.
Class description:
优惠券发放接口
Method signatures and docstrings:
- def get(self, request): 查看优惠券
- def post(self, request): 领取优惠券
<|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|bo... | 59053c88faf76de3592b5aa02b1425b126fe2f2d | <|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|body_0|>
def post(self, request):
"""领取优惠券"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
coupon_dict = {}
for item in all_coupon:
coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title':... | the_stack_v2_python_sparse | OnlineStudy/generic/views.py | NanRenTeam-9/MongoMicroCourse | train | 0 |
e1c08673fc93484dcaf3e426732ad2104ec37b4f | [
"assert timeendpoint is 'infinity' or timeendpoint >= 0, \"The time domain endpoint should be a positive number of the string 'infinity'\"\nself.timeendpoint = timeendpoint\nassert nstates > 0, 'The number of states is not a positive integer'\nself.nstates = nstates\nself.cache = {}",
"assert ground_truth_time >=... | <|body_start_0|>
assert timeendpoint is 'infinity' or timeendpoint >= 0, "The time domain endpoint should be a positive number of the string 'infinity'"
self.timeendpoint = timeendpoint
assert nstates > 0, 'The number of states is not a positive integer'
self.nstates = nstates
se... | ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined conventionally with a lag of 1. The sets of states are assumed to be constant and finite ... | NonstationaryMM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonstationaryMM:
"""ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined conventionally with a lag of 1. The sets of st... | stack_v2_sparse_classes_36k_train_005371 | 6,465 | no_license | [
{
"docstring": ":param nstates: int - number of states :param timeendpoint: (default='infinity') - time domain endpoint",
"name": "__init__",
"signature": "def __init__(self, nstates: int, timeendpoint='infinity')"
},
{
"docstring": "return the MM corresponding to the input evaluation time. :par... | 4 | stack_v2_sparse_classes_30k_train_004765 | Implement the Python class `NonstationaryMM` described below.
Class description:
ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined convent... | Implement the Python class `NonstationaryMM` described below.
Class description:
ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined convent... | 092238e7b984dc2a6ba294eb87348e4c582de79b | <|skeleton|>
class NonstationaryMM:
"""ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined conventionally with a lag of 1. The sets of st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonstationaryMM:
"""ToDo: Document HMM or MM? This class is for non-stationary MMs: mappings from integers within a (dimensionless) temporal domain (timedomain), either [0, timeendpoint] or [0, 'infinity') into the space of MMs, where MMs are defined conventionally with a lag of 1. The sets of states are assu... | the_stack_v2_python_sparse | ldshmm/util/nonstationary_mm.py | ag-csw/LDStreamHMMLearn | train | 1 |
c95d4a6126d6c0b873f6b1886328027a96c8ac19 | [
"payload = {'machine_name': machine_name, 'hash': hash}\ndata = request.post(endpoint='/machines/hash', payload=payload)\nreturn (data[0], data[1])",
"cmd = command.split()\ntry:\n machine_name = cmd[1]\n hash = cmd[2]\nexcept IndexError:\n console.print('Error: Please provide machine name and hash', sty... | <|body_start_0|>
payload = {'machine_name': machine_name, 'hash': hash}
data = request.post(endpoint='/machines/hash', payload=payload)
return (data[0], data[1])
<|end_body_0|>
<|body_start_1|>
cmd = command.split()
try:
machine_name = cmd[1]
hash = cmd[2... | hash class | Hash | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hash:
"""hash class"""
def send_hash(self, machine_name, hash, request):
"""send hash to server"""
<|body_0|>
def submit_hash(self, command, request):
"""send hash for check to hacksec server"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
paylo... | stack_v2_sparse_classes_36k_train_005372 | 1,159 | permissive | [
{
"docstring": "send hash to server",
"name": "send_hash",
"signature": "def send_hash(self, machine_name, hash, request)"
},
{
"docstring": "send hash for check to hacksec server",
"name": "submit_hash",
"signature": "def submit_hash(self, command, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018954 | Implement the Python class `Hash` described below.
Class description:
hash class
Method signatures and docstrings:
- def send_hash(self, machine_name, hash, request): send hash to server
- def submit_hash(self, command, request): send hash for check to hacksec server | Implement the Python class `Hash` described below.
Class description:
hash class
Method signatures and docstrings:
- def send_hash(self, machine_name, hash, request): send hash to server
- def submit_hash(self, command, request): send hash for check to hacksec server
<|skeleton|>
class Hash:
"""hash class"""
... | 37cde4576424f6499cab5d8e242a8219adf75123 | <|skeleton|>
class Hash:
"""hash class"""
def send_hash(self, machine_name, hash, request):
"""send hash to server"""
<|body_0|>
def submit_hash(self, command, request):
"""send hash for check to hacksec server"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hash:
"""hash class"""
def send_hash(self, machine_name, hash, request):
"""send hash to server"""
payload = {'machine_name': machine_name, 'hash': hash}
data = request.post(endpoint='/machines/hash', payload=payload)
return (data[0], data[1])
def submit_hash(self, co... | the_stack_v2_python_sparse | hacksec_cli/mechanism/hash/hash.py | TrendingTechnology/hacksec-cli | train | 0 |
ce1cd6275d95f154c1b7ea42c34826c87eacb5d8 | [
"super(IHModelWithBackbone, self).__init__()\nself.downsize_backbone_input = downsize_backbone_input\nself.mask_fusion = mask_fusion\nself.backbone = backbone\nself.model = model\nif mask_fusion == 'rgb':\n self.fusion = SimpleInputFusion()\nelif mask_fusion == 'sum':\n self.mask_conv = nn.Sequential(nn.Conv2... | <|body_start_0|>
super(IHModelWithBackbone, self).__init__()
self.downsize_backbone_input = downsize_backbone_input
self.mask_fusion = mask_fusion
self.backbone = backbone
self.model = model
if mask_fusion == 'rgb':
self.fusion = SimpleInputFusion()
el... | IHModelWithBackbone | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IHModelWithBackbone:
def __init__(self, model, backbone, downsize_backbone_input=False, mask_fusion='sum', backbone_conv1_channels=64):
"""Creates image harmonization model supported by the features extracted from the pre-trained backbone. Parameters ---------- model : nn.Module Image ha... | stack_v2_sparse_classes_36k_train_005373 | 3,528 | permissive | [
{
"docstring": "Creates image harmonization model supported by the features extracted from the pre-trained backbone. Parameters ---------- model : nn.Module Image harmonization model takes image and mask as an input and handles features from the backbone network. backbone : nn.Module Backbone model accepts RGB ... | 2 | null | Implement the Python class `IHModelWithBackbone` described below.
Class description:
Implement the IHModelWithBackbone class.
Method signatures and docstrings:
- def __init__(self, model, backbone, downsize_backbone_input=False, mask_fusion='sum', backbone_conv1_channels=64): Creates image harmonization model support... | Implement the Python class `IHModelWithBackbone` described below.
Class description:
Implement the IHModelWithBackbone class.
Method signatures and docstrings:
- def __init__(self, model, backbone, downsize_backbone_input=False, mask_fusion='sum', backbone_conv1_channels=64): Creates image harmonization model support... | 554bf15c5ce6e3b4ee6a219f348d416e71d3972f | <|skeleton|>
class IHModelWithBackbone:
def __init__(self, model, backbone, downsize_backbone_input=False, mask_fusion='sum', backbone_conv1_channels=64):
"""Creates image harmonization model supported by the features extracted from the pre-trained backbone. Parameters ---------- model : nn.Module Image ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IHModelWithBackbone:
def __init__(self, model, backbone, downsize_backbone_input=False, mask_fusion='sum', backbone_conv1_channels=64):
"""Creates image harmonization model supported by the features extracted from the pre-trained backbone. Parameters ---------- model : nn.Module Image harmonization mo... | the_stack_v2_python_sparse | cflearn/api/cv/third_party/iharm/model/backboned/ih_model.py | carefree0910/carefree-learn | train | 451 | |
d429ce156cadb40a081b901d84518b8504dc6be3 | [
"newcls = type.__new__(metacls, clsname, bases, clsdict)\nif 'countrycode' in clsdict and newcls.name:\n metacls.converters.append(newcls)\n metacls.converters_by_iso[newcls.countrycode] = newcls\n metacls.converters_by_classname[clsname] = newcls\nreturn newcls",
"if countrycode in cls.converters_by_iso... | <|body_start_0|>
newcls = type.__new__(metacls, clsname, bases, clsdict)
if 'countrycode' in clsdict and newcls.name:
metacls.converters.append(newcls)
metacls.converters_by_iso[newcls.countrycode] = newcls
metacls.converters_by_classname[clsname] = newcls
ret... | Meta annex factory class for online BBAN to IBAN converters. | OnlineBBANtoIBANconverters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnlineBBANtoIBANconverters:
"""Meta annex factory class for online BBAN to IBAN converters."""
def __new__(metacls, clsname, bases, clsdict):
"""Register class for online conversion when countrycode has been set"""
<|body_0|>
def bban_to_iban(cls, countrycode, bankcode=N... | stack_v2_sparse_classes_36k_train_005374 | 3,864 | no_license | [
{
"docstring": "Register class for online conversion when countrycode has been set",
"name": "__new__",
"signature": "def __new__(metacls, clsname, bases, clsdict)"
},
{
"docstring": "Generic interface to converter classes. Tests validity of resulting IBAN. Returns valid IBAN object or None",
... | 2 | null | Implement the Python class `OnlineBBANtoIBANconverters` described below.
Class description:
Meta annex factory class for online BBAN to IBAN converters.
Method signatures and docstrings:
- def __new__(metacls, clsname, bases, clsdict): Register class for online conversion when countrycode has been set
- def bban_to_i... | Implement the Python class `OnlineBBANtoIBANconverters` described below.
Class description:
Meta annex factory class for online BBAN to IBAN converters.
Method signatures and docstrings:
- def __new__(metacls, clsname, bases, clsdict): Register class for online conversion when countrycode has been set
- def bban_to_i... | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | <|skeleton|>
class OnlineBBANtoIBANconverters:
"""Meta annex factory class for online BBAN to IBAN converters."""
def __new__(metacls, clsname, bases, clsdict):
"""Register class for online conversion when countrycode has been set"""
<|body_0|>
def bban_to_iban(cls, countrycode, bankcode=N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnlineBBANtoIBANconverters:
"""Meta annex factory class for online BBAN to IBAN converters."""
def __new__(metacls, clsname, bases, clsdict):
"""Register class for online conversion when countrycode has been set"""
newcls = type.__new__(metacls, clsname, bases, clsdict)
if 'countr... | the_stack_v2_python_sparse | extra-addons/account_banking_old/old/sepa/bbantoiban.py | sgeerish/sirr_production | train | 0 |
35ebaf649bc0b5900856d6582efda4851f59517c | [
"with tempfile.TemporaryDirectory() as tmp_dir:\n test_repo = test_repos.TEST_REPOS[1]\n self.assertTrue(helper.build_image_impl(test_repo.project_name))\n host_src_dir = build_specified_commit.copy_src_from_docker(test_repo.project_name, tmp_dir)\n test_repo_manager = repo_manager.clone_repo_and_get_ma... | <|body_start_0|>
with tempfile.TemporaryDirectory() as tmp_dir:
test_repo = test_repos.TEST_REPOS[1]
self.assertTrue(helper.build_image_impl(test_repo.project_name))
host_src_dir = build_specified_commit.copy_src_from_docker(test_repo.project_name, tmp_dir)
test_r... | Tests if an image can be built from different states e.g. a commit. | BuildImageIntegrationTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildImageIntegrationTest:
"""Tests if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a specified commit. This is done by using a known regression range for a specific test case. The old com... | stack_v2_sparse_classes_36k_train_005375 | 5,754 | permissive | [
{
"docstring": "Tests if the fuzzers can build at a specified commit. This is done by using a known regression range for a specific test case. The old commit should show the error when its fuzzers run and the new one should not.",
"name": "test_build_fuzzers_from_commit",
"signature": "def test_build_fu... | 3 | stack_v2_sparse_classes_30k_train_000476 | Implement the Python class `BuildImageIntegrationTest` described below.
Class description:
Tests if an image can be built from different states e.g. a commit.
Method signatures and docstrings:
- def test_build_fuzzers_from_commit(self): Tests if the fuzzers can build at a specified commit. This is done by using a kno... | Implement the Python class `BuildImageIntegrationTest` described below.
Class description:
Tests if an image can be built from different states e.g. a commit.
Method signatures and docstrings:
- def test_build_fuzzers_from_commit(self): Tests if the fuzzers can build at a specified commit. This is done by using a kno... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class BuildImageIntegrationTest:
"""Tests if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a specified commit. This is done by using a known regression range for a specific test case. The old com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildImageIntegrationTest:
"""Tests if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a specified commit. This is done by using a known regression range for a specific test case. The old commit should sh... | the_stack_v2_python_sparse | infra/build_specified_commit_test.py | google/oss-fuzz | train | 9,438 |
091a48314e9c600d648acbdf5d959d5bf0170cda | [
"expected = 62006\nmodel: cifar.Net = cifar.load_model()\nactual = sum((p.numel() for p in model.parameters() if p.requires_grad))\nassert actual == expected",
"model: cifar.Net = cifar.load_model()\nexpected = 10\nweights: NDArrays = model.get_weights()\nassert len(weights) == expected",
"weights_expected: NDA... | <|body_start_0|>
expected = 62006
model: cifar.Net = cifar.load_model()
actual = sum((p.numel() for p in model.parameters() if p.requires_grad))
assert actual == expected
<|end_body_0|>
<|body_start_1|>
model: cifar.Net = cifar.load_model()
expected = 10
weights:... | Tests for cifar module. | CifarTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CifarTestCase:
"""Tests for cifar module."""
def test_load_model(self) -> None:
"""Test the number of (trainable) model parameters."""
<|body_0|>
def test_get_weights(self) -> None:
"""Test get_weights."""
<|body_1|>
def test_set_weights(self) -> Non... | stack_v2_sparse_classes_36k_train_005376 | 2,193 | permissive | [
{
"docstring": "Test the number of (trainable) model parameters.",
"name": "test_load_model",
"signature": "def test_load_model(self) -> None"
},
{
"docstring": "Test get_weights.",
"name": "test_get_weights",
"signature": "def test_get_weights(self) -> None"
},
{
"docstring": "T... | 3 | null | Implement the Python class `CifarTestCase` described below.
Class description:
Tests for cifar module.
Method signatures and docstrings:
- def test_load_model(self) -> None: Test the number of (trainable) model parameters.
- def test_get_weights(self) -> None: Test get_weights.
- def test_set_weights(self) -> None: T... | Implement the Python class `CifarTestCase` described below.
Class description:
Tests for cifar module.
Method signatures and docstrings:
- def test_load_model(self) -> None: Test the number of (trainable) model parameters.
- def test_get_weights(self) -> None: Test get_weights.
- def test_set_weights(self) -> None: T... | 55be690535e5f3feb33c888c3e4a586b7bdbf489 | <|skeleton|>
class CifarTestCase:
"""Tests for cifar module."""
def test_load_model(self) -> None:
"""Test the number of (trainable) model parameters."""
<|body_0|>
def test_get_weights(self) -> None:
"""Test get_weights."""
<|body_1|>
def test_set_weights(self) -> Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CifarTestCase:
"""Tests for cifar module."""
def test_load_model(self) -> None:
"""Test the number of (trainable) model parameters."""
expected = 62006
model: cifar.Net = cifar.load_model()
actual = sum((p.numel() for p in model.parameters() if p.requires_grad))
as... | the_stack_v2_python_sparse | src/py/flwr_example/pytorch_cifar/cifar_test.py | adap/flower | train | 2,999 |
81f097286be9eea88f5aea7c7086230b683ff299 | [
"res_lst = []\nfor x in range(1 << len(nums)):\n subset = []\n pow_2 = 1\n for i in range(len(nums)):\n if x & pow_2 > 0:\n subset.append(nums[i])\n pow_2 <<= 1\n res_lst.append(subset)\nreturn res_lst",
"res_lst = []\n\ndef dfs(index, subset):\n if index >= len(nums):\n ... | <|body_start_0|>
res_lst = []
for x in range(1 << len(nums)):
subset = []
pow_2 = 1
for i in range(len(nums)):
if x & pow_2 > 0:
subset.append(nums[i])
pow_2 <<= 1
res_lst.append(subset)
return re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums):
"""Use binary to implement. :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
"""DFS :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005377 | 1,012 | no_license | [
{
"docstring": "Use binary to implement. :type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
},
{
"docstring": "DFS :type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008166 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums): Use binary to implement. :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): DFS :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 subsets(self, nums): Use binary to implement. :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): DFS :type nums: List[int] :rtype: List[List[int]]
<|sk... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def subsets(self, nums):
"""Use binary to implement. :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
"""DFS :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 subsets(self, nums):
"""Use binary to implement. :type nums: List[int] :rtype: List[List[int]]"""
res_lst = []
for x in range(1 << len(nums)):
subset = []
pow_2 = 1
for i in range(len(nums)):
if x & pow_2 > 0:
... | the_stack_v2_python_sparse | python_solution/BitManipulation/78_Subsets.py | Dimen61/leetcode | train | 4 | |
6384efa65349068d425ebe8be4a5ed4fe484f8db | [
"seen, res = (set(''), '')\nbuckets = defaultdict(list)\nmin_len, max_len = (float('inf'), float('-inf'))\nfor idx, w in enumerate(words):\n buckets[len(w)].append(idx)\n min_len, max_len = (min(min_len, len(w)), max(max_len, len(w)))\nfor l in range(min_len, max_len + 1):\n for idx in buckets[l]:\n ... | <|body_start_0|>
seen, res = (set(''), '')
buckets = defaultdict(list)
min_len, max_len = (float('inf'), float('-inf'))
for idx, w in enumerate(words):
buckets[len(w)].append(idx)
min_len, max_len = (min(min_len, len(w)), max(max_len, len(w)))
for l in ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str"""
<|body_0|>
def longestWord2(self, words):
""":type words: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
seen, res = (set(''), '')
bucke... | stack_v2_sparse_classes_36k_train_005378 | 2,161 | no_license | [
{
"docstring": ":type words: List[str] :rtype: str",
"name": "longestWord1",
"signature": "def longestWord1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: str",
"name": "longestWord2",
"signature": "def longestWord2(self, words)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestWord1(self, words): :type words: List[str] :rtype: str
- def longestWord2(self, words): :type words: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestWord1(self, words): :type words: List[str] :rtype: str
- def longestWord2(self, words): :type words: List[str] :rtype: str
<|skeleton|>
class Solution:
def longe... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str"""
<|body_0|>
def longestWord2(self, words):
""":type words: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestWord1(self, words):
""":type words: List[str] :rtype: str"""
seen, res = (set(''), '')
buckets = defaultdict(list)
min_len, max_len = (float('inf'), float('-inf'))
for idx, w in enumerate(words):
buckets[len(w)].append(idx)
m... | the_stack_v2_python_sparse | Classify/HashTable/720#Longest Word in Dictionary.py | EachenKuang/LeetCode | train | 28 | |
59a07c7b024d3a75d5cae215ff24dcd6e074592d | [
"super(BasicBlock_fmd, self).__init__()\nself.name = block_type\nself.downsample = downsample\nself.bn1 = nn.BatchNorm2d(in_plane)\nself.relu1 = nn.ReLU(inplace=True)\nself.conv1 = conv3x3(in_plane, out_plane, stride)\nself.dropblock1 = LinearScheduler(FMDUnit(drop_prob=drop_prob, block_size=args.block_size, args=a... | <|body_start_0|>
super(BasicBlock_fmd, self).__init__()
self.name = block_type
self.downsample = downsample
self.bn1 = nn.BatchNorm2d(in_plane)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = conv3x3(in_plane, out_plane, stride)
self.dropblock1 = LinearScheduler(F... | Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :param downsample: down sample type for expand dimension of input feature maps, de... | BasicBlock_fmd | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock_fmd:
"""Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :param downsample: down sample type for ... | stack_v2_sparse_classes_36k_train_005379 | 9,962 | permissive | [
{
"docstring": "Init module and weights.",
"name": "__init__",
"signature": "def __init__(self, in_plane, out_plane, stride=1, downsample=None, args=None, drop_prob=0.1, block_type='both_preact')"
},
{
"docstring": "Forward procedure of residual module.",
"name": "forward",
"signature": ... | 2 | null | Implement the Python class `BasicBlock_fmd` described below.
Class description:
Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :... | Implement the Python class `BasicBlock_fmd` described below.
Class description:
Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class BasicBlock_fmd:
"""Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :param downsample: down sample type for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicBlock_fmd:
"""Base module for PreResNet on small data sets. :param in_plane: size of input plane :type in_plane: int :param out_plane: size of output plane :type out_plane: int :param stride: stride of convolutional layers, default 1 :type stride: int :param downsample: down sample type for expand dimens... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/benchmark/algs/fully_train/networks/resnet_cifar.py | Huawei-Ascend/modelzoo | train | 1 |
b7ce9a73bcbeb14a269f36ade5e12934cdf1b3c8 | [
"self.lines = [Pin(pin_name, Pin.OUT, value=True) for pin_name in lines]\nself.line_count = len(lines)\nself.cols = [Pin(pin_name, Pin.IN, Pin.PULL_UP) for pin_name in cols]\nself.col_count = len(cols)\nself.debounce_ms = debounce_ms\nself.last_release = time.ticks_ms()\nself.last_index = -1",
"r = []\nfor i in r... | <|body_start_0|>
self.lines = [Pin(pin_name, Pin.OUT, value=True) for pin_name in lines]
self.line_count = len(lines)
self.cols = [Pin(pin_name, Pin.IN, Pin.PULL_UP) for pin_name in cols]
self.col_count = len(cols)
self.debounce_ms = debounce_ms
self.last_release = time.t... | Class used to read Keypad Matrix | Keypad | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keypad:
"""Class used to read Keypad Matrix"""
def __init__(self, lines, cols, debounce_ms=300):
"""lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)"""
<|body_0|>
def scan(self):
"""Scan ... | stack_v2_sparse_classes_36k_train_005380 | 3,847 | no_license | [
{
"docstring": "lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)",
"name": "__init__",
"signature": "def __init__(self, lines, cols, debounce_ms=300)"
},
{
"docstring": "Scan all lines and read entries that are low. Retu... | 3 | stack_v2_sparse_classes_30k_train_017163 | Implement the Python class `Keypad` described below.
Class description:
Class used to read Keypad Matrix
Method signatures and docstrings:
- def __init__(self, lines, cols, debounce_ms=300): lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)
- ... | Implement the Python class `Keypad` described below.
Class description:
Class used to read Keypad Matrix
Method signatures and docstrings:
- def __init__(self, lines, cols, debounce_ms=300): lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)
- ... | 75184da49e8578315a26bc42d9c3816ae5d5afe8 | <|skeleton|>
class Keypad:
"""Class used to read Keypad Matrix"""
def __init__(self, lines, cols, debounce_ms=300):
"""lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)"""
<|body_0|>
def scan(self):
"""Scan ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keypad:
"""Class used to read Keypad Matrix"""
def __init__(self, lines, cols, debounce_ms=300):
"""lines : array of lines pins configured as OUPUT (from 1 to N) cols : array of columns pins configured as INPUT (from 1 to N)"""
self.lines = [Pin(pin_name, Pin.OUT, value=True) for pin_name... | the_stack_v2_python_sparse | keypad-4x4/lib/keypad.py | mchobby/esp8266-upy | train | 47 |
7b99b6cb00cf487a9158678ad18c27ba7050b526 | [
"need = defaultdict(int)\nwindow = defaultdict(int)\nfor c in s1:\n need[c] += 1\nleft, right = (0, 0)\nvalid = 0\nwhile right < len(s2):\n c = s2[right]\n right += 1\n if c in need:\n window[c] += 1\n if window[c] == need[c]:\n valid += 1\n while right - left >= len(s1):\n ... | <|body_start_0|>
need = defaultdict(int)
window = defaultdict(int)
for c in s1:
need[c] += 1
left, right = (0, 0)
valid = 0
while right < len(s2):
c = s2[right]
right += 1
if c in need:
window[c] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
need = defaultdict(i... | stack_v2_sparse_classes_36k_train_005381 | 3,498 | no_license | [
{
"docstring": "use the sliding window framework",
"name": "checkInclusionFramework",
"signature": "def checkInclusionFramework(self, s1, s2)"
},
{
"docstring": ":type s1: str :type s2: str :rtype: bool",
"name": "checkInclusion",
"signature": "def checkInclusion(self, s1, s2)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000356 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusionFramework(self, s1, s2): use the sliding window framework
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkInclusionFramework(self, s1, s2): use the sliding window framework
- def checkInclusion(self, s1, s2): :type s1: str :type s2: str :rtype: bool
<|skeleton|>
class Solut... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
<|body_0|>
def checkInclusion(self, s1, s2):
""":type s1: str :type s2: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkInclusionFramework(self, s1, s2):
"""use the sliding window framework"""
need = defaultdict(int)
window = defaultdict(int)
for c in s1:
need[c] += 1
left, right = (0, 0)
valid = 0
while right < len(s2):
c = s2[r... | the_stack_v2_python_sparse | P/PermutationInString.py | bssrdf/pyleet | train | 2 | |
e19366ba71fcf26deaf7d4f14b2c8de980ecb346 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AlterationResponse()",
"from .search_alteration import SearchAlteration\nfrom .search_alteration_type import SearchAlterationType\nfrom .search_alteration import SearchAlteration\nfrom .search_alteration_type import SearchAlterationTyp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AlterationResponse()
<|end_body_0|>
<|body_start_1|>
from .search_alteration import SearchAlteration
from .search_alteration_type import SearchAlterationType
from .search_alterat... | AlterationResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""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 obje... | stack_v2_sparse_classes_36k_train_005382 | 3,610 | 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: AlterationResponse",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `AlterationResponse` described below.
Class description:
Implement the AlterationResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse: Creates a new instance of the appropriate class based on disc... | Implement the Python class `AlterationResponse` described below.
Class description:
Implement the AlterationResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""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 obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""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: Al... | the_stack_v2_python_sparse | msgraph/generated/models/alteration_response.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
36bd06ee5a4e59df390b374e4e4d2e7584a4b56c | [
"super(PILCOAlgorithm, self).__init__(model, observed, extra_graphs=extra_graphs)\nself.cost_function = cost_function\nself.policy = policy\nself.initial_state_generator = initial_state_generator\nself.n_time_steps = n_time_steps\nself.num_samples = num_samples\nself.dtype = dtype if dtype is not None else get_defa... | <|body_start_0|>
super(PILCOAlgorithm, self).__init__(model, observed, extra_graphs=extra_graphs)
self.cost_function = cost_function
self.policy = policy
self.initial_state_generator = initial_state_generator
self.n_time_steps = n_time_steps
self.num_samples = num_samples... | Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of samples used in estimating the variational ... | PILCOAlgorithm | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of s... | stack_v2_sparse_classes_36k_train_005383 | 4,512 | permissive | [
{
"docstring": ":param model: The model to use to generate the next state from a state/action pair. :param observed: Observed variables for the model. :param cost_function: The cost function to evaluate state/action pairs on. :param policy: The policy function to determine what action to take next from a partic... | 2 | stack_v2_sparse_classes_30k_train_013258 | Implement the Python class `PILCOAlgorithm` described below.
Class description:
Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variab... | Implement the Python class `PILCOAlgorithm` described below.
Class description:
Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variab... | af6223e9636b055d029d136dd7ae023b210b4560 | <|skeleton|>
class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PILCOAlgorithm:
"""Sampling-based inference algorithm that returns the expectation of each variable in the model. :param model: the definition of the probabilistic model :type model: Model :param observed: A list of observed variables :type observed: [Variable] :param num_samples: the number of samples used i... | the_stack_v2_python_sparse | mxfusion/inference/pilco_alg.py | amzn/MXFusion | train | 109 |
a1bbb2b22f7c38bbe358a7cbf3c5c2360dd99cc4 | [
"if not self.platform:\n width, height = self.getViewPort()\n if width == 0 or height == 0:\n aspect = 1.0\n else:\n aspect = float(width) / float(height)\n self.platform = viewplatform.ViewPlatform(position=self.initialPosition, orientation=self.initialOrientation, aspect=aspect)\nreturn ... | <|body_start_0|>
if not self.platform:
width, height = self.getViewPort()
if width == 0 or height == 0:
aspect = 1.0
else:
aspect = float(width) / float(height)
self.platform = viewplatform.ViewPlatform(position=self.initialPosition... | Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for instantiating and using these objects. In particular, it overrides the Viewpoint cus... | ViewPlatformMixin | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewPlatformMixin:
"""Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for instantiating and using these objects. ... | stack_v2_sparse_classes_36k_train_005384 | 5,184 | permissive | [
{
"docstring": "Customization Point: Instantiate ViewPlatform for this context The default implementation is to instantiate a viewplatform.ViewPlatform with position equal to self.initialPosition and orientation equal to self.initialOrientation. See: OpenGLContext.shadow.shadowcontext for example where this met... | 4 | null | Implement the Python class `ViewPlatformMixin` described below.
Class description:
Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for ... | Implement the Python class `ViewPlatformMixin` described below.
Class description:
Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for ... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class ViewPlatformMixin:
"""Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for instantiating and using these objects. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewPlatformMixin:
"""Mix-in for Context classes providing ViewPlatform support The viewplatform module provides a ViewPlatform object which provides generic "camera" support for OpenGLContext. This mix-in provides Context classes with automatic support for instantiating and using these objects. In particular... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/move/viewplatformmixin.py | alexus37/AugmentedRealityChess | train | 1 |
1355d8e5fb49031ac6ab52459aaaa445917f45dd | [
"self.login()\nresponse = self.client.get(self.target_url)\nactual = response.resolver_match.func.__name__\nexpected = MedidaListView.as_view().__name__\nself.assertEqual(actual, expected, 'La vista de listado de medidas no es MedidaListView')",
"login_url = reverse('login')\nresponse = self.client.get(self.targe... | <|body_start_0|>
self.login()
response = self.client.get(self.target_url)
actual = response.resolver_match.func.__name__
expected = MedidaListView.as_view().__name__
self.assertEqual(actual, expected, 'La vista de listado de medidas no es MedidaListView')
<|end_body_0|>
<|body_s... | Pruebas para la vista de listado de medidas | MedidaListViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
<|body_0|>
def test_login_required(self):
"""Prueba que la vista sea solame... | stack_v2_sparse_classes_36k_train_005385 | 7,967 | no_license | [
{
"docstring": "Prueba que el url de listado de medidas use la vista MedidaListView",
"name": "test_url_view_correspondence",
"signature": "def test_url_view_correspondence(self)"
},
{
"docstring": "Prueba que la vista sea solamente accedible por usuarios autenticados",
"name": "test_login_r... | 4 | null | Implement the Python class `MedidaListViewTestCase` described below.
Class description:
Pruebas para la vista de listado de medidas
Method signatures and docstrings:
- def test_url_view_correspondence(self): Prueba que el url de listado de medidas use la vista MedidaListView
- def test_login_required(self): Prueba qu... | Implement the Python class `MedidaListViewTestCase` described below.
Class description:
Pruebas para la vista de listado de medidas
Method signatures and docstrings:
- def test_url_view_correspondence(self): Prueba que el url de listado de medidas use la vista MedidaListView
- def test_login_required(self): Prueba qu... | 64a8f8350f9092126864f3676f27dc690ed2a5f8 | <|skeleton|>
class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
<|body_0|>
def test_login_required(self):
"""Prueba que la vista sea solame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
self.login()
response = self.client.get(self.target_url)
actual = response.resolver_m... | the_stack_v2_python_sparse | medidas/test_views.py | german1608/EIA_CI4712 | train | 1 |
d9b5decd97ff8ac41d88a1f2c695e53f488fa8a6 | [
"self.__size = size\nself.__sum = 0\nself.__q = deque([])",
"if len(self.__q) == self.__size:\n self.__sum -= self.__q.popleft()\nself.__sum += val\nself.__q.append(val)\nreturn 1.0 * self.__sum / len(self.__q)"
] | <|body_start_0|>
self.__size = size
self.__sum = 0
self.__q = deque([])
<|end_body_0|>
<|body_start_1|>
if len(self.__q) == self.__size:
self.__sum -= self.__q.popleft()
self.__sum += val
self.__q.append(val)
return 1.0 * self.__sum / len(self.__q)
<|... | MovingAverage | [
"Apache-2.0"
] | 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.__sum... | stack_v2_sparse_classes_36k_train_005386 | 2,640 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | 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:
... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|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.__sum = 0
self.__q = deque([])
def next(self, val):
""":type val: int :rtype: float"""
if len(self.__q) == self.__size:
s... | the_stack_v2_python_sparse | cs15211/MovingAverageFromDataStream.py | JulyKikuAkita/PythonPrac | train | 1 | |
6eddb41f6f0e081a43c3adb26d283008e5fd2610 | [
"with tables(db.engine, 'user_comments') as (con, comments):\n q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))\n return [dict(c) for c in q.execute().fetchall()]",
"with tables(db.engine, 'user_comments') as (con, comments):\n q = comments.insert().values(vcf_id=ru... | <|body_start_0|>
with tables(db.engine, 'user_comments') as (con, comments):
q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))
return [dict(c) for c in q.execute().fetchall()]
<|end_body_0|>
<|body_start_1|>
with tables(db.engine, 'user_comm... | CommentList | [
"Apache-2.0",
"CC-BY-3.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
<|body_0|>
def post(self, run_id):
"""Create a comment."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with tables(db.engine, 'user_comments') as (con, comments):
q =... | stack_v2_sparse_classes_36k_train_005387 | 8,737 | permissive | [
{
"docstring": "Get a list of all comments.",
"name": "get",
"signature": "def get(self, run_id)"
},
{
"docstring": "Create a comment.",
"name": "post",
"signature": "def post(self, run_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021209 | Implement the Python class `CommentList` described below.
Class description:
Implement the CommentList class.
Method signatures and docstrings:
- def get(self, run_id): Get a list of all comments.
- def post(self, run_id): Create a comment. | Implement the Python class `CommentList` described below.
Class description:
Implement the CommentList class.
Method signatures and docstrings:
- def get(self, run_id): Get a list of all comments.
- def post(self, run_id): Create a comment.
<|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a... | a436c4fc212e4429fb5196a9a4d36c37bd050c52 | <|skeleton|>
class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
<|body_0|>
def post(self, run_id):
"""Create a comment."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentList:
def get(self, run_id):
"""Get a list of all comments."""
with tables(db.engine, 'user_comments') as (con, comments):
q = select(comments.c).where(comments.c.vcf_id == run_id).order_by(desc(comments.c.id))
return [dict(c) for c in q.execute().fetchall()]
... | the_stack_v2_python_sparse | cycledash/api/comments.py | haoziyeung/cycledash | train | 0 | |
b69b381a3671847a133a418d8b950dd064427f51 | [
"if stream is not None:\n self.stream = stream\nelse:\n self.stream = StringIO()",
"write = self.stream.write\ntptypes = getToolByName(target, 'portal_types', None)\nif tptypes is None:\n write('No portal_skins')\nelif not tptypes.getTypeInfo(type_name):\n tptypes.addType(type_name, fti[0])\n write... | <|body_start_0|>
if stream is not None:
self.stream = stream
else:
self.stream = StringIO()
<|end_body_0|>
<|body_start_1|>
write = self.stream.write
tptypes = getToolByName(target, 'portal_types', None)
if tptypes is None:
write('No portal_sk... | A suite of methods deploying CMF site | ManageCMFContent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageCMFContent:
"""A suite of methods deploying CMF site"""
def __init__(self, stream=None):
"""Stream is expected to be some writable file object, like a StringIO, that output will be sent to"""
<|body_0|>
def deploy_class(self, target, type_name, fti):
"""Reg... | stack_v2_sparse_classes_36k_train_005388 | 3,370 | no_license | [
{
"docstring": "Stream is expected to be some writable file object, like a StringIO, that output will be sent to",
"name": "__init__",
"signature": "def __init__(self, stream=None)"
},
{
"docstring": "Register a new type",
"name": "deploy_class",
"signature": "def deploy_class(self, targ... | 4 | stack_v2_sparse_classes_30k_test_000249 | Implement the Python class `ManageCMFContent` described below.
Class description:
A suite of methods deploying CMF site
Method signatures and docstrings:
- def __init__(self, stream=None): Stream is expected to be some writable file object, like a StringIO, that output will be sent to
- def deploy_class(self, target,... | Implement the Python class `ManageCMFContent` described below.
Class description:
A suite of methods deploying CMF site
Method signatures and docstrings:
- def __init__(self, stream=None): Stream is expected to be some writable file object, like a StringIO, that output will be sent to
- def deploy_class(self, target,... | bdf3ad7c1ec4bcdec08000bf4ac5315ca6a0ad19 | <|skeleton|>
class ManageCMFContent:
"""A suite of methods deploying CMF site"""
def __init__(self, stream=None):
"""Stream is expected to be some writable file object, like a StringIO, that output will be sent to"""
<|body_0|>
def deploy_class(self, target, type_name, fti):
"""Reg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageCMFContent:
"""A suite of methods deploying CMF site"""
def __init__(self, stream=None):
"""Stream is expected to be some writable file object, like a StringIO, that output will be sent to"""
if stream is not None:
self.stream = stream
else:
self.stre... | the_stack_v2_python_sparse | ExpressSuiteTools/ManageCMFContent.py | ichar/Express-Suite-DMS | train | 0 |
058c066f7261d3affd1b42b068472f55dd8489aa | [
"x0, y0 = pos\nx1, x2 = (x0 - length / 2.0, x0 + length / 2.0)\ny1, y2 = (y0 - height, y0)\nself.cv = cv\nself.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)",
"x1, y1, x2, y2 = self.cv.coords(self.item)\nx0, y0 = ((x1 + x2) / 2, y2)\ndx, dy = (x - x0, y - y0)\nd = (dx ** 2 + dy ** 2) *... | <|body_start_0|>
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
self.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)
<|end_body_0|>
<|body_start_1|>
x1, y1, x2, y2 = self.cv.coords(self.item)... | Movable Rectangle on a Tkinter Canvas | Disc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is i... | stack_v2_sparse_classes_36k_train_005389 | 11,212 | no_license | [
{
"docstring": "creates disc on given Canvas cv at given pos-ition",
"name": "__init__",
"signature": "def __init__(self, cv, pos, length, height, colour)"
},
{
"docstring": "moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10",
"name": "move_to",
... | 2 | stack_v2_sparse_classes_30k_train_001960 | Implement the Python class `Disc` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given pos-ition
- def move_to(self, x, y, speed): moves bottom center of disc to posit... | Implement the Python class `Disc` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given pos-ition
- def move_to(self, x, y, speed): moves bottom center of disc to posit... | eba9cc094f28ec7e26cbd85b1a42d3dccb560233 | <|skeleton|>
class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Disc:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given pos-ition"""
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
... | the_stack_v2_python_sparse | src/Unisa/Exemplos de programas em Python/hanoi.py | carlosDevPinheiro/Python | train | 0 |
c2b33c3ac0039fdfa820f0eda8b5b2975c5975c4 | [
"self.food = deque(food)\nself.width = width\nself.height = height\nself.bodyQueue = deque([(0, 0)])\nself.hashSet = set([(0, 0)])\nself.score = 0\nself.moveOps = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}",
"s = self.hashSet\nq = self.bodyQueue\nops = self.moveOps\nwidth = self.width\nheight = self.h... | <|body_start_0|>
self.food = deque(food)
self.width = width
self.height = height
self.bodyQueue = deque([(0, 0)])
self.hashSet = set([(0, 0)])
self.score = 0
self.moveOps = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
<|end_body_0|>
<|body_start_1|>
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_005390 | 1,997 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_004722 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 00bf9a8164008aa17507b1c87ce72a3374bcb7b9 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | solutions/353.design-snake-game.py | quixoteji/Leetcode | train | 1 | |
ff51308d8e2744fabb5bd7cfe8dadd167640afb1 | [
"super(ResBlk, self).__init__()\nself.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(ch_out)\nself.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(ch_out)\nself.extra = nn.Sequential()\nif ch_out != ch_in:\n self.ex... | <|body_start_0|>
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
self.ex... | resnet block | ResBlk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResBlk, self).__init__()
... | stack_v2_sparse_classes_36k_train_005391 | 2,694 | no_license | [
{
"docstring": ":param ch_in: :param ch_out:",
"name": "__init__",
"signature": "def __init__(self, ch_in, ch_out)"
},
{
"docstring": ":param x: [b, ch, h, w] :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017246 | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return: | Implement the Python class `ResBlk` described below.
Class description:
resnet block
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: [b, ch, h, w] :return:
<|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, c... | d3e44fad42809f23762c9028d8b1d478acf42ab2 | <|skeleton|>
class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: [b, ch, h, w] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResBlk:
"""resnet block"""
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out... | the_stack_v2_python_sparse | modules/performance/core/custom_resnet.py | CaravanPassenger/pytorch-learning-notes | train | 0 |
d5531759c80f209679425418b0f54e56d9709114 | [
"path_sum += triangle[x][y]\nif x == len(triangle) - 1:\n self.res = min(path_sum, self.res)\nelse:\n self.traversal(triangle, x + 1, y, path_sum)\n self.traversal(triangle, x + 1, y + 1, path_sum)",
"self.res = sys.maxsize\nself.traversal(triangle, 0, 0, 0)\nreturn self.res"
] | <|body_start_0|>
path_sum += triangle[x][y]
if x == len(triangle) - 1:
self.res = min(path_sum, self.res)
else:
self.traversal(triangle, x + 1, y, path_sum)
self.traversal(triangle, x + 1, y + 1, path_sum)
<|end_body_0|>
<|body_start_1|>
self.res = sy... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
<|body_0|>
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_005392 | 7,199 | no_license | [
{
"docstring": ":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:",
"name": "traversal",
"signature": "def traversal(self, triangle, x, y, path_sum)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal"... | 2 | stack_v2_sparse_classes_30k_train_021249 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def traversal(self, triangle, x, y, path_sum): :param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:
- def minimumTotal(self, t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def traversal(self, triangle, x, y, path_sum): :param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:
- def minimumTotal(self, t... | bfd16678f179bbfc7564bfc079d2fa4b3e554be6 | <|skeleton|>
class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
<|body_0|>
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
path_sum += triangle[x][y]
if x == len(triangle) - 1:
self.res = min(path_sum, self.res)
else:
... | the_stack_v2_python_sparse | DP/triangle.py | HeliWang/upstream | train | 0 | |
28708a47d6195ef96da18de0f21b4648cc056c8f | [
"super(TransformerTranslator, self).__init__()\nassert hidden_dim % num_heads == 0\nself.num_heads = num_heads\nself.word_embedding_dim = hidden_dim\nself.hidden_dim = hidden_dim\nself.dim_feedforward = dim_feedforward\nself.max_length = max_length\nself.input_size = input_size\nself.output_size = output_size\nself... | <|body_start_0|>
super(TransformerTranslator, self).__init__()
assert hidden_dim % num_heads == 0
self.num_heads = num_heads
self.word_embedding_dim = hidden_dim
self.hidden_dim = hidden_dim
self.dim_feedforward = dim_feedforward
self.max_length = max_length
... | A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, and operates on minibatches of size N. | TransformerTranslator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerTranslator:
"""A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, and operates on minibatches of size N."""... | stack_v2_sparse_classes_36k_train_005393 | 5,562 | no_license | [
{
"docstring": ":param input_size: the size of the input, which equals to the number of words in source language vocabulary :param output_size: the size of the output, which equals to the number of words in target language vocabulary :param hidden_dim: the dimensionality of the output embeddings that go into th... | 6 | stack_v2_sparse_classes_30k_train_017038 | Implement the Python class `TransformerTranslator` described below.
Class description:
A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, an... | Implement the Python class `TransformerTranslator` described below.
Class description:
A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, an... | 9463299e76ee200518e1448fdaf518339d773238 | <|skeleton|>
class TransformerTranslator:
"""A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, and operates on minibatches of size N."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerTranslator:
"""A single-layer Transformer which encodes a sequence of text and performs binary classification. The model has a vocab size of V, works on sequences of length T, has an hidden dimension of H, uses word vectors also of dimension H, and operates on minibatches of size N."""
def __i... | the_stack_v2_python_sparse | RNN_LSTM_Seq2Seq_and_Transformers/models/Transformer.py | jiani556/Deep-Learning | train | 0 |
782735a0835dd1b5af0b782932155f727ddd16af | [
"processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid='2016091200490210', app_notify_url='http://115.159.122.64:8000/alipay/return/', app_private_key_path=private_key_path, alipay_public_key_path=ali_pub_key_path... | <|body_start_0|>
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid='2016091200490210', app_notify_url='http://115.159.122.64:8000/alipay/return/', app_private_key_path=private_k... | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
<|body_0|>
def post(self, request):
"""Handling Alipay's notify_url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processed_dict = {}
for key, value in request.GET... | stack_v2_sparse_classes_36k_train_005394 | 7,420 | no_license | [
{
"docstring": "Handle Alipay's return_url return",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Handling Alipay's notify_url",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): Handle Alipay's return_url return
- def post(self, request): Handling Alipay's notify_url | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): Handle Alipay's return_url return
- def post(self, request): Handling Alipay's notify_url
<|skeleton|>
class AlipayView:
def get(self, request):... | 97f48a2a117a52d21143a440e546e2d894ba9244 | <|skeleton|>
class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
<|body_0|>
def post(self, request):
"""Handling Alipay's notify_url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlipayView:
def get(self, request):
"""Handle Alipay's return_url return"""
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid='2016091200490210', app_notify_ur... | the_stack_v2_python_sparse | apps/orders/views.py | muskanmahajan37/agrowdev_api | train | 0 | |
17a62e601443c5ef8b4a70f41f263457704ff5a3 | [
"length = len(nums)\nzero = [0] * length\ncur = 0\nfor index, num in enumerate(nums):\n if num == 0:\n cur += 1\n else:\n zero[index] = cur\nfor index, num in enumerate(nums):\n if num != 0:\n num[index - zero[index]] = num\nfor i in range(cur):\n nums[length - i] = 0",
"length = ... | <|body_start_0|>
length = len(nums)
zero = [0] * length
cur = 0
for index, num in enumerate(nums):
if num == 0:
cur += 1
else:
zero[index] = cur
for index, num in enumerate(nums):
if num != 0:
num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_005395 | 1,110 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "moveZeroes1",
"signature": "def moveZeroes1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_019891 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes1(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes(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 moveZeroes1(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums): :type nums: List[int] :rtype: ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def moveZeroes1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes1(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
length = len(nums)
zero = [0] * length
cur = 0
for index, num in enumerate(nums):
if num == 0:
cur += 1
... | the_stack_v2_python_sparse | python/leetcode_bak/283_Move_Zeroes.py | bobcaoge/my-code | train | 0 | |
e6164e470ea8b3e7fb60a21db9dd465ee5738e07 | [
"miner = Miner.objects.create(name='Some Miner', version='1.0.0')\nwith self.assertRaises(ValidationError):\n request = Request(name='Some Request', request='invalid json', miner=miner)\n request.full_clean()\n request.save()",
"miner = Miner.objects.create(name='Some Miner', version='1.0.0')\nrequest = ... | <|body_start_0|>
miner = Miner.objects.create(name='Some Miner', version='1.0.0')
with self.assertRaises(ValidationError):
request = Request(name='Some Request', request='invalid json', miner=miner)
request.full_clean()
request.save()
<|end_body_0|>
<|body_start_1|>
... | Тестирование валидатора json | JsonValidatorTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonValidatorTest:
"""Тестирование валидатора json"""
def test_validate_invalid_json(self):
"""Тестирование invalid json"""
<|body_0|>
def test_validate_valid_json(self):
"""Тестирование valid json"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005396 | 13,105 | permissive | [
{
"docstring": "Тестирование invalid json",
"name": "test_validate_invalid_json",
"signature": "def test_validate_invalid_json(self)"
},
{
"docstring": "Тестирование valid json",
"name": "test_validate_valid_json",
"signature": "def test_validate_valid_json(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019592 | Implement the Python class `JsonValidatorTest` described below.
Class description:
Тестирование валидатора json
Method signatures and docstrings:
- def test_validate_invalid_json(self): Тестирование invalid json
- def test_validate_valid_json(self): Тестирование valid json | Implement the Python class `JsonValidatorTest` described below.
Class description:
Тестирование валидатора json
Method signatures and docstrings:
- def test_validate_invalid_json(self): Тестирование invalid json
- def test_validate_valid_json(self): Тестирование valid json
<|skeleton|>
class JsonValidatorTest:
"... | d173f1bee44d0752eefb53b1a0da847a3882a352 | <|skeleton|>
class JsonValidatorTest:
"""Тестирование валидатора json"""
def test_validate_invalid_json(self):
"""Тестирование invalid json"""
<|body_0|>
def test_validate_valid_json(self):
"""Тестирование valid json"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonValidatorTest:
"""Тестирование валидатора json"""
def test_validate_invalid_json(self):
"""Тестирование invalid json"""
miner = Miner.objects.create(name='Some Miner', version='1.0.0')
with self.assertRaises(ValidationError):
request = Request(name='Some Request', ... | the_stack_v2_python_sparse | miningstatistic/core/tests.py | crowmurk/miners | train | 0 |
8353ae1289096f301e0dd287b965a69eff127320 | [
"auctioneer = Auctioneer()\n[auctioneer.register_bidder(x) for x in bidders]\nself._auctioneer = auctioneer",
"print('Auctioning ' + item + ' starting at ' + str(start_price))\nself._auctioneer.accept_bid(start_price, None)\nwinner = self._auctioneer.get_highest_bidder()\nfinal_price = self._auctioneer.get_highes... | <|body_start_0|>
auctioneer = Auctioneer()
[auctioneer.register_bidder(x) for x in bidders]
self._auctioneer = auctioneer
<|end_body_0|>
<|body_start_1|>
print('Auctioning ' + item + ' starting at ' + str(start_price))
self._auctioneer.accept_bid(start_price, None)
winne... | Simulates an auction. Is responsible for driving the auctioneer and the bidders. | Auction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_36k_train_005397 | 5,374 | no_license | [
{
"docstring": "Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder",
"name": "__init__",
"signature": "def __init__(self, bidders)"
},
{
"docstring": "Starts the auction for the given item at the g... | 2 | null | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | Implement the Python class `Auction` described below.
Class description:
Simulates an auction. Is responsible for driving the auctioneer and the bidders.
Method signatures and docstrings:
- def __init__(self, bidders): Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :para... | 46441744be7773075f5f91c09c1032e9fc0a54e8 | <|skeleton|>
class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Auction:
"""Simulates an auction. Is responsible for driving the auctioneer and the bidders."""
def __init__(self, bidders):
"""Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder"""
auctione... | the_stack_v2_python_sparse | Labs/Lab6/auction_simulator.py | Xaitin/3522_A01053901 | train | 0 |
00d29ece7956092f851a618109135ab23461c543 | [
"if not self.named_regexp:\n self.log.warning('Regular expression not provided for plugin. Run with `--help-all` flag for more information.')\n return None\nmatch = re.match(self.named_regexp, filename)\nif not match or not match.groups():\n self.log.warning(\"Regular expression '{}' did not match anything... | <|body_start_0|>
if not self.named_regexp:
self.log.warning('Regular expression not provided for plugin. Run with `--help-all` flag for more information.')
return None
match = re.match(self.named_regexp, filename)
if not match or not match.groups():
self.log.w... | Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class. | FileNameCollectorPlugin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileNameCollectorPlugin:
"""Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class."""
def _match(self, filename: str) -> Optional[dict]:
"""Match the named group regular expression to t... | stack_v2_sparse_classes_36k_train_005398 | 7,151 | permissive | [
{
"docstring": "Match the named group regular expression to the beginning of the filename and return the match groupdict or None if no match.",
"name": "_match",
"signature": "def _match(self, filename: str) -> Optional[dict]"
},
{
"docstring": "This is the main function called by the :class:`~n... | 2 | stack_v2_sparse_classes_30k_train_013784 | Implement the Python class `FileNameCollectorPlugin` described below.
Class description:
Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class.
Method signatures and docstrings:
- def _match(self, filename: str) -> Opti... | Implement the Python class `FileNameCollectorPlugin` described below.
Class description:
Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class.
Method signatures and docstrings:
- def _match(self, filename: str) -> Opti... | 6db380039dab377157620516ae49eafcf7537fc8 | <|skeleton|>
class FileNameCollectorPlugin:
"""Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class."""
def _match(self, filename: str) -> Optional[dict]:
"""Match the named group regular expression to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileNameCollectorPlugin:
"""Submission filename collector plugin for the :class:`~nbgrader.apps.zipcollectapp.ZipCollectApp`. Collect plugin subclasses MUST inherit from this class."""
def _match(self, filename: str) -> Optional[dict]:
"""Match the named group regular expression to the beginning ... | the_stack_v2_python_sparse | nbgrader/plugins/zipcollect.py | jupyter/nbgrader | train | 1,274 |
8bf923fc7b06cb6ca3be44c362359925d3a6258d | [
"if self.style == StyleChoices.Basic and self.layout == LayoutChoices.Basic:\n return VisualStyleChoices.Basic\nelif self.style == StyleChoices.Basic and self.layout == LayoutChoices.Enhanced:\n return VisualStyleChoices.Edgy\nelif self.style == StyleChoices.Enhanced and self.layout == LayoutChoices.Basic:\n ... | <|body_start_0|>
if self.style == StyleChoices.Basic and self.layout == LayoutChoices.Basic:
return VisualStyleChoices.Basic
elif self.style == StyleChoices.Basic and self.layout == LayoutChoices.Enhanced:
return VisualStyleChoices.Edgy
elif self.style == StyleChoices.Enh... | Slide | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slide:
def visualStyle(self):
"""Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers."""
<|body_0|>
def zeptoNum():
"""Method to get default value for zeptoId."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_005399 | 3,743 | no_license | [
{
"docstring": "Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers.",
"name": "visualStyle",
"signature": "def visualStyle(self)"
},
{
"docstring": "Method to get default value for zeptoId.",
"name": "zeptoNum",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_019090 | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def visualStyle(self): Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers.
- def zeptoNum(): Method to get default value for z... | Implement the Python class `Slide` described below.
Class description:
Implement the Slide class.
Method signatures and docstrings:
- def visualStyle(self): Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers.
- def zeptoNum(): Method to get default value for z... | 0849b1f86de63836801b63cc90b5dbb49b1d2a23 | <|skeleton|>
class Slide:
def visualStyle(self):
"""Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers."""
<|body_0|>
def zeptoNum():
"""Method to get default value for zeptoId."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Slide:
def visualStyle(self):
"""Visual style is a derived attribute of a slide. Defined as a property, so that it is availble to serializers."""
if self.style == StyleChoices.Basic and self.layout == LayoutChoices.Basic:
return VisualStyleChoices.Basic
elif self.style == S... | the_stack_v2_python_sparse | src/ZenCentral/SlideDB/models.py | prashant-labglo/test-repo | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.