blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
69f12016b032b5b57d57f0c902888a282052f597 | [
"g_criterion = gtn.Graph(False)\nL = len(target)\nS = 2 * L + 1\nfor s in range(S):\n idx = (s - 1) // 2\n g_criterion.add_node(s == 0, s == S - 1 or s == S - 2)\n label = target[idx] if s % 2 else blank_idx\n g_criterion.add_arc(s, s, label)\n if s > 0:\n g_criterion.add_arc(s - 1, s, label)\... | <|body_start_0|>
g_criterion = gtn.Graph(False)
L = len(target)
S = 2 * L + 1
for s in range(S):
idx = (s - 1) // 2
g_criterion.add_node(s == 0, s == S - 1 or s == S - 2)
label = target[idx] if s % 2 else blank_idx
g_criterion.add_arc(s, s,... | GTN CTC module. | GTNCTCLossFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_75kplus_train_065200 | 3,974 | permissive | [
{
"docstring": "Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph",
"name": "create_ctc_graph",
"signature": "def create_ctc_graph(target, blank_idx)"
},
{
"docstring": "Forward computati... | 3 | stack_v2_sparse_classes_30k_train_044466 | Implement the Python class `GTNCTCLossFunction` described below.
Class description:
GTN CTC module.
Method signatures and docstrings:
- def create_ctc_graph(target, blank_idx): Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence ... | Implement the Python class `GTNCTCLossFunction` described below.
Class description:
GTN CTC module.
Method signatures and docstrings:
- def create_ctc_graph(target, blank_idx): Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence ... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GTNCTCLossFunction:
"""GTN CTC module."""
def create_ctc_graph(target, blank_idx):
"""Build gtn graph. :param list target: single target sequence :param int blank_idx: index of blank token :return: gtn graph of target sequence :rtype: gtn.Graph"""
g_criterion = gtn.Graph(False)
L ... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/gtn_ctc.py | espnet/espnet | train | 7,242 |
cb3bf498d2568303381be6f17405925c6dbafca5 | [
"coupon_ids = uniquify_sequence(coupon_ids)\nif presorted:\n sorted_coupon_ids = coupon_ids\nelse:\n sorted_coupon_ids = self.sort_coupon_ids(coupon_ids)\ncoupons = Coupon.objects.filter(id__in=sorted_coupon_ids).select_related('coupon_type', 'offer', 'offer__business')\nsorted_coupons_ = sorted_coupon_ids[:]... | <|body_start_0|>
coupon_ids = uniquify_sequence(coupon_ids)
if presorted:
sorted_coupon_ids = coupon_ids
else:
sorted_coupon_ids = self.sort_coupon_ids(coupon_ids)
coupons = Coupon.objects.filter(id__in=sorted_coupon_ids).select_related('coupon_type', 'offer', 'of... | Class that helps sort coupons. | SortCoupons | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SortCoupons:
"""Class that helps sort coupons."""
def sorted_coupons(self, coupon_ids, presorted=False):
"""Convert a list of coupon ids to an ordered list of coupon instances."""
<|body_0|>
def sort_coupon_ids(coupon_ids):
"""Return the given coupons_ids ranked ... | stack_v2_sparse_classes_75kplus_train_065201 | 8,602 | no_license | [
{
"docstring": "Convert a list of coupon ids to an ordered list of coupon instances.",
"name": "sorted_coupons",
"signature": "def sorted_coupons(self, coupon_ids, presorted=False)"
},
{
"docstring": "Return the given coupons_ids ranked using the following preference: 1) Coupons created today, n... | 2 | stack_v2_sparse_classes_30k_train_053196 | Implement the Python class `SortCoupons` described below.
Class description:
Class that helps sort coupons.
Method signatures and docstrings:
- def sorted_coupons(self, coupon_ids, presorted=False): Convert a list of coupon ids to an ordered list of coupon instances.
- def sort_coupon_ids(coupon_ids): Return the give... | Implement the Python class `SortCoupons` described below.
Class description:
Class that helps sort coupons.
Method signatures and docstrings:
- def sorted_coupons(self, coupon_ids, presorted=False): Convert a list of coupon ids to an ordered list of coupon instances.
- def sort_coupon_ids(coupon_ids): Return the give... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class SortCoupons:
"""Class that helps sort coupons."""
def sorted_coupons(self, coupon_ids, presorted=False):
"""Convert a list of coupon ids to an ordered list of coupon instances."""
<|body_0|>
def sort_coupon_ids(coupon_ids):
"""Return the given coupons_ids ranked ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SortCoupons:
"""Class that helps sort coupons."""
def sorted_coupons(self, coupon_ids, presorted=False):
"""Convert a list of coupon ids to an ordered list of coupon instances."""
coupon_ids = uniquify_sequence(coupon_ids)
if presorted:
sorted_coupon_ids = coupon_ids
... | the_stack_v2_python_sparse | coupon/service/coupons_service.py | wcirillo/ten | train | 0 |
87092991e9e2ba8e66656983a1ba2e3f3f6e54cf | [
"self.capacity = capacity\nself.root = ListNode(0, 0)\nself.tail = ListNode(0, 0)\nself.root.next = self.tail\nself.tail.pre = self.root\nself.table = {}\nself.cnt = 0",
"if key in self.table:\n self.table[key].pre.next = self.table[key].next\n self.table[key].next.pre = self.table[key].pre\n self.table[... | <|body_start_0|>
self.capacity = capacity
self.root = ListNode(0, 0)
self.tail = ListNode(0, 0)
self.root.next = self.tail
self.tail.pre = self.root
self.table = {}
self.cnt = 0
<|end_body_0|>
<|body_start_1|>
if key in self.table:
self.table[... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_065202 | 1,949 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_016300 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.root = ListNode(0, 0)
self.tail = ListNode(0, 0)
self.root.next = self.tail
self.tail.pre = self.root
self.table = {}
self.cnt = 0
def get(self, ... | the_stack_v2_python_sparse | leetcode/hard/LRU_cache.py | SuperMartinYang/learning_algorithm | train | 0 | |
a8d4677a2ee231590d9c8d9eeb71f4ef8a159748 | [
"url = 'http://third.payment.com'\ndata = {'card_num': card_num, 'amount': amount}\nself.response = requests.post(url, data=data)\nreturn self.response.status_code",
"try:\n status_code = self.auth(card_num, amount)\nexcept TimeoutError:\n status_code = self.auth(card_num, amount)\nif status_code == 200:\n ... | <|body_start_0|>
url = 'http://third.payment.com'
data = {'card_num': card_num, 'amount': amount}
self.response = requests.post(url, data=data)
return self.response.status_code
<|end_body_0|>
<|body_start_1|>
try:
status_code = self.auth(card_num, amount)
exc... | 定义第三方支付类 | Payment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Payment:
"""定义第三方支付类"""
def auth(self, card_num, amount):
"""请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败"""
<|body_0|>
def pay(self, user_id, card_num, amount):
"""支付 :param user_id: :param card_num: :param amount: :r... | stack_v2_sparse_classes_75kplus_train_065203 | 1,178 | no_license | [
{
"docstring": "请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败",
"name": "auth",
"signature": "def auth(self, card_num, amount)"
},
{
"docstring": "支付 :param user_id: :param card_num: :param amount: :return:",
"name": "pay",
"signature": "def pa... | 2 | stack_v2_sparse_classes_30k_train_023241 | Implement the Python class `Payment` described below.
Class description:
定义第三方支付类
Method signatures and docstrings:
- def auth(self, card_num, amount): 请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败
- def pay(self, user_id, card_num, amount): 支付 :param user_id: :param card_n... | Implement the Python class `Payment` described below.
Class description:
定义第三方支付类
Method signatures and docstrings:
- def auth(self, card_num, amount): 请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败
- def pay(self, user_id, card_num, amount): 支付 :param user_id: :param card_n... | c8bd6d284499ac205b772280d3a347a888c80d17 | <|skeleton|>
class Payment:
"""定义第三方支付类"""
def auth(self, card_num, amount):
"""请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败"""
<|body_0|>
def pay(self, user_id, card_num, amount):
"""支付 :param user_id: :param card_num: :param amount: :r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Payment:
"""定义第三方支付类"""
def auth(self, card_num, amount):
"""请求第三方支付接口,并返回响应码 :param card_num: 卡号 :param amount: 金额 :return: 返回状态码,200代表支付成功,500代表支付失败"""
url = 'http://third.payment.com'
data = {'card_num': card_num, 'amount': amount}
self.response = requests.post(url, dat... | the_stack_v2_python_sparse | PycharmProjects/Python_Automated_Testing_Class_16/Class_16_20190612_Learn_Mock/payment_mock.py | dransonjs/my_python_test_codes | train | 0 |
d5e8852e968dd03124b12cf626a64d535c3cbc59 | [
"n = len(s)\none, zero = (0, n - 1)\nwhile one < n:\n if s[one] == '1':\n break\n one += 1\nwhile zero >= 0:\n if s[zero] == '0':\n break\n zero -= 1\nprint(one, zero)\nk, l = (0, 0)\ni = one + 1\nwhile i < n:\n if s[i] == '0':\n k += 1\n i += 1\ni = zero - 1\nwhile i >= 0:\n ... | <|body_start_0|>
n = len(s)
one, zero = (0, n - 1)
while one < n:
if s[one] == '1':
break
one += 1
while zero >= 0:
if s[zero] == '0':
break
zero -= 1
print(one, zero)
k, l = (0, 0)
i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minFlipsMonoIncrWrong(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def minFlipsMonoIncr(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def minFlipsMonoIncrO1Space(self, s):
""":type s: str :rtype: int"""
<|body_2... | stack_v2_sparse_classes_75kplus_train_065204 | 2,800 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "minFlipsMonoIncrWrong",
"signature": "def minFlipsMonoIncrWrong(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "minFlipsMonoIncr",
"signature": "def minFlipsMonoIncr(self, s)"
},
{
"docstring": ":type s: str :rt... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFlipsMonoIncrWrong(self, s): :type s: str :rtype: int
- def minFlipsMonoIncr(self, s): :type s: str :rtype: int
- def minFlipsMonoIncrO1Space(self, s): :type s: str :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFlipsMonoIncrWrong(self, s): :type s: str :rtype: int
- def minFlipsMonoIncr(self, s): :type s: str :rtype: int
- def minFlipsMonoIncrO1Space(self, s): :type s: str :rtype... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def minFlipsMonoIncrWrong(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def minFlipsMonoIncr(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def minFlipsMonoIncrO1Space(self, s):
""":type s: str :rtype: int"""
<|body_2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minFlipsMonoIncrWrong(self, s):
""":type s: str :rtype: int"""
n = len(s)
one, zero = (0, n - 1)
while one < n:
if s[one] == '1':
break
one += 1
while zero >= 0:
if s[zero] == '0':
break
... | the_stack_v2_python_sparse | F/FlipStringtoMonotoneIncreasing.py | bssrdf/pyleet | train | 2 | |
03724c667175bcbfb72facb13582e5978b0b1b46 | [
"authenticated_user = request.user\nuser_id = kwargs['id']\nuser_profile = get_object_or_404(Profile, user_id=user_id)\nif authenticated_user.id == user_id:\n profile_form = ProfileForm(instance=user_profile)\n return render(request, self.template_name, {'profile_form': profile_form})\nunauthenticated_url = f... | <|body_start_0|>
authenticated_user = request.user
user_id = kwargs['id']
user_profile = get_object_or_404(Profile, user_id=user_id)
if authenticated_user.id == user_id:
profile_form = ProfileForm(instance=user_profile)
return render(request, self.template_name, {... | Handles the user profile view. Requires user to be logged in | ProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles profile fo... | stack_v2_sparse_classes_75kplus_train_065205 | 3,240 | no_license | [
{
"docstring": "Shows the user his own profile or redirects to the login page",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Handles profile form data and either updates profile or renders the form again with errors",
"name": "post",
"signature... | 2 | stack_v2_sparse_classes_30k_train_031010 | Implement the Python class `ProfileView` described below.
Class description:
Handles the user profile view. Requires user to be logged in
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Shows the user his own profile or redirects to the login page
- def post(self, request, *args, **kwargs... | Implement the Python class `ProfileView` described below.
Class description:
Handles the user profile view. Requires user to be logged in
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Shows the user his own profile or redirects to the login page
- def post(self, request, *args, **kwargs... | ce8a83cea5fe7232b6746ad9708688c23d486e99 | <|skeleton|>
class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles profile fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
authenticated_user = request.user
user_id = kwargs['id']
user_profile = get_object_o... | the_stack_v2_python_sparse | users/views.py | johnjudeh/Rendez-Vous-Py | train | 0 |
22a60725b00e3dcdf96c58fae81969a0508687f2 | [
"self.path_connectomist = path_connectomist\nself.environment = os.environ\ncmd = '%s --help' % self.path_connectomist\nprocess = subprocess.Popen(cmd, shell=True, env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nself.stdout, self.stderr = process.communicate()\nself.exitcode = process.returnc... | <|body_start_0|>
self.path_connectomist = path_connectomist
self.environment = os.environ
cmd = '%s --help' % self.path_connectomist
process = subprocess.Popen(cmd, shell=True, env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.stdout, self.stderr = proces... | Parent class for the wrapping of Connectomist functions. | ConnectomistWrapper | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- pat... | stack_v2_sparse_classes_75kplus_train_065206 | 8,020 | permissive | [
{
"docstring": "Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- path_connectomist: str (optional) path to the Connectomist executable. Raises ------ ConnectomistConfigurationError: If Connectomist is not configured.",
"name": "__init__",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_002106 | Implement the Python class `ConnectomistWrapper` described below.
Class description:
Parent class for the wrapping of Connectomist functions.
Method signatures and docstrings:
- def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'): Initialize the ConnectomistWrapper class by se... | Implement the Python class `ConnectomistWrapper` described below.
Class description:
Parent class for the wrapping of Connectomist functions.
Method signatures and docstrings:
- def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'): Initialize the ConnectomistWrapper class by se... | 3105d2b1e4458c3be398391436be54bf59949a34 | <|skeleton|>
class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- pat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConnectomistWrapper:
"""Parent class for the wrapping of Connectomist functions."""
def __init__(self, path_connectomist='/i2bm/local/Ubuntu-14.04-x86_64/ptk/bin/connectomist'):
"""Initialize the ConnectomistWrapper class by setting properly the environment. Parameters ---------- path_connectomis... | the_stack_v2_python_sparse | clindmri/extensions/connectomist/wrappers.py | neurospin/caps-clindmri | train | 0 |
41295b538c303e62417768af18a59b2f8d082868 | [
"res = []\ndummy = head = ListNode(-1)\nfor l in lists:\n while l:\n res.append(l.val)\n l = l.next\nfor value in sorted(res):\n dummy.next = ListNode(value)\n dummy = dummy.next\nreturn head.next",
"dummy = head = ListNode(-1)\nq = PriorityQueue()\nfor l in lists:\n if l:\n q.put... | <|body_start_0|>
res = []
dummy = head = ListNode(-1)
for l in lists:
while l:
res.append(l.val)
l = l.next
for value in sorted(res):
dummy.next = ListNode(value)
dummy = dummy.next
return head.next
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists1(self, lists: List[ListNode]) -> ListNode:
"""O(nLogn)"""
<|body_0|>
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
"""O(Nlogk)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
dummy = head = List... | stack_v2_sparse_classes_75kplus_train_065207 | 1,568 | no_license | [
{
"docstring": "O(nLogn)",
"name": "mergeKLists1",
"signature": "def mergeKLists1(self, lists: List[ListNode]) -> ListNode"
},
{
"docstring": "O(Nlogk)",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: List[ListNode]) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_014343 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists1(self, lists: List[ListNode]) -> ListNode: O(nLogn)
- def mergeKLists(self, lists: List[ListNode]) -> ListNode: O(Nlogk) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists1(self, lists: List[ListNode]) -> ListNode: O(nLogn)
- def mergeKLists(self, lists: List[ListNode]) -> ListNode: O(Nlogk)
<|skeleton|>
class Solution:
def me... | fbaae4bdbb2017ee43b0d1a3f23137a75f7ea2c1 | <|skeleton|>
class Solution:
def mergeKLists1(self, lists: List[ListNode]) -> ListNode:
"""O(nLogn)"""
<|body_0|>
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
"""O(Nlogk)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeKLists1(self, lists: List[ListNode]) -> ListNode:
"""O(nLogn)"""
res = []
dummy = head = ListNode(-1)
for l in lists:
while l:
res.append(l.val)
l = l.next
for value in sorted(res):
dummy.next = ... | the_stack_v2_python_sparse | b_75/merge_k_sorted_lists.py | Milan-Chicago/ds-guide | train | 0 | |
db7182ba59e04cfd998c29f48c614622a6c75a89 | [
"auth_string = self.get_auth_string(url)\nif not auth_string:\n return {}\nb64_auth = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')\nreturn {'Authorization': 'Basic %s' % b64_auth}",
"username, password = self.get_username_password(url)\nif username and password:\n return '%s:%s' % (username... | <|body_start_0|>
auth_string = self.get_auth_string(url)
if not auth_string:
return {}
b64_auth = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')
return {'Authorization': 'Basic %s' % b64_auth}
<|end_body_0|>
<|body_start_1|>
username, password = self.g... | A base for downloaders to add an HTTP basic auth header | BasicAuthDownloader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuthDownloader:
"""A base for downloaders to add an HTTP basic auth header"""
def build_auth_header(self, url):
"""Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header ... | stack_v2_sparse_classes_75kplus_train_065208 | 2,100 | permissive | [
{
"docstring": "Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header name as the key and the value as the value. Both are unicode strings.",
"name": "build_auth_header",
"signature": "def build... | 3 | stack_v2_sparse_classes_30k_train_019058 | Implement the Python class `BasicAuthDownloader` described below.
Class description:
A base for downloaders to add an HTTP basic auth header
Method signatures and docstrings:
- def build_auth_header(self, url): Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the ... | Implement the Python class `BasicAuthDownloader` described below.
Class description:
A base for downloaders to add an HTTP basic auth header
Method signatures and docstrings:
- def build_auth_header(self, url): Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the ... | 9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20 | <|skeleton|>
class BasicAuthDownloader:
"""A base for downloaders to add an HTTP basic auth header"""
def build_auth_header(self, url):
"""Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicAuthDownloader:
"""A base for downloaders to add an HTTP basic auth header"""
def build_auth_header(self, url):
"""Constructs an HTTP basic auth header for a URL, if present in settings :param url: A unicode string of the URL being downloaded :return: A dict with an HTTP header name as the k... | the_stack_v2_python_sparse | app/lib/package_control/downloaders/basic_auth_downloader.py | june07/packagecontrol.io | train | 1 |
50dde82c8d3676eba1c0f8bd03a0aa790aee0758 | [
"super(ClassifierEvaluator, self).__init__()\nself.task_name, self.task_type = task\nself.learner_name, self.learner_type = learner\nself.evaluator_name, self.evaluator_type = evaluator",
"self.logger.info('Executing external subprocess to MOA: %s ON %s USING %s EVALUATED BY %s' % (self.task_name, input, self.lea... | <|body_start_0|>
super(ClassifierEvaluator, self).__init__()
self.task_name, self.task_type = task
self.learner_name, self.learner_type = learner
self.evaluator_name, self.evaluator_type = evaluator
<|end_body_0|>
<|body_start_1|>
self.logger.info('Executing external subprocess ... | Class initiating a MOA classifier for evaluating the classification accuracy of data stream | ClassifierEvaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierEvaluator:
"""Class initiating a MOA classifier for evaluating the classification accuracy of data stream"""
def __init__(self, task, learner, evaluator):
"""Class constructor - initiate evaluation classifier object :param task: Task of evaluation (e.g., name: EvaluatePrequ... | stack_v2_sparse_classes_75kplus_train_065209 | 5,704 | no_license | [
{
"docstring": "Class constructor - initiate evaluation classifier object :param task: Task of evaluation (e.g., name: EvaluatePrequential, type:EvaluatePrequential) :param learner: Type of classification model learner algorithm (e.g., name: HoeffdingTree, type:trees.HoeffdingTree) :param evaluator: Evaluation ... | 4 | stack_v2_sparse_classes_30k_train_005289 | Implement the Python class `ClassifierEvaluator` described below.
Class description:
Class initiating a MOA classifier for evaluating the classification accuracy of data stream
Method signatures and docstrings:
- def __init__(self, task, learner, evaluator): Class constructor - initiate evaluation classifier object :... | Implement the Python class `ClassifierEvaluator` described below.
Class description:
Class initiating a MOA classifier for evaluating the classification accuracy of data stream
Method signatures and docstrings:
- def __init__(self, task, learner, evaluator): Class constructor - initiate evaluation classifier object :... | b66862bd469bf078ca12bdb692e39675d40c96b8 | <|skeleton|>
class ClassifierEvaluator:
"""Class initiating a MOA classifier for evaluating the classification accuracy of data stream"""
def __init__(self, task, learner, evaluator):
"""Class constructor - initiate evaluation classifier object :param task: Task of evaluation (e.g., name: EvaluatePrequ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassifierEvaluator:
"""Class initiating a MOA classifier for evaluating the classification accuracy of data stream"""
def __init__(self, task, learner, evaluator):
"""Class constructor - initiate evaluation classifier object :param task: Task of evaluation (e.g., name: EvaluatePrequential, type:... | the_stack_v2_python_sparse | Evaluator/PostEvaluator/ClassifierEvaluator.py | Navypowder/MiDiPSA-for-non-stationary-streams | train | 0 |
10fabfd281a8860bd1379d066709440578e617ec | [
"if longUrl in self.full2tiny:\n return 'http://tinyurl.com/' + self.full2tiny[longUrl]\nsuffix = ''\ndec = self.global_counter\nif dec == 0:\n suffix += self.letters[0]\nwhile dec:\n suffix += self.letters[dec % 62]\n dec //= 62\nself.full2tiny[longUrl] = suffix\nself.tiny2full[suffix] = longUrl\nself.... | <|body_start_0|>
if longUrl in self.full2tiny:
return 'http://tinyurl.com/' + self.full2tiny[longUrl]
suffix = ''
dec = self.global_counter
if dec == 0:
suffix += self.letters[0]
while dec:
suffix += self.letters[dec % 62]
dec //= 6... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_065210 | 1,390 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_test_002373 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | bf71ef64a9c6e93e434e9daa99479989cc80cadb | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
if longUrl in self.full2tiny:
return 'http://tinyurl.com/' + self.full2tiny[longUrl]
suffix = ''
dec = self.global_counter
if dec == 0:
suffi... | the_stack_v2_python_sparse | 535_Encode_and_Decode_TinyURL.py | IrisSunshine/leetcode | train | 0 | |
f67ca6bb1bdc7852837abf341caa7b029eb7a35f | [
"if nums == []:\n return 0\n'This problems needs to considers the following dynamical programming approach\\n to solve. Otherwise still exceed time limit.\\n ref: http://bookshadow.com/weblog/2017/01/22/leetcode-target-sum/\\n This turns to time complexity O(n*l) \\n '\ndp = ... | <|body_start_0|>
if nums == []:
return 0
'This problems needs to considers the following dynamical programming approach\n to solve. Otherwise still exceed time limit.\n ref: http://bookshadow.com/weblog/2017/01/22/leetcode-target-sum/\n This turns to time comple... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
<|body_0|>
def DFS(self, depth, nums, sum, S):
"""this method regards the problem as a binary tree, "+" like left and "-" like right. The time complexity is O(2**n). ... | stack_v2_sparse_classes_75kplus_train_065211 | 2,891 | no_license | [
{
"docstring": ":type nums: List[int] :type S: int :rtype: int",
"name": "findTargetSumWays",
"signature": "def findTargetSumWays(self, nums, S)"
},
{
"docstring": "this method regards the problem as a binary tree, \"+\" like left and \"-\" like right. The time complexity is O(2**n). But this me... | 2 | stack_v2_sparse_classes_30k_train_038353 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): :type nums: List[int] :type S: int :rtype: int
- def DFS(self, depth, nums, sum, S): this method regards the problem as a binary tree, "+" l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): :type nums: List[int] :type S: int :rtype: int
- def DFS(self, depth, nums, sum, S): this method regards the problem as a binary tree, "+" l... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
<|body_0|>
def DFS(self, depth, nums, sum, S):
"""this method regards the problem as a binary tree, "+" like left and "-" like right. The time complexity is O(2**n). ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTargetSumWays(self, nums, S):
""":type nums: List[int] :type S: int :rtype: int"""
if nums == []:
return 0
'This problems needs to considers the following dynamical programming approach\n to solve. Otherwise still exceed time limit.\n r... | the_stack_v2_python_sparse | leetcode_solution/dynamical programming/#494.Target_Sum.py | HsiangHung/Code-Challenges | train | 0 | |
79d49aea9d87b6460e6df937a2e497fe637e2e91 | [
"try:\n team = Team.objects.get(pk=pk)\nexcept ObjectDoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\nif request.user.has_perm(VIEW_TEAM):\n serializer = TeamDetailsSerializer(team)\n return Response(serializer.data)\nelse:\n return Response(status=status.HTTP_401_UNAUTHORIZED)",
... | <|body_start_0|>
try:
team = Team.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.user.has_perm(VIEW_TEAM):
serializer = TeamDetailsSerializer(team)
return Response(serializer.data)
... | Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}. | TeamDetail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamDetail:
"""Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}."""
def get(self, request, pk, format='None'):
"""Implement the GET method. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team Return : respo... | stack_v2_sparse_classes_75kplus_train_065212 | 10,635 | permissive | [
{
"docstring": "Implement the GET method. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team Return : response (Response) : the response. GET request : return the team's data.",
"name": "get",
"signature": "def get(self, request, pk, format='None')"
... | 3 | stack_v2_sparse_classes_30k_train_028314 | Implement the Python class `TeamDetail` described below.
Class description:
Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}.
Method signatures and docstrings:
- def get(self, request, pk, format='None'): Implement the GET method. Parameters : request (HttpRequest) : the request coming from t... | Implement the Python class `TeamDetail` described below.
Class description:
Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}.
Method signatures and docstrings:
- def get(self, request, pk, format='None'): Implement the GET method. Parameters : request (HttpRequest) : the request coming from t... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class TeamDetail:
"""Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}."""
def get(self, request, pk, format='None'):
"""Implement the GET method. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team Return : respo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamDetail:
"""Contains HTTP methods GET, PUT, DELETE used on /usermanagement/teams/{pk}."""
def get(self, request, pk, format='None'):
"""Implement the GET method. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team Return : response (Response... | the_stack_v2_python_sparse | usersmanagement/views/views_team.py | Open-CMMS/openCMMS_backend | train | 4 |
be754ea7688001bd04b84fb87d6fcf6e4137453d | [
"data_store_adapter = get_configured_data_store_adapter()\ndata = []\nsource_files = data_store_adapter.listdir(path=asset.ready_path, recursive=True)\nif asset.declarations.is_parquet_output:\n for fpath in source_files:\n with data_store_adapter.open(fpath, 'rb') as f:\n data.append(pd.read_p... | <|body_start_0|>
data_store_adapter = get_configured_data_store_adapter()
data = []
source_files = data_store_adapter.listdir(path=asset.ready_path, recursive=True)
if asset.declarations.is_parquet_output:
for fpath in source_files:
with data_store_adapter.ope... | IO interface for the Airtunnel PandasDataAsset. | PandasDataAssetIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PandasDataAssetIO:
"""IO interface for the Airtunnel PandasDataAsset."""
def retrieve_data_asset(asset: PandasDataAsset, **reader_kwargs) -> pd.DataFrame:
"""Retrieves a PandasDataAsset from the Airtunnel data store (using Pandas). :param asset: the data asset to retrieve :param read... | stack_v2_sparse_classes_75kplus_train_065213 | 29,578 | permissive | [
{
"docstring": "Retrieves a PandasDataAsset from the Airtunnel data store (using Pandas). :param asset: the data asset to retrieve :param reader_kwargs: additional keyword arguments to pass into the Pandas reader function :return: the retrieved data as a Pandas dataframe",
"name": "retrieve_data_asset",
... | 3 | stack_v2_sparse_classes_30k_train_012892 | Implement the Python class `PandasDataAssetIO` described below.
Class description:
IO interface for the Airtunnel PandasDataAsset.
Method signatures and docstrings:
- def retrieve_data_asset(asset: PandasDataAsset, **reader_kwargs) -> pd.DataFrame: Retrieves a PandasDataAsset from the Airtunnel data store (using Pand... | Implement the Python class `PandasDataAssetIO` described below.
Class description:
IO interface for the Airtunnel PandasDataAsset.
Method signatures and docstrings:
- def retrieve_data_asset(asset: PandasDataAsset, **reader_kwargs) -> pd.DataFrame: Retrieves a PandasDataAsset from the Airtunnel data store (using Pand... | bbed0a2d5addd0dd6221b75c06982f47e0d837d4 | <|skeleton|>
class PandasDataAssetIO:
"""IO interface for the Airtunnel PandasDataAsset."""
def retrieve_data_asset(asset: PandasDataAsset, **reader_kwargs) -> pd.DataFrame:
"""Retrieves a PandasDataAsset from the Airtunnel data store (using Pandas). :param asset: the data asset to retrieve :param read... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PandasDataAssetIO:
"""IO interface for the Airtunnel PandasDataAsset."""
def retrieve_data_asset(asset: PandasDataAsset, **reader_kwargs) -> pd.DataFrame:
"""Retrieves a PandasDataAsset from the Airtunnel data store (using Pandas). :param asset: the data asset to retrieve :param reader_kwargs: ad... | the_stack_v2_python_sparse | src/airtunnel/data_asset.py | rufuspollock/airtunnel | train | 0 |
66ab92cf377d558ad3276f356fc0cbfc1fc137f9 | [
"if len(prices) == 0:\n return 0\nL = [0] * len(prices)\nP = [0] * len(prices)\nL[0] = prices[0]\nP[0] = 0\nfor i in range(1, len(prices)):\n L[i] = min(prices[i], L[i - 1])\n P[i] = max(prices[i] - L[i], P[i - 1])\nreturn max(P)",
"if len(prices) <= 1:\n return 0\nprofit = [prices[i] - prices[i - 1] ... | <|body_start_0|>
if len(prices) == 0:
return 0
L = [0] * len(prices)
P = [0] * len(prices)
L[0] = prices[0]
P[0] = 0
for i in range(1, len(prices)):
L[i] = min(prices[i], L[i - 1])
P[i] = max(prices[i] - L[i], P[i - 1])
return m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int DP in terms of max subarray sum"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus_train_065214 | 1,745 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int DP in terms of max subarray sum",
"name": "maxProfit",
"signature": "def maxP... | 2 | stack_v2_sparse_classes_30k_train_048041 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)
- def maxProfit(self, prices): :type prices: List[int] :rtype: int DP in te... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)
- def maxProfit(self, prices): :type prices: List[int] :rtype: int DP in te... | 9746205998338fb4d7fd51300a21149c4181fc8f | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int DP in terms of max subarray sum"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int DP O(n) space, can be reduced to O(1)"""
if len(prices) == 0:
return 0
L = [0] * len(prices)
P = [0] * len(prices)
L[0] = prices[0]
P[0] = 0
for i in range(1, len(p... | the_stack_v2_python_sparse | leetcode/dp/6_stock.py | RuizhenMai/academic-blog | train | 0 | |
8ddb26ff3c6bee016b24c67f31390de196c1ff53 | [
"return_dict = {}\nif not table:\n return return_dict\nfor record in table.records:\n if record.get_number_of_values() != 2:\n continue\n identification = self._GetRecordValue(record, 0)\n filename = self._GetRecordValue(record, 1)\n if not identification:\n continue\n return_dict[id... | <|body_start_0|>
return_dict = {}
if not table:
return return_dict
for record in table.records:
if record.get_number_of_values() != 2:
continue
identification = self._GetRecordValue(record, 0)
filename = self._GetRecordValue(record,... | Parses a File History ESE database file. | FileHistoryEseDbPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification fie... | stack_v2_sparse_classes_75kplus_train_065215 | 3,890 | permissive | [
{
"docstring": "Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification field as key and filename as value.",
"name": "_GetDictFromStringsTable",
"signature": "def _GetDictFromStringsTable(self, t... | 2 | stack_v2_sparse_classes_30k_train_009348 | Implement the Python class `FileHistoryEseDbPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, table): Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.tab... | Implement the Python class `FileHistoryEseDbPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, table): Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.tab... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification fie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification field as key and... | the_stack_v2_python_sparse | plaso/parsers/esedb_plugins/file_history.py | CNR-ITTIG/plasodfaxp | train | 1 |
7cbbffc8a42aeff3aaf4730f6fa0ff8886699b90 | [
"super(DQN, self).__init__()\nself.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)\nself.bn1 = nn.BatchNorm2d(16)\nself.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)\nself.bn2 = nn.BatchNorm2d(32)\nself.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)\nself.bn3 = nn.BatchNorm2d(32)\n\ndef conv2d_size_out(s... | <|body_start_0|>
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)
self.bn1 = nn.BatchNorm2d(16)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)
self.bn2 = nn.BatchNorm2d(32)
self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
... | DQN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQN:
def __init__(self, h, w, outputs):
"""DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN input, return the NN output"""
<|body_0|>
def forward(self, x):
"""given ... | stack_v2_sparse_classes_75kplus_train_065216 | 9,848 | no_license | [
{
"docstring": "DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN input, return the NN output",
"name": "__init__",
"signature": "def __init__(self, h, w, outputs)"
},
{
"docstring": "given x as ... | 2 | stack_v2_sparse_classes_30k_train_017738 | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, h, w, outputs): DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN in... | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, h, w, outputs): DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN in... | e76933f60c569280f939c2695bcef4f8465cb7c1 | <|skeleton|>
class DQN:
def __init__(self, h, w, outputs):
"""DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN input, return the NN output"""
<|body_0|>
def forward(self, x):
"""given ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DQN:
def __init__(self, h, w, outputs):
"""DQN Attributes ---------- h : int image height w : int image width outputs : int size of output feature Methods ------- forward(self, x) given x as NN input, return the NN output"""
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, ker... | the_stack_v2_python_sparse | torch_env/001-dqn/dqn.py | n4m4g/python_project | train | 0 | |
274abdb88bdc24b6b9d7a52f9f47735c9f04898a | [
"if os.environ.get('TCL_LIBRARY'):\n self.had_TCL_LIBRARY = True\n self.old_TCL_LIBRARY = os.environ['TCL_LIBRARY']\nelse:\n self.had_TCL_LIBRARY = False\ntcl_path = os.path.join(devkit_root, 'tools', 'python27', 'tcl', 'tcl8.5')\nos.environ['TCL_LIBRARY'] = tcl_path",
"if self.had_TCL_LIBRARY:\n os.e... | <|body_start_0|>
if os.environ.get('TCL_LIBRARY'):
self.had_TCL_LIBRARY = True
self.old_TCL_LIBRARY = os.environ['TCL_LIBRARY']
else:
self.had_TCL_LIBRARY = False
tcl_path = os.path.join(devkit_root, 'tools', 'python27', 'tcl', 'tcl8.5')
os.environ['TC... | TCL_LIBRARY_handler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
<|body... | stack_v2_sparse_classes_75kplus_train_065217 | 24,092 | no_license | [
{
"docstring": "If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter.",
"name": "__init__",
"signature": "def __init__(self, devkit_root)"
},
... | 2 | stack_v2_sparse_classes_30k_train_046740 | Implement the Python class `TCL_LIBRARY_handler` described below.
Class description:
Implement the TCL_LIBRARY_handler class.
Method signatures and docstrings:
- def __init__(self, devkit_root): If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note tha... | Implement the Python class `TCL_LIBRARY_handler` described below.
Class description:
Implement the TCL_LIBRARY_handler class.
Method signatures and docstrings:
- def __init__(self, devkit_root): If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note tha... | bff2d8c9e5e1ead4018f63098c1adea0e0c28184 | <|skeleton|>
class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
if os.environ.get('T... | the_stack_v2_python_sparse | adk/tools/packages/menus/buildFlashImage.py | litterstar7/Qualcomm_BT_Audio | train | 4 | |
80b627c06551071dd5bb9d4f0679e0375d4b227f | [
"if cls.credentials is None:\n cls.credentials = service_account.Credentials.from_service_account_info(cls.service_account_info, scopes=cls.GCP_SA_SCOPES)\nrequest = google.auth.transport.requests.Request()\ncls.credentials.refresh(request)\ncurrent_app.logger.info('Call successful: obtained token.')\nreturn cls... | <|body_start_0|>
if cls.credentials is None:
cls.credentials = service_account.Credentials.from_service_account_info(cls.service_account_info, scopes=cls.GCP_SA_SCOPES)
request = google.auth.transport.requests.Request()
cls.credentials.refresh(request)
current_app.logger.info... | Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls. | GoogleStorageTokenService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleStorageTokenService:
"""Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls."""
def get_token(cls):
"""Generate an OAuth access token with cloud storage access."""
<|body_0|>
def get_credentials(cls):
"""Generate GC... | stack_v2_sparse_classes_75kplus_train_065218 | 4,009 | permissive | [
{
"docstring": "Generate an OAuth access token with cloud storage access.",
"name": "get_token",
"signature": "def get_token(cls)"
},
{
"docstring": "Generate GCP auth credentials to pass to a GCP client.",
"name": "get_credentials",
"signature": "def get_credentials(cls)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_005636 | Implement the Python class `GoogleStorageTokenService` described below.
Class description:
Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls.
Method signatures and docstrings:
- def get_token(cls): Generate an OAuth access token with cloud storage access.
- def get_credenti... | Implement the Python class `GoogleStorageTokenService` described below.
Class description:
Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls.
Method signatures and docstrings:
- def get_token(cls): Generate an OAuth access token with cloud storage access.
- def get_credenti... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class GoogleStorageTokenService:
"""Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls."""
def get_token(cls):
"""Generate an OAuth access token with cloud storage access."""
<|body_0|>
def get_credentials(cls):
"""Generate GC... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleStorageTokenService:
"""Google Cloud Storage implementation. Maintain access token for Google Cloud Storage API calls."""
def get_token(cls):
"""Generate an OAuth access token with cloud storage access."""
if cls.credentials is None:
cls.credentials = service_account.Cre... | the_stack_v2_python_sparse | ppr-api/src/ppr_api/callback/auth/token_service.py | bcgov/ppr | train | 4 |
3cc4a0d1031e0e71c072e5d0720379eb3c8991b6 | [
"self.flag = False\nvisited = [0] * numCourses\ncourses = {}\nfor x in prerequisites:\n courses[x[1]] = courses.get(x[1], []) + [x[0]]\nfor i in range(numCourses):\n self.DFS(i, numCourses, visited, courses)\nreturn not self.flag",
"if visited[i] != 0:\n if visited[i] == 2:\n self.flag = True\n ... | <|body_start_0|>
self.flag = False
visited = [0] * numCourses
courses = {}
for x in prerequisites:
courses[x[1]] = courses.get(x[1], []) + [x[0]]
for i in range(numCourses):
self.DFS(i, numCourses, visited, courses)
return not self.flag
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,... | stack_v2_sparse_classes_75kplus_train_065219 | 1,696 | no_license | [
{
"docstring": "https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,1], [3,2], [0,3]], cyclic * [[2,5],[0,5],[2,4],[1,4],[1,3],[3,0],[2,0]], sort = [5,4,0,2,3,1]",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological ... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""https://www.youtube.com/watch?v=qe_pQCh09yU https://www.youtube.com/watch?v=kXy0ABd1vwo topological sorting. DAG: directed acyclic diagram O(V+E) V:vertex, E: edge good test examples: * [[1,0], [2,1], [3,2], [0,... | the_stack_v2_python_sparse | leetcode_solution/graph/#207.Course_Schedule.py | HsiangHung/Code-Challenges | train | 0 | |
b984f8f457887caf757c748d15aaa2e9fe86a769 | [
"self.xd = kwargs['xd']\nself.vol_rank = kwargs['vol_rank']\nself.vol_daily = kwargs['vol_daily']\nself.factor_name = '{}:{}'.format(self.__class__.__name__, self.xd)",
"if self.today_ind < self.xd - 1:\n return None\nyesterday = self.kl_pd.iloc[self.today_ind - 1]\nvolumes = self.kl_pd.volume[-self.vol_daily:... | <|body_start_0|>
self.xd = kwargs['xd']
self.vol_rank = kwargs['vol_rank']
self.vol_daily = kwargs['vol_daily']
self.factor_name = '{}:{}'.format(self.__class__.__name__, self.xd)
<|end_body_0|>
<|body_start_1|>
if self.today_ind < self.xd - 1:
return None
ye... | 示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event | FactorBuyBreak | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorBuyBreak:
"""示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 突破参数xd 比如20,30,40天...突破"""
<|body_0|>
def fit_day(self, today):
"""针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :return:"""
<|bod... | stack_v2_sparse_classes_75kplus_train_065220 | 4,779 | no_license | [
{
"docstring": "kwargs中必须包含: 突破参数xd 比如20,30,40天...突破",
"name": "_init_self",
"signature": "def _init_self(self, **kwargs)"
},
{
"docstring": "针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :return:",
"name": "fit_day",
"signature": "def fit_day(self, today)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010160 | Implement the Python class `FactorBuyBreak` described below.
Class description:
示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中必须包含: 突破参数xd 比如20,30,40天...突破
- def fit_day(self, today): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :ret... | Implement the Python class `FactorBuyBreak` described below.
Class description:
示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中必须包含: 突破参数xd 比如20,30,40天...突破
- def fit_day(self, today): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :ret... | 822d97afd0ed0987723b574c22d15cc1325c36ed | <|skeleton|>
class FactorBuyBreak:
"""示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 突破参数xd 比如20,30,40天...突破"""
<|body_0|>
def fit_day(self, today):
"""针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :return:"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactorBuyBreak:
"""示例正向突破买入择时类,混入BuyCallMixin,即向上突破触发买入event"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 突破参数xd 比如20,30,40天...突破"""
self.xd = kwargs['xd']
self.vol_rank = kwargs['vol_rank']
self.vol_daily = kwargs['vol_daily']
self.factor_name = '{}:{}'.form... | the_stack_v2_python_sparse | common/FactorBuy/FactorBuyBreak.py | xiaoshitoucoding/Quantitative_Trading | train | 0 |
d1d8b95966d2280d2f6e978c5c22aeeda94f578f | [
"log.info('Spawning subprocess: {}'.format(command))\nenv = {**os.environ, 'ETS_TOOLKIT': 'null'}\nrw_out = FileReaderWriter('./data.txt')\nd_out = {}\nd_keys = ['force.X', 'force.Y']\nfor i in range(len(d_keys)):\n d_out[d_keys[i]] = user_input[i]\nrw_out.writeData(d_out)\nprocess = subprocess.Popen(command, en... | <|body_start_0|>
log.info('Spawning subprocess: {}'.format(command))
env = {**os.environ, 'ETS_TOOLKIT': 'null'}
rw_out = FileReaderWriter('./data.txt')
d_out = {}
d_keys = ['force.X', 'force.Y']
for i in range(len(d_keys)):
d_out[d_keys[i]] = user_input[i]
... | A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point. | SubprocessWorkflow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def _call_subprocess(self, command, user_input):
"""Calls a subprocess to perform a command with parsed user_input"""
<|body_0|>
def _subprocess_evaluate(self, par... | stack_v2_sparse_classes_75kplus_train_065221 | 6,092 | permissive | [
{
"docstring": "Calls a subprocess to perform a command with parsed user_input",
"name": "_call_subprocess",
"signature": "def _call_subprocess(self, command, user_input)"
},
{
"docstring": "Executes the workflow using the given parameter values running on an external process via the subprocess ... | 3 | null | Implement the Python class `SubprocessWorkflow` described below.
Class description:
A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point.
Method signatures and docstrings:
- def _call_subprocess(self, command, user_input): Calls a subprocess to perform a command with parsed user_input
- de... | Implement the Python class `SubprocessWorkflow` described below.
Class description:
A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point.
Method signatures and docstrings:
- def _call_subprocess(self, command, user_input): Calls a subprocess to perform a command with parsed user_input
- de... | f22c0ad3cc45c3b5a7f9c4fd0b20549d7dfc9aeb | <|skeleton|>
class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def _call_subprocess(self, command, user_input):
"""Calls a subprocess to perform a command with parsed user_input"""
<|body_0|>
def _subprocess_evaluate(self, par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def _call_subprocess(self, command, user_input):
"""Calls a subprocess to perform a command with parsed user_input"""
log.info('Spawning subprocess: {}'.format(command))
env... | the_stack_v2_python_sparse | es_example/es_evaluator/subprocess_workflow.py | force-h2020/force-bdss-plugin-enginsoft-toy-model | train | 0 |
231824f489c72a9cfa09d2fdf6992ab233ecf1c8 | [
"tmp = visual.TextStim(win=window, font=task_font, text=static_task_text)\nstatic_task_pos = (tmp.boundingBox[0] / window.size[0] - 1, 1 - task_height)\ninfo_color = [static_task_color, info_color]\ninfo_font = [task_font, info_font]\ninfo_text = [static_task_text, info_text]\ninfo_pos = [static_task_pos, info_pos]... | <|body_start_0|>
tmp = visual.TextStim(win=window, font=task_font, text=static_task_text)
static_task_pos = (tmp.boundingBox[0] / window.size[0] - 1, 1 - task_height)
info_color = [static_task_color, info_color]
info_font = [task_font, info_font]
info_text = [static_task_text, in... | Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli): task visualization. sti(visual_Text_Stimuli): stimuli text. | CopyPhraseDisplay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyPhraseDisplay:
"""Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli): task visualization. sti(visual_Text_... | stack_v2_sparse_classes_75kplus_train_065222 | 4,166 | permissive | [
{
"docstring": "Initializes Copy Phrase Task Objects",
"name": "__init__",
"signature": "def __init__(self, window, clock, experiment_clock, marker_writer, static_task_text='COPY_PHRASE', static_task_color='White', info_text='Press Space Bar to Pause', info_color='White', info_pos=(0, -0.9), info_height... | 2 | stack_v2_sparse_classes_30k_train_050389 | Implement the Python class `CopyPhraseDisplay` described below.
Class description:
Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli... | Implement the Python class `CopyPhraseDisplay` described below.
Class description:
Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli... | 397ce67c15a9e84d8a6c13f621fad3cf6b62df2e | <|skeleton|>
class CopyPhraseDisplay:
"""Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli): task visualization. sti(visual_Text_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CopyPhraseDisplay:
"""Copy Phrase display object of RSVP Attr: static_task(visual_Text_Stimuli): aim string of the copy phrase. (Stored in self.text[0]) information(visual_Text_Stimuli): information text. (Stored in self.text[1]) task(Multiinfo_color_Stimuli): task visualization. sti(visual_Text_Stimuli): sti... | the_stack_v2_python_sparse | bcipy/display/rsvp/mode/copy_phrase.py | nik-sm/BciPy | train | 0 |
cae97a94f559e542863ce7c81b05a43a13444646 | [
"buy_1, buy_2 = (float('-inf'), float('-inf'))\nsell_1, sell_2 = (0, 0)\nfor price in prices:\n buy_1 = max(buy_1, -price)\n sell_1 = max(sell_1, buy_1 + price)\n buy_2 = max(buy_2, sell_1 - price)\n sell_2 = max(sell_2, buy_2 + price)\n print(price, buy_1, sell_1, buy_2, sell_2)\nreturn sell_2",
"... | <|body_start_0|>
buy_1, buy_2 = (float('-inf'), float('-inf'))
sell_1, sell_2 = (0, 0)
for price in prices:
buy_1 = max(buy_1, -price)
sell_1 = max(sell_1, buy_1 + price)
buy_2 = max(buy_2, sell_1 - price)
sell_2 = max(sell_2, buy_2 + price)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_atmostk(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit_dp(self, prices):
""":type prices: List[int] :rtyp... | stack_v2_sparse_classes_75kplus_train_065223 | 4,217 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_atmostk",
"signature": "def maxProfit_atmostk(self, prices)"
},
{
"docstring": ":type ... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_atmostk(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_dp(self, prices): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_atmostk(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_dp(self, prices): :typ... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_atmostk(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit_dp(self, prices):
""":type prices: List[int] :rtyp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
buy_1, buy_2 = (float('-inf'), float('-inf'))
sell_1, sell_2 = (0, 0)
for price in prices:
buy_1 = max(buy_1, -price)
sell_1 = max(sell_1, buy_1 + price)
buy_2 =... | the_stack_v2_python_sparse | src/lt_123.py | oxhead/CodingYourWay | train | 0 | |
8df1f5685a66075b63f50c260dcaf7e6c866f776 | [
"self.types = {}\nwith open('resources/types.txt') as file:\n for line in file:\n if not line.startswith('#'):\n tokens = line.split('\\t')\n self.types[tokens[0]] = tokens[1].strip()",
"clausetypes = {'p': 'dcl', 's': 'dcl', 'f': 'dcl', 'r': 'rel', 'd': 'dep'}\nclausetype = clause... | <|body_start_0|>
self.types = {}
with open('resources/types.txt') as file:
for line in file:
if not line.startswith('#'):
tokens = line.split('\t')
self.types[tokens[0]] = tokens[1].strip()
<|end_body_0|>
<|body_start_1|>
claus... | Adds CCG features | CCGTyper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
<|body_0|>
def type_verb(self, surface, pos, tag):
"""Adds CCG features"""
<|body_1|>
def type(self, surface, pos, tag):
"""Retypes it as a verb if it's a verb, cop... | stack_v2_sparse_classes_75kplus_train_065224 | 24,263 | no_license | [
{
"docstring": "Adds CCG features",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds CCG features",
"name": "type_verb",
"signature": "def type_verb(self, surface, pos, tag)"
},
{
"docstring": "Retypes it as a verb if it's a verb, copula or verbal nou... | 3 | stack_v2_sparse_classes_30k_train_043602 | Implement the Python class `CCGTyper` described below.
Class description:
Adds CCG features
Method signatures and docstrings:
- def __init__(self): Adds CCG features
- def type_verb(self, surface, pos, tag): Adds CCG features
- def type(self, surface, pos, tag): Retypes it as a verb if it's a verb, copula or verbal n... | Implement the Python class `CCGTyper` described below.
Class description:
Adds CCG features
Method signatures and docstrings:
- def __init__(self): Adds CCG features
- def type_verb(self, surface, pos, tag): Adds CCG features
- def type(self, surface, pos, tag): Retypes it as a verb if it's a verb, copula or verbal n... | 0f6e943c2bf639f2bdad278145f6fa25502a02df | <|skeleton|>
class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
<|body_0|>
def type_verb(self, surface, pos, tag):
"""Adds CCG features"""
<|body_1|>
def type(self, surface, pos, tag):
"""Retypes it as a verb if it's a verb, cop... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CCGTyper:
"""Adds CCG features"""
def __init__(self):
"""Adds CCG features"""
self.types = {}
with open('resources/types.txt') as file:
for line in file:
if not line.startswith('#'):
tokens = line.split('\t')
self... | the_stack_v2_python_sparse | innealan/acainn.py | colinbatchelor/gdbank | train | 4 |
098f4a68571c592ab452b243c06c946d55810bc5 | [
"super(RNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)\nself.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hidden_dim, num_layers=n_layers, dropout=dropout, batch_f... | <|body_start_0|>
super(RNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embed = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
self.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hi... | RNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of... | stack_v2_sparse_classes_75kplus_train_065225 | 11,328 | no_license | [
{
"docstring": "Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of the embeddings :param hidden_dim: The size of the hidden ... | 3 | stack_v2_sparse_classes_30k_train_032898 | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the ne... | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the ne... | 727cedd3e3aca715b9326f625548bedb5a0c1b9b | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN module :param vocab_size: The number of input dimensions of the neural network (size of the vocabulary) :param output_size: The number of output dimensions of the neural ne... | the_stack_v2_python_sparse | recurring_neural_network/tv_script_generation/tv_script_generation.py | sivaneshl/deep_learning_course | train | 0 | |
c7d548efec7c7d0da7efabd95c1442f97613a1c9 | [
"filters = defaultdict(int)\nlen_words = len(words)\nfor i in range(len_words):\n curr = words[i]\n len_curr = len(curr)\n for j in range(len_curr + 1):\n for k in range(len_curr + 1):\n pre = ''\n suf = ''\n if j > 0:\n pre = curr[:j]\n if ... | <|body_start_0|>
filters = defaultdict(int)
len_words = len(words)
for i in range(len_words):
curr = words[i]
len_curr = len(curr)
for j in range(len_curr + 1):
for k in range(len_curr + 1):
pre = ''
suf ... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
filters = defaultdict(int)
len_wor... | stack_v2_sparse_classes_75kplus_train_065226 | 1,650 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001532 | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
def __in... | d4bcee3df2f501349feed7a26ef9828573aff873 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
filters = defaultdict(int)
len_words = len(words)
for i in range(len_words):
curr = words[i]
len_curr = len(curr)
for j in range(len_curr + 1):
for k in range... | the_stack_v2_python_sparse | LeetCodeContests/62/745_Prefix_and_Suffix_Search.py | rajlath/rkl_codes | train | 0 | |
a2f6e949323ee353297f30a9e4299104435bc70c | [
"try:\n self.check_object_permissions(request, pkprofile)\n self.check_object_permissions(request, Message_receive.objects.get(id=pkmsg).to.id)\n Message_receive.objects.filter(id=pkmsg).update(msg_read=bool(request.DATA.get('value')))\nexcept ValidationError as e:\n raise Response({'detail': e.message}... | <|body_start_0|>
try:
self.check_object_permissions(request, pkprofile)
self.check_object_permissions(request, Message_receive.objects.get(id=pkmsg).to.id)
Message_receive.objects.filter(id=pkmsg).update(msg_read=bool(request.DATA.get('value')))
except ValidationError... | MsgDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MsgDetailView:
def put(self, request, pkmsg, pkprofile, *args, **kwargs):
"""Revisa errores."""
<|body_0|>
def delete(self, request, pkmsg, pkprofile, *args, **kwargs):
"""Revisa errores."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_065227 | 4,932 | no_license | [
{
"docstring": "Revisa errores.",
"name": "put",
"signature": "def put(self, request, pkmsg, pkprofile, *args, **kwargs)"
},
{
"docstring": "Revisa errores.",
"name": "delete",
"signature": "def delete(self, request, pkmsg, pkprofile, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `MsgDetailView` described below.
Class description:
Implement the MsgDetailView class.
Method signatures and docstrings:
- def put(self, request, pkmsg, pkprofile, *args, **kwargs): Revisa errores.
- def delete(self, request, pkmsg, pkprofile, *args, **kwargs): Revisa errores. | Implement the Python class `MsgDetailView` described below.
Class description:
Implement the MsgDetailView class.
Method signatures and docstrings:
- def put(self, request, pkmsg, pkprofile, *args, **kwargs): Revisa errores.
- def delete(self, request, pkmsg, pkprofile, *args, **kwargs): Revisa errores.
<|skeleton|>... | dc9edd3a42f17664e71c6a554c4074c0538acd05 | <|skeleton|>
class MsgDetailView:
def put(self, request, pkmsg, pkprofile, *args, **kwargs):
"""Revisa errores."""
<|body_0|>
def delete(self, request, pkmsg, pkprofile, *args, **kwargs):
"""Revisa errores."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MsgDetailView:
def put(self, request, pkmsg, pkprofile, *args, **kwargs):
"""Revisa errores."""
try:
self.check_object_permissions(request, pkprofile)
self.check_object_permissions(request, Message_receive.objects.get(id=pkmsg).to.id)
Message_receive.objects... | the_stack_v2_python_sparse | api1/message/views.py | hvar90/ProjectStartup | train | 0 | |
a75c33816dc918279b40a897b2ee13d17c1177e0 | [
"self.words = words\nself.memo = {}\nself.indices = collections.defaultdict(list)\nfor i, x in enumerate(words):\n self.indices[x].append(i)",
"min_dist = len(self.words)\nindices1, indices2 = (self.indices[word1], self.indices[word2])\ni, j = (0, 0)\nwhile i < len(indices1) and j < len(indices2):\n min_dis... | <|body_start_0|>
self.words = words
self.memo = {}
self.indices = collections.defaultdict(list)
for i, x in enumerate(words):
self.indices[x].append(i)
<|end_body_0|>
<|body_start_1|>
min_dist = len(self.words)
indices1, indices2 = (self.indices[word1], self.... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.words = words
self.memo ... | stack_v2_sparse_classes_75kplus_train_065228 | 959 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018564 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 24aaca7585c59255a86474c1f8088bd5b81ebf51 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.words = words
self.memo = {}
self.indices = collections.defaultdict(list)
for i, x in enumerate(words):
self.indices[x].append(i)
def shortest(self, word1, word2):
""":ty... | the_stack_v2_python_sparse | Design/244. Shortest Word Distance II.py | burnmg/LC_algorithms_practice | train | 0 | |
0abf097846d090a9f1214d0735d5eee8c2b07bac | [
"super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)\nif distribution:\n self.dist = distribution\nelse:\n self.dist = UniformDistribution()\nself.water_viscosity = water_viscosity\nself.water_density = water_density",
"drop_size = np.zeros((num_new_particles,), dtype=np.float64)\nle_density ... | <|body_start_0|>
super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)
if distribution:
self.dist = distribution
else:
self.dist = UniformDistribution()
self.water_viscosity = water_viscosity
self.water_density = water_density
<|end_body_0|>
... | InitRiseVelFromDropletSizeFromDist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_75kplus_train_065229 | 23,180 | no_license | [
{
"docstring": "Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet size. Even though the droplet size is not changing over time, it is still stored in data array, as it can be useful for post-pro... | 2 | null | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | 81f0e73b50b83022bf8327e181a3799fa2d980c1 | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet s... | the_stack_v2_python_sparse | py_gnome/gnome/elements.py | kthyng/GNOME2 | train | 1 | |
6067ea210d2b75e44fe5784d66f07bb67beae91d | [
"if digits is None or len(digits) == 0:\n return [1]\ntemp = [str(i) for i in digits]\nnumber = int(''.join(temp))\nreturn [int(i) for i in list(str(number + 1))]",
"if digits is None or len(digits) == 0:\n return [1]\nmove_one = 0\ndigits[-1] += 1\nfor i in reversed(range(len(digits))):\n if move_one + ... | <|body_start_0|>
if digits is None or len(digits) == 0:
return [1]
temp = [str(i) for i in digits]
number = int(''.join(temp))
return [int(i) for i in list(str(number + 1))]
<|end_body_0|>
<|body_start_1|>
if digits is None or len(digits) == 0:
return [1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if digits is None or len(di... | stack_v2_sparse_classes_75kplus_train_065230 | 1,166 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne_test1",
"signature": "def plusOne_test1(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022951 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne_test1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne_test1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def plusOne_test1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
if digits is None or len(digits) == 0:
return [1]
temp = [str(i) for i in digits]
number = int(''.join(temp))
return [int(i) for i in list(str(number + 1))]
def p... | the_stack_v2_python_sparse | array_66.py | cainingning/leetcode | train | 1 | |
6668cd69fdae67c18e2dbab4384d99012e497c75 | [
"self.caching_enabled = caching_enabled\nself.discovery_enabled = discovery_enabled\nself.encryption_enabled = encryption_enabled\nself.encryption_required = encryption_required\nself.is_share_level_permission_empty = is_share_level_permission_empty\nself.permissions = permissions",
"if dictionary is None:\n r... | <|body_start_0|>
self.caching_enabled = caching_enabled
self.discovery_enabled = discovery_enabled
self.encryption_enabled = encryption_enabled
self.encryption_required = encryption_required
self.is_share_level_permission_empty = is_share_level_permission_empty
self.permi... | Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file caching is supported discovery_enabled (bool): Whether the share is discoverable. ... | AliasSmbConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliasSmbConfig:
"""Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file caching is supported discovery_enabled (... | stack_v2_sparse_classes_75kplus_train_065231 | 3,713 | permissive | [
{
"docstring": "Constructor for the AliasSmbConfig class",
"name": "__init__",
"signature": "def __init__(self, caching_enabled=None, discovery_enabled=None, encryption_enabled=None, encryption_required=None, is_share_level_permission_empty=None, permissions=None)"
},
{
"docstring": "Creates an ... | 2 | stack_v2_sparse_classes_30k_train_009025 | Implement the Python class `AliasSmbConfig` described below.
Class description:
Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file c... | Implement the Python class `AliasSmbConfig` described below.
Class description:
Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file c... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AliasSmbConfig:
"""Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file caching is supported discovery_enabled (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AliasSmbConfig:
"""Implementation of the 'AliasSmbConfig' model. Message defining SMB config for IRIS. SMB config contains SMB encryption flags, SMB discoverable flag and Share level permissions. Attributes: caching_enabled (bool): Indicate if offline file caching is supported discovery_enabled (bool): Whethe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/alias_smb_config.py | cohesity/management-sdk-python | train | 24 |
5ebaf98990f1723ed520236535b543888dfc7e95 | [
"if type(data) != np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = (data.shape[0], data.shape[1])\nif n < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1, keepdims=True)\nself.cov = np.matmul(data - self.mean, da... | <|body_start_0|>
if type(data) != np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = (data.shape[0], data.shape[1])
if n < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1, ke... | represents multinormal random variable | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""represents multinormal random variable"""
def __init__(self, data):
"""creates multinormal instance"""
<|body_0|>
def pdf(self, x):
"""calculates the pdf at a data point x: np.ndarray (d, 1) containing a data point d: number of dimensions"""
... | stack_v2_sparse_classes_75kplus_train_065232 | 1,446 | no_license | [
{
"docstring": "creates multinormal instance",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "calculates the pdf at a data point x: np.ndarray (d, 1) containing a data point d: number of dimensions",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016477 | Implement the Python class `MultiNormal` described below.
Class description:
represents multinormal random variable
Method signatures and docstrings:
- def __init__(self, data): creates multinormal instance
- def pdf(self, x): calculates the pdf at a data point x: np.ndarray (d, 1) containing a data point d: number o... | Implement the Python class `MultiNormal` described below.
Class description:
represents multinormal random variable
Method signatures and docstrings:
- def __init__(self, data): creates multinormal instance
- def pdf(self, x): calculates the pdf at a data point x: np.ndarray (d, 1) containing a data point d: number o... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class MultiNormal:
"""represents multinormal random variable"""
def __init__(self, data):
"""creates multinormal instance"""
<|body_0|>
def pdf(self, x):
"""calculates the pdf at a data point x: np.ndarray (d, 1) containing a data point d: number of dimensions"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""represents multinormal random variable"""
def __init__(self, data):
"""creates multinormal instance"""
if type(data) != np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = (data.shape[0], data.shape[1])
... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | mag389/holbertonschool-machine_learning | train | 2 |
a02a5e7846dbc3679274699a071b435788d8d4be | [
"height = len(matrix)\nwidth = len(matrix[0])\nrotated = [[0 for x in range(width)] for y in range(height)]\nfor y in range(height):\n for x in range(width):\n rotated[x][height - 1 - y] = matrix[y][x]\nfor y in range(height):\n for x in range(width):\n matrix[y][x] = rotated[y][x]\nreturn None"... | <|body_start_0|>
height = len(matrix)
width = len(matrix[0])
rotated = [[0 for x in range(width)] for y in range(height)]
for y in range(height):
for x in range(width):
rotated[x][height - 1 - y] = matrix[y][x]
for y in range(height):
for x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""... | stack_v2_sparse_classes_75kplus_train_065233 | 1,234 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix: 'List[List[int]]') -> 'None'"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "ro... | 2 | stack_v2_sparse_classes_30k_train_003270 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: 'List[List[int]]') -> 'None': Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: v... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: 'List[List[int]]') -> 'None': Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: v... | ae8bb8bf4ae4026ccaf1dce323b4098547dd35ec | <|skeleton|>
class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
height = len(matrix)
width = len(matrix[0])
rotated = [[0 for x in range(width)] for y in range(height)]
for y in range(height):
fo... | the_stack_v2_python_sparse | leet_code/48_Rotate_Image.py | roiei/algo | train | 0 | |
fc2aeabca5ab13924be1b872d7ec6d03e207b1df | [
"super(CategoricalDist, self).__init__(input_size=input_size, output_size=output_size, hidden_sizes=hidden_sizes, hidden_activation=hidden_activation, use_output_layer=False)\nin_size = hidden_sizes[-1]\nself.last_layer = nn.Linear(in_size, output_size)\nself.last_layer = init_fn(self.last_layer)",
"hidden = supe... | <|body_start_0|>
super(CategoricalDist, self).__init__(input_size=input_size, output_size=output_size, hidden_sizes=hidden_sizes, hidden_activation=hidden_activation, use_output_layer=False)
in_size = hidden_sizes[-1]
self.last_layer = nn.Linear(in_size, output_size)
self.last_layer = in... | Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax | CategoricalDist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoricalDist:
"""Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax"""
def __init__(self, input_size, output_size, hidden_sizes, hidden_activation=torch.relu, init_fn=init_layer_uniform):
"... | stack_v2_sparse_classes_75kplus_train_065234 | 10,144 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, input_size, output_size, hidden_sizes, hidden_activation=torch.relu, init_fn=init_layer_uniform)"
},
{
"docstring": "Forward method implementation.",
"name": "forward",
"signature": "def forward(self, x)"
... | 2 | stack_v2_sparse_classes_30k_train_000042 | Implement the Python class `CategoricalDist` described below.
Class description:
Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_sizes, ... | Implement the Python class `CategoricalDist` described below.
Class description:
Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_sizes, ... | 2d70d4792e78ceefd4626302fa85e7774e2ff250 | <|skeleton|>
class CategoricalDist:
"""Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax"""
def __init__(self, input_size, output_size, hidden_sizes, hidden_activation=torch.relu, init_fn=init_layer_uniform):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoricalDist:
"""Multilayer perceptron with categorical distribution output (for discrete domains) Attributes: last_layer (nn.Linear): output layer for softmax"""
def __init__(self, input_size, output_size, hidden_sizes, hidden_activation=torch.relu, init_fn=init_layer_uniform):
"""Initialize.... | the_stack_v2_python_sparse | src/SDRL_Project/learning_agents/architectures/mlp.py | sbhambr1/symbolic_planning_and_rl | train | 0 |
829f3763db197ec7a84adff17d5e853293cdf327 | [
"if frame.name == self.name:\n raise ValueError('Cannot connect to a frame with the same name.')\nself._connected_frames[frame.name] = transformation_to_frame.inverse\nframe._connected_frames[self.name] = transformation_to_frame",
"if not hasattr(geom_obj, '_frame'):\n raise ValueError('Cannot transform obj... | <|body_start_0|>
if frame.name == self.name:
raise ValueError('Cannot connect to a frame with the same name.')
self._connected_frames[frame.name] = transformation_to_frame.inverse
frame._connected_frames[self.name] = transformation_to_frame
<|end_body_0|>
<|body_start_1|>
if... | Frame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
<|body_0|>
def __call__(self, geom_obj):
"""Calling an instance... | stack_v2_sparse_classes_75kplus_train_065235 | 2,578 | permissive | [
{
"docstring": "Connect this frame to another frame through a transformation. This also connects the other frame to this one.",
"name": "connect_to",
"signature": "def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType)"
},
{
"docstring": "Calling an instance transforms t... | 2 | stack_v2_sparse_classes_30k_train_054664 | Implement the Python class `Frame` described below.
Class description:
Implement the Frame class.
Method signatures and docstrings:
- def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType): Connect this frame to another frame through a transformation. This also connects the other frame to thi... | Implement the Python class `Frame` described below.
Class description:
Implement the Frame class.
Method signatures and docstrings:
- def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType): Connect this frame to another frame through a transformation. This also connects the other frame to thi... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
<|body_0|>
def __call__(self, geom_obj):
"""Calling an instance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Frame:
def connect_to(self, frame: 'Frame', *, transformation_to_frame: TransformType):
"""Connect this frame to another frame through a transformation. This also connects the other frame to this one."""
if frame.name == self.name:
raise ValueError('Cannot connect to a frame with t... | the_stack_v2_python_sparse | simulation/utils/geometry/frame.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 | |
a226ac26d353ffc140c0d5c0e6f4f124ba8fb790 | [
"self.ax_kw.update(kwargs)\nDynaPlotBackTest.__init__(self, fig=fig, ax=ax, size=size, **self.ax_kw)\nself.set_axes()\nself.ax2 = self.ax.twinx()",
"if clear:\n self.clear()\n self.ax2.clear()\nself.h_test = self.ax.plot(test, **self.test_plot_kw)\nself.h_eval = self.ax2.plot(eval, **self.eval_plot_kw)\nsel... | <|body_start_0|>
self.ax_kw.update(kwargs)
DynaPlotBackTest.__init__(self, fig=fig, ax=ax, size=size, **self.ax_kw)
self.set_axes()
self.ax2 = self.ax.twinx()
<|end_body_0|>
<|body_start_1|>
if clear:
self.clear()
self.ax2.clear()
self.h_test = se... | Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing title, ylabel, xlabel, yscale, xscale and ticks_params. Methods ------- plot set_... | DynaPlotPerf | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynaPlotPerf:
"""Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing title, ylabel, xlabel, yscale, xscale and... | stack_v2_sparse_classes_75kplus_train_065236 | 21,693 | permissive | [
{
"docstring": "Initialize method. Parameters ---------- fig : matplotlib.figure.Figure, optional Figure to display backtest. ax : matplotlib.axes, optional Axe(s) to display a part of backtest. size : tuple, optional Size of figure, default is (9, 6) kwargs : dict, optional Axes configuration, cf matplotlib do... | 3 | stack_v2_sparse_classes_30k_train_043270 | Implement the Python class `DynaPlotPerf` described below.
Class description:
Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing ti... | Implement the Python class `DynaPlotPerf` described below.
Class description:
Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing ti... | b7e9bfce52fc5d732f340348945bde3b514f5a3a | <|skeleton|>
class DynaPlotPerf:
"""Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing title, ylabel, xlabel, yscale, xscale and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynaPlotPerf:
"""Plot dynamically the performance values. Attributes ---------- fig : matplotlib.figure.Figure Figure to display backtest. ax : matplotlib.axes Axe(s) to display a part of backtest. ax_kwargs : dict Parameters of matplotlib axes containing title, ylabel, xlabel, yscale, xscale and ticks_params... | the_stack_v2_python_sparse | fynance/backtest/dynamic_plot_backtest.py | ArthurBernard/Fynance | train | 22 |
6be942a6cd1f69303b7b7ddb135ac620b5ebdb07 | [
"logging.info('Get cookies from Google Chrome')\ntry:\n return browser_cookie3.chrome()\nexcept:\n return None",
"logging.info('Check html page is MyDTU home page is not.')\nsoup = BeautifulSoup(html, 'lxml')\nnameStudent = soup.find(class_='hello man')\nif nameStudent:\n return True\nreturn False",
"l... | <|body_start_0|>
logging.info('Get cookies from Google Chrome')
try:
return browser_cookie3.chrome()
except:
return None
<|end_body_0|>
<|body_start_1|>
logging.info('Check html page is MyDTU home page is not.')
soup = BeautifulSoup(html, 'lxml')
... | Yêu cầu: Google Chrome được cài đặt trên máy tính. | DTULogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTULogin:
"""Yêu cầu: Google Chrome được cài đặt trên máy tính."""
def getCookiesFromChrome(self):
"""Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None."""
<|body_0|>
def isHomePageDTU(html: str) -> bool:
... | stack_v2_sparse_classes_75kplus_train_065237 | 3,856 | permissive | [
{
"docstring": "Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None.",
"name": "getCookiesFromChrome",
"signature": "def getCookiesFromChrome(self)"
},
{
"docstring": "Kiểm tra HTML doc truyền vào có phải là trang chủ sau khi đăng nhập của ... | 5 | stack_v2_sparse_classes_30k_train_023085 | Implement the Python class `DTULogin` described below.
Class description:
Yêu cầu: Google Chrome được cài đặt trên máy tính.
Method signatures and docstrings:
- def getCookiesFromChrome(self): Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None.
- def isHomePage... | Implement the Python class `DTULogin` described below.
Class description:
Yêu cầu: Google Chrome được cài đặt trên máy tính.
Method signatures and docstrings:
- def getCookiesFromChrome(self): Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None.
- def isHomePage... | 930d9e38299011677018d4479f525bd3cd39062a | <|skeleton|>
class DTULogin:
"""Yêu cầu: Google Chrome được cài đặt trên máy tính."""
def getCookiesFromChrome(self):
"""Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None."""
<|body_0|>
def isHomePageDTU(html: str) -> bool:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DTULogin:
"""Yêu cầu: Google Chrome được cài đặt trên máy tính."""
def getCookiesFromChrome(self):
"""Trả về cookies của Google Chrome trong máy tính. Nếu Google Chrome chưa được cài đặt trong máy, trả về None."""
logging.info('Get cookies from Google Chrome')
try:
ret... | the_stack_v2_python_sparse | class_DTUWeb.py | lucid-irl/DTU-Universe | train | 2 |
10cdd2a874774e967570233501f23654b9679002 | [
"super(Sfc5xxxCalibrationConditions, self).__init__()\nself.company = company\nself.operator = operator\nself.datetime = datetime\nself.temperature = temperature\nself.inlet_pressure = inlet_pressure\nself.differential_pressure = differential_pressure\nself.is_real_gas_calibration = is_real_gas_calibration\nself.ac... | <|body_start_0|>
super(Sfc5xxxCalibrationConditions, self).__init__()
self.company = company
self.operator = operator
self.datetime = datetime
self.temperature = temperature
self.inlet_pressure = inlet_pressure
self.differential_pressure = differential_pressure
... | A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access directly. | Sfc5xxxCalibrationConditions | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sfc5xxxCalibrationConditions:
"""A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access directly."""
def __init__(self, c... | stack_v2_sparse_classes_75kplus_train_065238 | 6,738 | permissive | [
{
"docstring": "Constructor. :param str company: The company which has created the calibration. :param str operator: The operator who has created the calibration. :param ~datetime.datetime datetime: Date and time when the calibration was created. :param float temperature: System/gas temperature [°C]. :param flo... | 2 | stack_v2_sparse_classes_30k_train_028201 | Implement the Python class `Sfc5xxxCalibrationConditions` described below.
Class description:
A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access... | Implement the Python class `Sfc5xxxCalibrationConditions` described below.
Class description:
A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access... | f9bd288a996ad969ee5bbb7f52b6e8f00fdf47e5 | <|skeleton|>
class Sfc5xxxCalibrationConditions:
"""A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access directly."""
def __init__(self, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sfc5xxxCalibrationConditions:
"""A class representing the calibration condition parameters as used to store the initial calibration conditions and recalibration conditions of gas calibration blocks. The class provides some public members which you can access directly."""
def __init__(self, company, opera... | the_stack_v2_python_sparse | sensirion_shdlc_sfc5xxx/types.py | Sensirion/python-shdlc-sfc5xxx | train | 0 |
f7a53e95f6ab52aa728f14b817fcb6050be010a6 | [
"self.phase = phase\nself.args = args\n_log.debug(f'BaseDataset <Initialized: phase={phase}>')",
"params = {'pin_memory': True, 'shuffle': self.phase == 'train' if self.phase else False, 'batch_size': self.args.batch_size if self.args else 0, 'num_workers': self.args.worker if self.args else 0}\nparams.update(kwa... | <|body_start_0|>
self.phase = phase
self.args = args
_log.debug(f'BaseDataset <Initialized: phase={phase}>')
<|end_body_0|>
<|body_start_1|>
params = {'pin_memory': True, 'shuffle': self.phase == 'train' if self.phase else False, 'batch_size': self.args.batch_size if self.args else 0, '... | BaseDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDataset:
def __init__(self, phase=None, args=None):
"""Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace): parsed arguments from onegan.option.Parser"""
<|body_0|>
def to_loader(self, **kwargs)... | stack_v2_sparse_classes_75kplus_train_065239 | 1,821 | permissive | [
{
"docstring": "Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace): parsed arguments from onegan.option.Parser",
"name": "__init__",
"signature": "def __init__(self, phase=None, args=None)"
},
{
"docstring": "Dispatch ... | 2 | stack_v2_sparse_classes_30k_train_000333 | Implement the Python class `BaseDataset` described below.
Class description:
Implement the BaseDataset class.
Method signatures and docstrings:
- def __init__(self, phase=None, args=None): Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace):... | Implement the Python class `BaseDataset` described below.
Class description:
Implement the BaseDataset class.
Method signatures and docstrings:
- def __init__(self, phase=None, args=None): Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace):... | 9214c4e04e532067fc149299b51f401bbbe365db | <|skeleton|>
class BaseDataset:
def __init__(self, phase=None, args=None):
"""Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace): parsed arguments from onegan.option.Parser"""
<|body_0|>
def to_loader(self, **kwargs)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseDataset:
def __init__(self, phase=None, args=None):
"""Base dataset with to_loader method Args: phase (str): should be `train` or `val` to indicate the phase args (argparse.Namespace): parsed arguments from onegan.option.Parser"""
self.phase = phase
self.args = args
_log.de... | the_stack_v2_python_sparse | onegan/io/loader.py | amitbend/lsun-room-dsc | train | 0 | |
d75117ee13a2ceb6cf203ef7bf7e4c97c0fd8c4a | [
"if p and q:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\nreturn p is q",
"def isSame(r1, r2):\n \"\"\"\n ret: True, same, False, not same.\n \"\"\"\n if r1 and r2:\n if r1.val != r2.val:\n return False\n ... | <|body_start_0|>
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
<|end_body_0|>
<|body_start_1|>
def isSame(r1, r2):
"""
ret: True, same, False, not same.
""... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def rewrite(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if p and q:
... | stack_v2_sparse_classes_75kplus_train_065240 | 2,427 | no_license | [
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "rewrite",
"signature": "def rewrite(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020042 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def rewrite(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def rewrite(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class Solut... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def rewrite(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
def rewrite(self, p, q):
""":type p: TreeNode ... | the_stack_v2_python_sparse | depth-first-search/100_Same_Tree.py | vsdrun/lc_public | train | 6 | |
86ca4b36b803bf5cc2e006b88c9829c0cf702023 | [
"with self.distribute_strategy.scope():\n self._validate_compile(optimizer, metrics, **kwargs)\n self._run_eagerly = run_eagerly\n self.optimizer = self._get_optimizer(optimizer)\n custom_loss_copy = custom_loss.copy()\n if custom_loss is not None:\n if not isinstance(custom_loss, dict):\n ... | <|body_start_0|>
with self.distribute_strategy.scope():
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
custom_loss_copy = custom_loss.copy()
if custom_loss is not Non... | LegacyModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyModel:
def compile2(self, optimizer='rmsprop', loss=None, custom_loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, **kwargs):
"""Configures the model for training. Arguments: optimizer: String (name of optimizer) or optimizer instance. See `tf.ker... | stack_v2_sparse_classes_75kplus_train_065241 | 8,607 | permissive | [
{
"docstring": "Configures the model for training. Arguments: optimizer: String (name of optimizer) or optimizer instance. See `tf.keras.optimizers`. loss: String (name of objective function), objective function or `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective function is any callable wit... | 4 | stack_v2_sparse_classes_30k_train_032005 | Implement the Python class `LegacyModel` described below.
Class description:
Implement the LegacyModel class.
Method signatures and docstrings:
- def compile2(self, optimizer='rmsprop', loss=None, custom_loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, **kwargs): Configures the mod... | Implement the Python class `LegacyModel` described below.
Class description:
Implement the LegacyModel class.
Method signatures and docstrings:
- def compile2(self, optimizer='rmsprop', loss=None, custom_loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, **kwargs): Configures the mod... | f26d440a4de0557e0e481279bfd70a732aaa8825 | <|skeleton|>
class LegacyModel:
def compile2(self, optimizer='rmsprop', loss=None, custom_loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, **kwargs):
"""Configures the model for training. Arguments: optimizer: String (name of optimizer) or optimizer instance. See `tf.ker... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LegacyModel:
def compile2(self, optimizer='rmsprop', loss=None, custom_loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, **kwargs):
"""Configures the model for training. Arguments: optimizer: String (name of optimizer) or optimizer instance. See `tf.keras.optimizers`... | the_stack_v2_python_sparse | src/tf_transformers/core/legacy_model.py | Vibha111094/tf-transformers | train | 1 | |
76f32816b81a2645b48c5f143d13198f86ec11e7 | [
"try:\n return int(value)\nexcept ValueError:\n raise ValueError('Attempted to set value for an %s field which is not compatible: %s' % (self.typeName(), repr(value)))",
"if isinstance(value, int):\n return 1\nreturn 0",
"try:\n return str(int(value))\nexcept OverflowError:\n base = str(value)\n ... | <|body_start_0|>
try:
return int(value)
except ValueError:
raise ValueError('Attempted to set value for an %s field which is not compatible: %s' % (self.typeName(), repr(value)))
<|end_body_0|>
<|body_start_1|>
if isinstance(value, int):
return 1
retu... | SFInt32 field/event type base-class | _SFInt32 | [
"GPL-1.0-or-later",
"MIT",
"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 _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
<|body_0|>
def check(self, value):
"""Check that the given value is of exactly expected type... | stack_v2_sparse_classes_75kplus_train_065242 | 34,853 | permissive | [
{
"docstring": "Coerce the given value to our type Allowable types: any object with true/false protocol",
"name": "coerce",
"signature": "def coerce(self, value)"
},
{
"docstring": "Check that the given value is of exactly expected type",
"name": "check",
"signature": "def check(self, va... | 3 | stack_v2_sparse_classes_30k_train_003486 | Implement the Python class `_SFInt32` described below.
Class description:
SFInt32 field/event type base-class
Method signatures and docstrings:
- def coerce(self, value): Coerce the given value to our type Allowable types: any object with true/false protocol
- def check(self, value): Check that the given value is of ... | Implement the Python class `_SFInt32` described below.
Class description:
SFInt32 field/event type base-class
Method signatures and docstrings:
- def coerce(self, value): Coerce the given value to our type Allowable types: any object with true/false protocol
- def check(self, value): Check that the given value is of ... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
<|body_0|>
def check(self, value):
"""Check that the given value is of exactly expected type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
try:
return int(value)
except ValueError:
raise ValueError('Attempted to set value for... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/vrml/fieldtypes.py | alexus37/AugmentedRealityChess | train | 1 |
f481fa590d36066166dbbd6871387fe48d7cf3ca | [
"res = self.create_residual(data, model, nbins=nbins, calcphi=calcphi, skipzero=skipzero)\nSingleHistBase.__init__(self, res, 'angularRes', fill, workinprogress)\nself._xtitle = '#phi [rad]'\nself._ytitle = 'Pull'",
"if nbins is None:\n nbins = data.GetXaxis().GetNbins()\nif calcphi is None:\n calcphi = lam... | <|body_start_0|>
res = self.create_residual(data, model, nbins=nbins, calcphi=calcphi, skipzero=skipzero)
SingleHistBase.__init__(self, res, 'angularRes', fill, workinprogress)
self._xtitle = '#phi [rad]'
self._ytitle = 'Pull'
<|end_body_0|>
<|body_start_1|>
if nbins is None:
... | Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins. | AngularResidualPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AngularResidualPlot:
"""Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, calcphi=None, skipzero=False, fill=4954, workinprogress=False):
"""Project residual h... | stack_v2_sparse_classes_75kplus_train_065243 | 8,137 | no_license | [
{
"docstring": "Project residual histogram to one-dimensional plot.",
"name": "__init__",
"signature": "def __init__(self, data, model, nbins=None, calcphi=None, skipzero=False, fill=4954, workinprogress=False)"
},
{
"docstring": "Create angular residual histogram.",
"name": "create_residual... | 3 | stack_v2_sparse_classes_30k_train_008089 | Implement the Python class `AngularResidualPlot` described below.
Class description:
Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins.
Method signatures and docstrings:
- def __init__(self, data, model, nbins=None, calcphi=None, skipzero=Fa... | Implement the Python class `AngularResidualPlot` described below.
Class description:
Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins.
Method signatures and docstrings:
- def __init__(self, data, model, nbins=None, calcphi=None, skipzero=Fa... | 8eed4783e17226fd026e74e7a95c77ae88b63162 | <|skeleton|>
class AngularResidualPlot:
"""Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, calcphi=None, skipzero=False, fill=4954, workinprogress=False):
"""Project residual h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AngularResidualPlot:
"""Plot residuals projected to one angular dimension. __init__: Initialize. chisq: Return the chi-squared summed over radial bins."""
def __init__(self, data, model, nbins=None, calcphi=None, skipzero=False, fill=4954, workinprogress=False):
"""Project residual histogram to o... | the_stack_v2_python_sparse | lib/plot/residual.py | knollejo/BeamImagingAnalysis | train | 0 |
6f486f4ab46ccf2af6904f2b9c05f7314c2d73f6 | [
"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... | EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s). | EventListenerServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1... | stack_v2_sparse_classes_75kplus_train_065244 | 4,141 | permissive | [
{
"docstring": "Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediate tensors from a debugged graph being executed, which can be sent from DebugIdentity ops configured with grpc URLs. 2) GraphDefs of partition graphs, which can b... | 3 | stack_v2_sparse_classes_30k_train_038867 | Implement the Python class `EventListenerServicer` described below.
Class description:
EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).
Method signatures and docstrings:
- def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event... | Implement the Python class `EventListenerServicer` described below.
Class description:
EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).
Method signatures and docstrings:
- def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediat... | the_stack_v2_python_sparse | Keras_tensorflow_nightly/source2.7/tensorflow/core/debug/debug_service_pb2_grpc.py | ryfeus/lambda-packs | train | 1,283 |
634378481c29fdfb7f88b9a40665ae45694634af | [
"start_date = date.today()\nexp_date = date.today() + timedelta(days=30)\ne = Employee(first_name='John', last_name='Gamlet', email='gamlet@example.com', contract_start_date=start_date, contract_exp_date=exp_date)\nself.assertEqual(e.full_name(), 'Gamlet John')",
"start_date = date.today()\nexp_date = date.today(... | <|body_start_0|>
start_date = date.today()
exp_date = date.today() + timedelta(days=30)
e = Employee(first_name='John', last_name='Gamlet', email='gamlet@example.com', contract_start_date=start_date, contract_exp_date=exp_date)
self.assertEqual(e.full_name(), 'Gamlet John')
<|end_body_0|... | EmployeeMethodTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
<|body_0|>
def test_create_new_employee_with_empty_attributes(self):
"""saving employee without all required data should ... | stack_v2_sparse_classes_75kplus_train_065245 | 27,946 | no_license | [
{
"docstring": "the full_name method should return joined (' ') first_name and last_name",
"name": "test_full_name_with_valid_employee",
"signature": "def test_full_name_with_valid_employee(self)"
},
{
"docstring": "saving employee without all required data should be aborted",
"name": "test_... | 2 | stack_v2_sparse_classes_30k_train_054098 | Implement the Python class `EmployeeMethodTests` described below.
Class description:
Implement the EmployeeMethodTests class.
Method signatures and docstrings:
- def test_full_name_with_valid_employee(self): the full_name method should return joined (' ') first_name and last_name
- def test_create_new_employee_with_e... | Implement the Python class `EmployeeMethodTests` described below.
Class description:
Implement the EmployeeMethodTests class.
Method signatures and docstrings:
- def test_full_name_with_valid_employee(self): the full_name method should return joined (' ') first_name and last_name
- def test_create_new_employee_with_e... | aa82ab2cb219617c1fa9a18970b2a4d27c573191 | <|skeleton|>
class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
<|body_0|>
def test_create_new_employee_with_empty_attributes(self):
"""saving employee without all required data should ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmployeeMethodTests:
def test_full_name_with_valid_employee(self):
"""the full_name method should return joined (' ') first_name and last_name"""
start_date = date.today()
exp_date = date.today() + timedelta(days=30)
e = Employee(first_name='John', last_name='Gamlet', email='ga... | the_stack_v2_python_sparse | employees/tests.py | Code-Poets/polish-lody | train | 0 | |
7aa0653bafc11b065bb47d21a55d0c4e8f3ba002 | [
"def find(parent, i):\n \"\"\"\n find the \"root\" node which is connected to i\n \"\"\"\n while parent[i] != i:\n i = parent[i]\n return parent[i]\nN = len(edges)\nparent = [0] * (N + 1)\nA, B = ([], [])\nfor i in range(N):\n u, v = edges[i]\n if parent[v] == 0:\n ... | <|body_start_0|>
def find(parent, i):
"""
find the "root" node which is connected to i
"""
while parent[i] != i:
i = parent[i]
return parent[i]
N = len(edges)
parent = [0] * (N + 1)
A, B = ([], []... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRedundantDirectedConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantDirectedConnection2(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_065246 | 7,752 | no_license | [
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantDirectedConnection",
"signature": "def findRedundantDirectedConnection(self, edges)"
},
{
"docstring": ":type edges: List[List[int]] :rtype: List[int]",
"name": "findRedundantDirectedConnection2",
"sig... | 2 | stack_v2_sparse_classes_30k_train_018547 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantDirectedConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantDirectedConnection2(self, edges): :type edges: List[List[int]]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRedundantDirectedConnection(self, edges): :type edges: List[List[int]] :rtype: List[int]
- def findRedundantDirectedConnection2(self, edges): :type edges: List[List[int]]... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def findRedundantDirectedConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findRedundantDirectedConnection2(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findRedundantDirectedConnection(self, edges):
""":type edges: List[List[int]] :rtype: List[int]"""
def find(parent, i):
"""
find the "root" node which is connected to i
"""
while parent[i] != i:
i = p... | the_stack_v2_python_sparse | code685RedundantConnectionII.py | cybelewang/leetcode-python | train | 0 | |
2373044a9e7cddcff1bd79b34500cc44ae84909b | [
"def isPalindrome(i, j) -> bool:\n return s[i:j + 1] == s[i:j + 1][::-1]\ni = 0\ncount = 0\nslen = len(s)\nwhile i < slen:\n j = slen - 1\n while j >= i:\n if isPalindrome(i, j):\n count += 1\n j -= 1\n i += 1\nreturn count",
"count = 0\nslen = len(s)\ni = 0\n\ndef isPalin(i, ... | <|body_start_0|>
def isPalindrome(i, j) -> bool:
return s[i:j + 1] == s[i:j + 1][::-1]
i = 0
count = 0
slen = len(s)
while i < slen:
j = slen - 1
while j >= i:
if isPalindrome(i, j):
count += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubString(self, s) -> int:
""":type s: String :return: int"""
<|body_0|>
def countString2(self, s):
"""while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i.... | stack_v2_sparse_classes_75kplus_train_065247 | 1,558 | no_license | [
{
"docstring": ":type s: String :return: int",
"name": "countSubString",
"signature": "def countSubString(self, s) -> int"
},
{
"docstring": "while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i.e s[i:j] ... | 2 | stack_v2_sparse_classes_30k_train_014242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubString(self, s) -> int: :type s: String :return: int
- def countString2(self, s): while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubString(self, s) -> int: :type s: String :return: int
- def countString2(self, s): while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i ... | e3e076206b34ff6edf00596a03bc2b5911051cd8 | <|skeleton|>
class Solution:
def countSubString(self, s) -> int:
""":type s: String :return: int"""
<|body_0|>
def countString2(self, s):
"""while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countSubString(self, s) -> int:
""":type s: String :return: int"""
def isPalindrome(i, j) -> bool:
return s[i:j + 1] == s[i:j + 1][::-1]
i = 0
count = 0
slen = len(s)
while i < slen:
j = slen - 1
while j >= i:
... | the_stack_v2_python_sparse | Code/DataStructures/python/leetcode_ds/Py_PalindromicSubstrings_1.py | karanalang/technology | train | 0 | |
fbd7a6a0a7cb8b31348ab41c375ec0098f7a6aff | [
"super(CtrTrainerCallback, self).__init__()\nself.best_score = 0\nlogging.info('init autogate s1 trainer callback')",
"self.model = self.trainer.model\nfeature_interaction_score = self.model.get_feature_interaction_score()\nprint('get feature_interaction_score', feature_interaction_score)\ncurr_auc = float(self.t... | <|body_start_0|>
super(CtrTrainerCallback, self).__init__()
self.best_score = 0
logging.info('init autogate s1 trainer callback')
<|end_body_0|>
<|body_start_1|>
self.model = self.trainer.model
feature_interaction_score = self.model.get_feature_interaction_score()
print(... | AutoGateS1TrainerCallback module. | AutoGateS1TrainerCallback | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoGateS1TrainerCallback:
"""AutoGateS1TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS1TrainerCallback class."""
<|body_0|>
def after_valid(self, logs=None):
"""Call after_valid of the managed callbacks."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_065248 | 1,993 | permissive | [
{
"docstring": "Construct AutoGateS1TrainerCallback class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call after_valid of the managed callbacks.",
"name": "after_valid",
"signature": "def after_valid(self, logs=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002683 | Implement the Python class `AutoGateS1TrainerCallback` described below.
Class description:
AutoGateS1TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS1TrainerCallback class.
- def after_valid(self, logs=None): Call after_valid of the managed callbacks. | Implement the Python class `AutoGateS1TrainerCallback` described below.
Class description:
AutoGateS1TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS1TrainerCallback class.
- def after_valid(self, logs=None): Call after_valid of the managed callbacks.
<|skeleton|>
c... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class AutoGateS1TrainerCallback:
"""AutoGateS1TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS1TrainerCallback class."""
<|body_0|>
def after_valid(self, logs=None):
"""Call after_valid of the managed callbacks."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoGateS1TrainerCallback:
"""AutoGateS1TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS1TrainerCallback class."""
super(CtrTrainerCallback, self).__init__()
self.best_score = 0
logging.info('init autogate s1 trainer callback')
def after_valid(sel... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/algorithms/nas/fis/autogate_s1_trainer_callback.py | Huawei-Ascend/modelzoo | train | 1 |
15a8faea643011472c446cfaae6fb06ba43d6b87 | [
"hops = validated_data.pop('recipe_hops')\nmalts = validated_data.pop('recipe_malts')\nuser = validated_data.pop('user')\nreturn Recipe.objects.create_recipe(user, validated_data, malts, hops)",
"instance.recipe_name = validated_data.get('recipe_name', instance.recipe_name)\ninstance.recipe_style = validated_data... | <|body_start_0|>
hops = validated_data.pop('recipe_hops')
malts = validated_data.pop('recipe_malts')
user = validated_data.pop('user')
return Recipe.objects.create_recipe(user, validated_data, malts, hops)
<|end_body_0|>
<|body_start_1|>
instance.recipe_name = validated_data.get... | Serialization class for all your yummy recipes. | RecipeSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeSerializer:
"""Serialization class for all your yummy recipes."""
def create(self, validated_data):
"""Create the recipe and all related data"""
<|body_0|>
def update(self, instance, validated_data):
"""Update a recipe. This will clear all previous malts/ho... | stack_v2_sparse_classes_75kplus_train_065249 | 3,077 | permissive | [
{
"docstring": "Create the recipe and all related data",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update a recipe. This will clear all previous malts/hops and replace them with a new list",
"name": "update",
"signature": "def update(self, insta... | 2 | stack_v2_sparse_classes_30k_train_029744 | Implement the Python class `RecipeSerializer` described below.
Class description:
Serialization class for all your yummy recipes.
Method signatures and docstrings:
- def create(self, validated_data): Create the recipe and all related data
- def update(self, instance, validated_data): Update a recipe. This will clear ... | Implement the Python class `RecipeSerializer` described below.
Class description:
Serialization class for all your yummy recipes.
Method signatures and docstrings:
- def create(self, validated_data): Create the recipe and all related data
- def update(self, instance, validated_data): Update a recipe. This will clear ... | 6d0a31f021755425d420394d84aa7250f86f5ebe | <|skeleton|>
class RecipeSerializer:
"""Serialization class for all your yummy recipes."""
def create(self, validated_data):
"""Create the recipe and all related data"""
<|body_0|>
def update(self, instance, validated_data):
"""Update a recipe. This will clear all previous malts/ho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecipeSerializer:
"""Serialization class for all your yummy recipes."""
def create(self, validated_data):
"""Create the recipe and all related data"""
hops = validated_data.pop('recipe_hops')
malts = validated_data.pop('recipe_malts')
user = validated_data.pop('user')
... | the_stack_v2_python_sparse | brew_journal/recipies/serializers.py | moonboy13/brew-journal | train | 0 |
50d98101dde7ef8c3e746f6611041c3134fcc7d8 | [
"if isinstance(tag, six.integer_types):\n try:\n tag = Tag.objects.get(pk=tag, owner=self.owner)\n except Tag.DoesNotExist:\n return\nif isinstance(tag, six.string_types):\n tname = tag\n try:\n tag = Tag(owner=self.owner, name=tag)\n tag.save()\n except IntegrityError:\n ... | <|body_start_0|>
if isinstance(tag, six.integer_types):
try:
tag = Tag.objects.get(pk=tag, owner=self.owner)
except Tag.DoesNotExist:
return
if isinstance(tag, six.string_types):
tname = tag
try:
tag = Tag(ow... | Base class for taggable models; anything taggable must extend this | Taggable | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
<|body_0|>
def untag(self, tag):
"""Untags this object from a tag s... | stack_v2_sparse_classes_75kplus_train_065250 | 10,108 | permissive | [
{
"docstring": "Tags this object with a tag specified by a tag name, primary key or Tag model instance",
"name": "tag",
"signature": "def tag(self, tag)"
},
{
"docstring": "Untags this object from a tag specified by a tag name, primary key or Tag model instance",
"name": "untag",
"signat... | 3 | stack_v2_sparse_classes_30k_train_001021 | Implement the Python class `Taggable` described below.
Class description:
Base class for taggable models; anything taggable must extend this
Method signatures and docstrings:
- def tag(self, tag): Tags this object with a tag specified by a tag name, primary key or Tag model instance
- def untag(self, tag): Untags thi... | Implement the Python class `Taggable` described below.
Class description:
Base class for taggable models; anything taggable must extend this
Method signatures and docstrings:
- def tag(self, tag): Tags this object with a tag specified by a tag name, primary key or Tag model instance
- def untag(self, tag): Untags thi... | 5e102935cc6166f4d8ea13051769787c47303153 | <|skeleton|>
class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
<|body_0|>
def untag(self, tag):
"""Untags this object from a tag s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Taggable:
"""Base class for taggable models; anything taggable must extend this"""
def tag(self, tag):
"""Tags this object with a tag specified by a tag name, primary key or Tag model instance"""
if isinstance(tag, six.integer_types):
try:
tag = Tag.objects.get... | the_stack_v2_python_sparse | tags/models.py | RossBrunton/BMAT | train | 0 |
27751d2dbeaea06757ec8817dd0759515772b941 | [
"task_args_json = '' if task_args is None else json.dumps(task_args)\njob = self.create(task_type=task_type, task_args_json=task_args_json)\nreturn job",
"job = self.create_job(task_type, task_args)\ngetQueue(queue_name).send_message(job.create_json_message())\nreturn job"
] | <|body_start_0|>
task_args_json = '' if task_args is None else json.dumps(task_args)
job = self.create(task_type=task_type, task_args_json=task_args_json)
return job
<|end_body_0|>
<|body_start_1|>
job = self.create_job(task_type, task_args)
getQueue(queue_name).send_message(job... | Adds job-specific convenience methods to the default Django Manager. | JobManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobManager:
"""Adds job-specific convenience methods to the default Django Manager."""
def create_job(self, task_type, task_args):
"""Creates a job. :param task_type: A string identifying the type of task to carry out. :param task_args: An object defining the task's input arguments. ... | stack_v2_sparse_classes_75kplus_train_065251 | 9,472 | permissive | [
{
"docstring": "Creates a job. :param task_type: A string identifying the type of task to carry out. :param task_args: An object defining the task's input arguments. The object must allow serialization to a JSON string using `json.dumps(obj)`. A None value is acceptable if the task requires no input arguments."... | 2 | null | Implement the Python class `JobManager` described below.
Class description:
Adds job-specific convenience methods to the default Django Manager.
Method signatures and docstrings:
- def create_job(self, task_type, task_args): Creates a job. :param task_type: A string identifying the type of task to carry out. :param t... | Implement the Python class `JobManager` described below.
Class description:
Adds job-specific convenience methods to the default Django Manager.
Method signatures and docstrings:
- def create_job(self, task_type, task_args): Creates a job. :param task_type: A string identifying the type of task to carry out. :param t... | a3e12648ea80e23f21938103d41d70eb0917d833 | <|skeleton|>
class JobManager:
"""Adds job-specific convenience methods to the default Django Manager."""
def create_job(self, task_type, task_args):
"""Creates a job. :param task_type: A string identifying the type of task to carry out. :param task_args: An object defining the task's input arguments. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobManager:
"""Adds job-specific convenience methods to the default Django Manager."""
def create_job(self, task_type, task_args):
"""Creates a job. :param task_type: A string identifying the type of task to carry out. :param task_args: An object defining the task's input arguments. The object mu... | the_stack_v2_python_sparse | codalab/apps/jobs/models.py | codalab/codalab-competitions | train | 425 |
3efc1a7c3f80be90d4ea2fa2345cdbad7fca04f0 | [
"if n == 1:\n return ['()']\ndiagram = ['(){}', '{}()', '({})']\ngraph = self.generateParenthesis(n - 1)\nresult = set()\nfor g in graph:\n for dia in diagram:\n result.add(dia.format(g))\nreturn sorted(result)",
"if n == 1:\n return ['()']\nresult = set()\ngraph = self.generateParenthesis(n - 1)\... | <|body_start_0|>
if n == 1:
return ['()']
diagram = ['(){}', '{}()', '({})']
graph = self.generateParenthesis(n - 1)
result = set()
for g in graph:
for dia in diagram:
result.add(dia.format(g))
return sorted(result)
<|end_body_0|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1:
return ['()']
... | stack_v2_sparse_classes_75kplus_train_065252 | 1,798 | permissive | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "_generateParenthesis",
"signature": "def _generateParenthesis(self, n)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052414 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Solution:
def _gener... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
if n == 1:
return ['()']
diagram = ['(){}', '{}()', '({})']
graph = self.generateParenthesis(n - 1)
result = set()
for g in graph:
for dia in diagram:
... | the_stack_v2_python_sparse | 22.generate-parentheses.py | windard/leeeeee | train | 0 | |
1828828acc0498907dd5c9b7757f98272917bead | [
"currencies_list = DB_crypto_currencies().select_check_currencies_for_exchange_id(exchange_id)\nif currency_types['currency_in_crypto'] == False:\n if json['currency_out'] not in currencies_list:\n return ({'message': 'Crypto currency_out doesnt exist in exchange_id: '.format(exchange_id)}, 400)\n bala... | <|body_start_0|>
currencies_list = DB_crypto_currencies().select_check_currencies_for_exchange_id(exchange_id)
if currency_types['currency_in_crypto'] == False:
if json['currency_out'] not in currencies_list:
return ({'message': 'Crypto currency_out doesnt exist in exchange_i... | Check_balance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Check_balance:
def check_balance(exchange_id, json, currency_types):
"""Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param json: :param currency_types: Type = bool, True = crypto, False = fiat :return: None if ok Else error m... | stack_v2_sparse_classes_75kplus_train_065253 | 13,350 | no_license | [
{
"docstring": "Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param json: :param currency_types: Type = bool, True = crypto, False = fiat :return: None if ok Else error message",
"name": "check_balance",
"signature": "def check_balance(exchan... | 2 | null | Implement the Python class `Check_balance` described below.
Class description:
Implement the Check_balance class.
Method signatures and docstrings:
- def check_balance(exchange_id, json, currency_types): Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param ... | Implement the Python class `Check_balance` described below.
Class description:
Implement the Check_balance class.
Method signatures and docstrings:
- def check_balance(exchange_id, json, currency_types): Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param ... | d88fe9966abe92522173384dc96a5dbc3b61727c | <|skeleton|>
class Check_balance:
def check_balance(exchange_id, json, currency_types):
"""Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param json: :param currency_types: Type = bool, True = crypto, False = fiat :return: None if ok Else error m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Check_balance:
def check_balance(exchange_id, json, currency_types):
"""Check if crypto currency exist for exchange_id Check if balance_amount >= trade_amount :param exchange_id: :param json: :param currency_types: Type = bool, True = crypto, False = fiat :return: None if ok Else error message"""
... | the_stack_v2_python_sparse | models/trade_model.py | davidbelusky/crypto_exchanges | train | 0 | |
334a368a962935346036bdb6cd75a9213a426627 | [
"if 'case_manager' in validated_data:\n old_case_manager = instance.case_manager\n old_notifications = Notification.objects.filter(student=instance, user=old_case_manager)\n for notification in old_notifications:\n notification.delete()\nreturn super(StudentSerializer, self).update(instance, validat... | <|body_start_0|>
if 'case_manager' in validated_data:
old_case_manager = instance.case_manager
old_notifications = Notification.objects.filter(student=instance, user=old_case_manager)
for notification in old_notifications:
notification.delete()
return ... | StudentSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentSerializer:
def update(self, instance, validated_data):
"""Clean up notifications for a case manager when a student is reassigned"""
<|body_0|>
def validate_grade_level(self, grade_level):
"""Ensure that the grade level is within the range supported by the sch... | stack_v2_sparse_classes_75kplus_train_065254 | 24,441 | no_license | [
{
"docstring": "Clean up notifications for a case manager when a student is reassigned",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "Ensure that the grade level is within the range supported by the school",
"name": "validate_grade_level",
... | 2 | stack_v2_sparse_classes_30k_train_018891 | Implement the Python class `StudentSerializer` described below.
Class description:
Implement the StudentSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Clean up notifications for a case manager when a student is reassigned
- def validate_grade_level(self, grade_level)... | Implement the Python class `StudentSerializer` described below.
Class description:
Implement the StudentSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Clean up notifications for a case manager when a student is reassigned
- def validate_grade_level(self, grade_level)... | b75d38ce91b94896c20b93ae43777372e4431950 | <|skeleton|>
class StudentSerializer:
def update(self, instance, validated_data):
"""Clean up notifications for a case manager when a student is reassigned"""
<|body_0|>
def validate_grade_level(self, grade_level):
"""Ensure that the grade level is within the range supported by the sch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudentSerializer:
def update(self, instance, validated_data):
"""Clean up notifications for a case manager when a student is reassigned"""
if 'case_manager' in validated_data:
old_case_manager = instance.case_manager
old_notifications = Notification.objects.filter(stud... | the_stack_v2_python_sparse | server/api/serializers.py | ndisera/Sprout | train | 0 | |
d4a04969cb0c0bf3cffc64ef162b3110e30b8d7b | [
"if is_horizontal:\n super(Composition3x1, self).__init__(3 * width, height)\nelse:\n super(Composition3x1, self).__init__(width, 3 * height)\nself.single_w = width\nself.single_h = height\nself.is_horizontal = is_horizontal\nself.empty = np.zeros((height, width, 3), dtype=np.uint8)\nself.left = left\nself.mi... | <|body_start_0|>
if is_horizontal:
super(Composition3x1, self).__init__(3 * width, height)
else:
super(Composition3x1, self).__init__(width, 3 * height)
self.single_w = width
self.single_h = height
self.is_horizontal = is_horizontal
self.empty = np... | Display two keras_tf next to each other. | Composition3x1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Composition3x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, middle, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final compo... | stack_v2_sparse_classes_75kplus_train_065255 | 1,891 | no_license | [
{
"docstring": "Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. :param left: Reference to the function which gets the frame to be displayed on left. :param right: Reference to the function which gets the frame to be ... | 2 | stack_v2_sparse_classes_30k_train_031904 | Implement the Python class `Composition3x1` described below.
Class description:
Display two keras_tf next to each other.
Method signatures and docstrings:
- def __init__(self, width, height, left, middle, right, is_horizontal: bool=True): Initialize the step with all relevant attributes. :param width: Width of the fi... | Implement the Python class `Composition3x1` described below.
Class description:
Display two keras_tf next to each other.
Method signatures and docstrings:
- def __init__(self, width, height, left, middle, right, is_horizontal: bool=True): Initialize the step with all relevant attributes. :param width: Width of the fi... | 8316bcc43805ba3cdc196b68b14f921f81610337 | <|skeleton|>
class Composition3x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, middle, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final compo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Composition3x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, middle, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. :para... | the_stack_v2_python_sparse | video/pipeline/compositions/composition_3x1.py | breitmuuufrosch/OpenCvPipeline | train | 0 |
577cdca8b5375f4dd13424f7cb80312450d984e2 | [
"self.game_pointer = None\nself.num_players = num_players\nself.init_raise_amount = init_raise_amount\nself.current_raise_amount = self.init_raise_amount\nself.not_raise_num = 0\nself.raised = [0 for _ in range(self.num_players)]",
"self.game_pointer = game_pointer\nself.not_raise_num = 0\nself.current_raise_amou... | <|body_start_0|>
self.game_pointer = None
self.num_players = num_players
self.init_raise_amount = init_raise_amount
self.current_raise_amount = self.init_raise_amount
self.not_raise_num = 0
self.raised = [0 for _ in range(self.num_players)]
<|end_body_0|>
<|body_start_1|... | Round can call other Classes' functions to keep the game running | NolimitholdemRound | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NolimitholdemRound:
"""Round can call other Classes' functions to keep the game running"""
def __init__(self, num_players, init_raise_amount):
"""Initilize the round class Args: allowed_raise_num (int): The number of allowed raise num num_players (int): The number of players init_rai... | stack_v2_sparse_classes_75kplus_train_065256 | 4,759 | permissive | [
{
"docstring": "Initilize the round class Args: allowed_raise_num (int): The number of allowed raise num num_players (int): The number of players init_raise_amount (int): The min raise amount when every round starts",
"name": "__init__",
"signature": "def __init__(self, num_players, init_raise_amount)"
... | 4 | stack_v2_sparse_classes_30k_train_019899 | Implement the Python class `NolimitholdemRound` described below.
Class description:
Round can call other Classes' functions to keep the game running
Method signatures and docstrings:
- def __init__(self, num_players, init_raise_amount): Initilize the round class Args: allowed_raise_num (int): The number of allowed ra... | Implement the Python class `NolimitholdemRound` described below.
Class description:
Round can call other Classes' functions to keep the game running
Method signatures and docstrings:
- def __init__(self, num_players, init_raise_amount): Initilize the round class Args: allowed_raise_num (int): The number of allowed ra... | 1724aa92ce33abd26a427c97f138bc883217bb9f | <|skeleton|>
class NolimitholdemRound:
"""Round can call other Classes' functions to keep the game running"""
def __init__(self, num_players, init_raise_amount):
"""Initilize the round class Args: allowed_raise_num (int): The number of allowed raise num num_players (int): The number of players init_rai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NolimitholdemRound:
"""Round can call other Classes' functions to keep the game running"""
def __init__(self, num_players, init_raise_amount):
"""Initilize the round class Args: allowed_raise_num (int): The number of allowed raise num num_players (int): The number of players init_raise_amount (in... | the_stack_v2_python_sparse | rlcard/games/nolimitholdem/round.py | noahj08/rlcard | train | 2 |
eb86da42e35090952e8c205885c9fd6b3f4df7c2 | [
"if self.request.method == 'GET':\n return (IsInActiveCommunity(), IsAbleToRetrieveAlbum())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method in ('PUT', 'PATCH', 'DELETE'):\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsStaffOfCommun... | <|body_start_0|>
if self.request.method == 'GET':
return (IsInActiveCommunity(), IsAbleToRetrieveAlbum())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method in ('PUT', 'PATCH', 'DELETE'):
return (permissions.Is... | Album view set | AlbumViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumViewSet:
"""Album view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List albums"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_065257 | 8,383 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List albums",
"name": "list",
"... | 3 | stack_v2_sparse_classes_30k_train_010656 | Implement the Python class `AlbumViewSet` described below.
Class description:
Album view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List albums | Implement the Python class `AlbumViewSet` described below.
Class description:
Album view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List albums
<|skeleton|>
class AlbumViewSet:
... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class AlbumViewSet:
"""Album view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List albums"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlbumViewSet:
"""Album view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (IsInActiveCommunity(), IsAbleToRetrieveAlbum())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
... | the_stack_v2_python_sparse | asset/views.py | 810Teams/clubs-and-events-backend | train | 3 |
286b58d160d6098874228f0de2eda41b674026c5 | [
"if model._meta.app_label == self.appname:\n return self.db_name\nreturn None",
"if model._meta.app_label == self.appname:\n return self.db_name\nreturn None",
"if obj1._meta.app_label == self.appname or obj2._meta.app_label == self.appname:\n return True\nreturn None",
"if app_label == self.appname:... | <|body_start_0|>
if model._meta.app_label == self.appname:
return self.db_name
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == self.appname:
return self.db_name
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label =... | Router | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models go to model.db."""
<|body_1|>
def allow_relation(self, o... | stack_v2_sparse_classes_75kplus_train_065258 | 1,715 | no_license | [
{
"docstring": "Attempts to read self.appname models go to model.db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write self.appname models go to model.db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model... | 4 | stack_v2_sparse_classes_30k_train_043536 | Implement the Python class `Router` described below.
Class description:
Implement the Router class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db.
- def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode... | Implement the Python class `Router` described below.
Class description:
Implement the Router class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read self.appname models go to model.db.
- def db_for_write(self, model, **hints): Attempts to write self.appname models go to mode... | 7cf818076b67cf6d4e40192b6bbe7db547005c96 | <|skeleton|>
class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models go to model.db."""
<|body_1|>
def allow_relation(self, o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Router:
def db_for_read(self, model, **hints):
"""Attempts to read self.appname models go to model.db."""
if model._meta.app_label == self.appname:
return self.db_name
return None
def db_for_write(self, model, **hints):
"""Attempts to write self.appname models ... | the_stack_v2_python_sparse | apps_cenco/db_local/router.py | robCastro/academica_cenco | train | 0 | |
4ad1ddede995c1f705f01058e235b608f4b8f33b | [
"self.handle = ml.matelight_open(match_serial)\nself.dbuf = np.zeros(config.frame_size * 4, dtype=np.uint8)\nif self.handle is None:\n raise ValueError('Cannot find requested matelight.')",
"rgba = len(framedata) == config.frame_size * 4\nnp.copyto(self.dbuf[:config.frame_size * (3 + rgba)], np.frombuffer(fram... | <|body_start_0|>
self.handle = ml.matelight_open(match_serial)
self.dbuf = np.zeros(config.frame_size * 4, dtype=np.uint8)
if self.handle is None:
raise ValueError('Cannot find requested matelight.')
<|end_body_0|>
<|body_start_1|>
rgba = len(framedata) == config.frame_size ... | Matelight | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matelight:
def __init__(self, match_serial=None):
"""Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight"""
<|body_0|>
def sendframe(self, framedata):
"""Send a frame to the display The argument... | stack_v2_sparse_classes_75kplus_train_065259 | 1,376 | no_license | [
{
"docstring": "Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight",
"name": "__init__",
"signature": "def __init__(self, match_serial=None)"
},
{
"docstring": "Send a frame to the display The argument contains a h * w arr... | 2 | stack_v2_sparse_classes_30k_train_036578 | Implement the Python class `Matelight` described below.
Class description:
Implement the Matelight class.
Method signatures and docstrings:
- def __init__(self, match_serial=None): Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight
- def sendfr... | Implement the Python class `Matelight` described below.
Class description:
Implement the Matelight class.
Method signatures and docstrings:
- def __init__(self, match_serial=None): Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight
- def sendfr... | def6d67af481fb3d7f283a665c800b8aa6ea4bb7 | <|skeleton|>
class Matelight:
def __init__(self, match_serial=None):
"""Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight"""
<|body_0|>
def sendframe(self, framedata):
"""Send a frame to the display The argument... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Matelight:
def __init__(self, match_serial=None):
"""Open the matelight matching the USB serial number given as a bytes object. If match_serial is None, open the first matelight"""
self.handle = ml.matelight_open(match_serial)
self.dbuf = np.zeros(config.frame_size * 4, dtype=np.uint8)... | the_stack_v2_python_sparse | host/matelight.py | arnew/fritzlight | train | 0 | |
d3d358dc1644305c04e334c95458237ecb8416e2 | [
"self._param = kwargs.copy()\nfparam = kwargs.copy()\nif 'upsert' in fparam:\n fparam.pop('upsert')\nself._collect = pymongo.MongoClient(host, port, **fparam)[db][collection]",
"if '_id' in value.keys():\n try:\n self._collect.insert(value)\n self.logger.info('Insert document with _id {0}'.for... | <|body_start_0|>
self._param = kwargs.copy()
fparam = kwargs.copy()
if 'upsert' in fparam:
fparam.pop('upsert')
self._collect = pymongo.MongoClient(host, port, **fparam)[db][collection]
<|end_body_0|>
<|body_start_1|>
if '_id' in value.keys():
try:
... | MongoDBDriver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoDBDriver:
def __init__(self, host='localhost', port=27017, db='test', collection='collection', **kwargs):
"""如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_id存在, 且upins为True则更新其内容;否则不做更改 z @param kwargs: Others paramters of mongodb, e.g. socketTimeoutMS, conn... | stack_v2_sparse_classes_75kplus_train_065260 | 1,661 | no_license | [
{
"docstring": "如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_id存在, 且upins为True则更新其内容;否则不做更改 z @param kwargs: Others paramters of mongodb, e.g. socketTimeoutMS, connectTimeoutMS @return: 文档``_id``",
"name": "__init__",
"signature": "def __init__(self, host='localhost', port=2701... | 2 | stack_v2_sparse_classes_30k_train_040881 | Implement the Python class `MongoDBDriver` described below.
Class description:
Implement the MongoDBDriver class.
Method signatures and docstrings:
- def __init__(self, host='localhost', port=27017, db='test', collection='collection', **kwargs): 如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_i... | Implement the Python class `MongoDBDriver` described below.
Class description:
Implement the MongoDBDriver class.
Method signatures and docstrings:
- def __init__(self, host='localhost', port=27017, db='test', collection='collection', **kwargs): 如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_i... | 15e72f41d66899cc0b85bf62eb2c659b6cc8efd1 | <|skeleton|>
class MongoDBDriver:
def __init__(self, host='localhost', port=27017, db='test', collection='collection', **kwargs):
"""如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_id存在, 且upins为True则更新其内容;否则不做更改 z @param kwargs: Others paramters of mongodb, e.g. socketTimeoutMS, conn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MongoDBDriver:
def __init__(self, host='localhost', port=27017, db='test', collection='collection', **kwargs):
"""如果存在名称为_id的字段,则使用此字段中的值为documents的_id @param upsert: 当存在名称为_id的字段时,如果该_id存在, 且upins为True则更新其内容;否则不做更改 z @param kwargs: Others paramters of mongodb, e.g. socketTimeoutMS, connectTimeoutMS @... | the_stack_v2_python_sparse | spiderflow/storage/mongostorage.py | zzpwelkin/autospider | train | 1 | |
0741cac3684ef0a539178e26aa0522ddec4ac697 | [
"Promo(code=Promo.generate_code()).put()\nquery = Promo.all()\nquery.filter('used =', False)\npromos = query.fetch(250)\noptions = self.get_options()\noptions['promos'] = promos\noptions['content'] = self.render('admin/promos.html', options)\nself.response.out.write(self.render('admin.html', options))",
"query = ... | <|body_start_0|>
Promo(code=Promo.generate_code()).put()
query = Promo.all()
query.filter('used =', False)
promos = query.fetch(250)
options = self.get_options()
options['promos'] = promos
options['content'] = self.render('admin/promos.html', options)
self... | Handles requests for the tickets page. | PromosHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromosHandler:
"""Handles requests for the tickets page."""
def post(self):
"""Handles HTTP POST requests."""
<|body_0|>
def get(self):
"""Handles HTTP GET requests."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Promo(code=Promo.generate_code(... | stack_v2_sparse_classes_75kplus_train_065261 | 2,643 | no_license | [
{
"docstring": "Handles HTTP POST requests.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Handles HTTP GET requests.",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018991 | Implement the Python class `PromosHandler` described below.
Class description:
Handles requests for the tickets page.
Method signatures and docstrings:
- def post(self): Handles HTTP POST requests.
- def get(self): Handles HTTP GET requests. | Implement the Python class `PromosHandler` described below.
Class description:
Handles requests for the tickets page.
Method signatures and docstrings:
- def post(self): Handles HTTP POST requests.
- def get(self): Handles HTTP GET requests.
<|skeleton|>
class PromosHandler:
"""Handles requests for the tickets p... | f96b19cbddc70368deb72ccd1afab50e71963135 | <|skeleton|>
class PromosHandler:
"""Handles requests for the tickets page."""
def post(self):
"""Handles HTTP POST requests."""
<|body_0|>
def get(self):
"""Handles HTTP GET requests."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PromosHandler:
"""Handles requests for the tickets page."""
def post(self):
"""Handles HTTP POST requests."""
Promo(code=Promo.generate_code()).put()
query = Promo.all()
query.filter('used =', False)
promos = query.fetch(250)
options = self.get_options()
... | the_stack_v2_python_sparse | admin.py | coderoshi/mostlymt | train | 1 |
2094d4152b0808dc5f7127042985085730672c2a | [
"smach.State.__init__(self, outcomes=['succeeded', 'failed'])\nself._robot = robot\nself._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage)\nself._entity_str = entity_str",
"self._robot.head.reset()\nself._robot.head.wait_for_motion_done(5.0)\nrospy.sleep(rospy.Duration(1.0)... | <|body_start_0|>
smach.State.__init__(self, outcomes=['succeeded', 'failed'])
self._robot = robot
self._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage)
self._entity_str = entity_str
<|end_body_0|>
<|body_start_1|>
self._robot.head.reset()... | Fits an entity | FitEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
<|body_0|>
def execute(self, userdata=None):
"""Executes the state"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_065262 | 32,974 | no_license | [
{
"docstring": "Constructor :param robot: robot object :param entity_str: string with the entity type to fit",
"name": "__init__",
"signature": "def __init__(self, robot, entity_str)"
},
{
"docstring": "Executes the state",
"name": "execute",
"signature": "def execute(self, userdata=None... | 2 | null | Implement the Python class `FitEntity` described below.
Class description:
Fits an entity
Method signatures and docstrings:
- def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit
- def execute(self, userdata=None): Executes the state | Implement the Python class `FitEntity` described below.
Class description:
Fits an entity
Method signatures and docstrings:
- def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit
- def execute(self, userdata=None): Executes the state
<|sk... | 092a354315b9b2c08e32cdc049791d82dfd47745 | <|skeleton|>
class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
<|body_0|>
def execute(self, userdata=None):
"""Executes the state"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FitEntity:
"""Fits an entity"""
def __init__(self, robot, entity_str):
"""Constructor :param robot: robot object :param entity_str: string with the entity type to fit"""
smach.State.__init__(self, outcomes=['succeeded', 'failed'])
self._robot = robot
self._srv = rospy.Serv... | the_stack_v2_python_sparse | challenge_manipulation/src/manipulation.py | tue-robotics/tue_robocup | train | 39 |
d87475378290243deafad1491afcbb367962d500 | [
"colors = ['blue', 'cherry red', 'golden yellow', 'vibrant green', 'violet', 'pumpkin orange']\npalette = sns.xkcd_palette(colors)\nreturn palette",
"mat1 = np.loadtxt(open(fn1, 'r'), delimiter=',')\nmat2 = np.loadtxt(open(fn2, 'r'), delimiter=',')\nmat3 = np.loadtxt(open(fn3, 'r'), delimiter=',')\nfig = plt.figu... | <|body_start_0|>
colors = ['blue', 'cherry red', 'golden yellow', 'vibrant green', 'violet', 'pumpkin orange']
palette = sns.xkcd_palette(colors)
return palette
<|end_body_0|>
<|body_start_1|>
mat1 = np.loadtxt(open(fn1, 'r'), delimiter=',')
mat2 = np.loadtxt(open(fn2, 'r'), del... | Utils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utils:
def defineColorPalette():
"""Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette: the seaborn palette defined"""
<|body_0|>
def plotCorrelationMatrices3GivenCMapR... | stack_v2_sparse_classes_75kplus_train_065263 | 4,055 | no_license | [
{
"docstring": "Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette: the seaborn palette defined",
"name": "defineColorPalette",
"signature": "def defineColorPalette()"
},
{
"docstring": "Ta... | 2 | stack_v2_sparse_classes_30k_train_034287 | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def defineColorPalette(): Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette:... | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def defineColorPalette(): Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette:... | a61970ca0df21031a0d324e86ba0c72e5ca98dfc | <|skeleton|>
class Utils:
def defineColorPalette():
"""Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette: the seaborn palette defined"""
<|body_0|>
def plotCorrelationMatrices3GivenCMapR... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Utils:
def defineColorPalette():
"""Use the seaborn library to define a better looking color palette. Currently takes no inputs, but that might change as I make more palettes Returns: - palette: the seaborn palette defined"""
colors = ['blue', 'cherry red', 'golden yellow', 'vibrant green', 'v... | the_stack_v2_python_sparse | utils.py | jmschabdach/markov-movement-correction | train | 1 | |
a2f7482fb19af0064e301bf6263ce26267abdd38 | [
"pairs = []\nfor i, num1 in enumerate(nums1):\n for j, num2 in enumerate(nums2):\n if i + j >= k:\n break\n pairs.append((num1 + num2, num1, num2))\nreturn map(lambda x: [x[1], x[2]], heapq.nsmallest(k, pairs))",
"if not nums1 or not nums2:\n return []\nlength1, length2 = (len(nums1... | <|body_start_0|>
pairs = []
for i, num1 in enumerate(nums1):
for j, num2 in enumerate(nums2):
if i + j >= k:
break
pairs.append((num1 + num2, num1, num2))
return map(lambda x: [x[1], x[2]], heapq.nsmallest(k, pairs))
<|end_body_0|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs2(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_75kplus_train_065264 | 1,286 | permissive | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairs",
"signature": "def kSmallestPairs(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"nam... | 2 | stack_v2_sparse_classes_30k_train_009845 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs2(self, nums1, nums2, k): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs2(self, nums1, nums2, k): :type ... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs2(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
pairs = []
for i, num1 in enumerate(nums1):
for j, num2 in enumerate(nums2):
if i + j >= k:
brea... | the_stack_v2_python_sparse | 301-400/371-380/373-findKPairsWithSmallestSums/findKPairsWithSmallestSums.py | xuychen/Leetcode | train | 0 | |
b404866de3d16e8000724d698921d5310837fe5c | [
"self._client = None\npool = redis.ConnectionPool\nif blocking_pool:\n pool = redis.BlockingConnectionPool\nself.pool = pool(host=host, port=port, db=db, **kwargs)",
"if self._client is None:\n self._client = redis.Redis(connection_pool=self.pool)\nreturn self._client"
] | <|body_start_0|>
self._client = None
pool = redis.ConnectionPool
if blocking_pool:
pool = redis.BlockingConnectionPool
self.pool = pool(host=host, port=port, db=db, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self._client is None:
self._client = redis.Re... | A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (int, optional): The REDIS ... | RedisClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisClient:
"""A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to loca... | stack_v2_sparse_classes_75kplus_train_065265 | 5,405 | permissive | [
{
"docstring": "Initialize class properties",
"name": "__init__",
"signature": "def __init__(self, host='localhost', port=6379, db=0, blocking_pool=False, **kwargs)"
},
{
"docstring": "Return an instance of redis.client.Redis.",
"name": "client",
"signature": "def client(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044624 | Implement the Python class `RedisClient` described below.
Class description:
A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, opti... | Implement the Python class `RedisClient` described below.
Class description:
A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, opti... | 78680f055f4259e31f0b4989a5695604108d9fdd | <|skeleton|>
class RedisClient:
"""A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to loca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisClient:
"""A shared REDIS client connection using a ConnectionPooling singleton. Initialize a single shared redis.connection.ConnectionPool. For a full list of kwargs see https://redis-py.readthedocs.io/en/latest/#redis.Connection. Args: host (str, optional): The REDIS host. Defaults to localhost. port (... | the_stack_v2_python_sparse | tcex/tcex_redis.py | brikardtc/tcex | train | 0 |
3d298b52eda0cc5ae0f6f056f631ad9f50ae34c9 | [
"length = len(nums)\nself.d = {}\nself.a = nums\nself.build(0, length, 0)",
"if left == right - 1:\n self.d[p] = self.a[left]\n return\nmid = left + (right - left) // 2\nchdleft = 2 * p + 1\nchdright = 2 * p + 2\nself.build(left, mid, chdleft)\nself.build(mid, right, chdright)\nself.d[p] = self.d[chdleft] +... | <|body_start_0|>
length = len(nums)
self.d = {}
self.a = nums
self.build(0, length, 0)
<|end_body_0|>
<|body_start_1|>
if left == right - 1:
self.d[p] = self.a[left]
return
mid = left + (right - left) // 2
chdleft = 2 * p + 1
chdri... | 非完美二叉树版本, 即二分法分割区间 | segmentTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: ... | stack_v2_sparse_classes_75kplus_train_065266 | 4,234 | permissive | [
{
"docstring": "p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: 21 6 15 3 3 9 6 1 2 (3) 4 5 (6)",
"name": "__init__",
"signature": "def __init_... | 4 | stack_v2_sparse_classes_30k_train_030560 | Implement the Python class `segmentTree` described below.
Class description:
非完美二叉树版本, 即二分法分割区间
Method signatures and docstrings:
- def __init__(self, nums) -> None: p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连... | Implement the Python class `segmentTree` described below.
Class description:
非完美二叉树版本, 即二分法分割区间
Method signatures and docstrings:
- def __init__(self, nums) -> None: p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class segmentTree:
"""非完美二叉树版本, 即二分法分割区间"""
def __init__(self, nums) -> None:
"""p 代表 [left, right) eg: 0 -> [0, length) 1 -> [0, mid) 2 -> [mid, length) 注意, 这里d的数据类型dict是更优选择, 因为对nums 进行递归的二分法分割区间, 会导致 二叉树并非是完全二叉树,会出现大量不连续的叶子结点,然而不连续的叶子结点仍然会占用索引空间 如果用list,这个索引必须有值 如果用dict, 则会节省很多索引空间 eg: 21 6 15 3 3 9... | the_stack_v2_python_sparse | utils/segmentTree.py | wisesky/LeetCode-Practice | train | 0 |
ecd2e3126d92251a593524cb4db28a282df66a96 | [
"n = len(g)\ndp = [0] * (1 << n)\nfor i in range(1 << n):\n s = 0\n for j in range(n):\n if i >> j & 1:\n s += g[j]\n for j in range(n):\n if i & 1 << j == 0:\n dp[i | 1 << j] = max(dp[i | 1 << j], dp[i] + int(s % b == 0))\nreturn dp[-1]",
"arr = [0] * b\nfor gg in g:\... | <|body_start_0|>
n = len(g)
dp = [0] * (1 << n)
for i in range(1 << n):
s = 0
for j in range(n):
if i >> j & 1:
s += g[j]
for j in range(n):
if i & 1 << j == 0:
dp[i | 1 << j] = max(dp[i |... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxHappyGroups(self, b: int, g: List[int]) -> int:
"""常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:"""
<|body_0|>
def maxHappyGroups(self, b: int, g: List[int]) -> int:
"""如果用2进制枚举会超时,由于客户数量最多30组,采用31进制 @param b: @param g: @return:"""
... | stack_v2_sparse_classes_75kplus_train_065267 | 2,946 | no_license | [
{
"docstring": "常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:",
"name": "maxHappyGroups",
"signature": "def maxHappyGroups(self, b: int, g: List[int]) -> int"
},
{
"docstring": "如果用2进制枚举会超时,由于客户数量最多30组,采用31进制 @param b: @param g: @return:",
"name": "maxHappyGroups",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_009642 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxHappyGroups(self, b: int, g: List[int]) -> int: 常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:
- def maxHappyGroups(self, b: int, g: List[int]) -> int: 如果用2进制... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxHappyGroups(self, b: int, g: List[int]) -> int: 常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:
- def maxHappyGroups(self, b: int, g: List[int]) -> int: 如果用2进制... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def maxHappyGroups(self, b: int, g: List[int]) -> int:
"""常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:"""
<|body_0|>
def maxHappyGroups(self, b: int, g: List[int]) -> int:
"""如果用2进制枚举会超时,由于客户数量最多30组,采用31进制 @param b: @param g: @return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxHappyGroups(self, b: int, g: List[int]) -> int:
"""常规做法:二进制枚举(超时) 1. 本代码可帮助理解题目意思 @param b: @param g: @return:"""
n = len(g)
dp = [0] * (1 << n)
for i in range(1 << n):
s = 0
for j in range(n):
if i >> j & 1:
... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/状态压缩DP/1815. 得到新鲜甜甜圈的最多组数.py | yiming1012/MyLeetCode | train | 2 | |
859b29554a79b8c1752c5caa5ad13f155d5da098 | [
"if not board:\n return\nyLen, xLen = (len(board), len(board[0]))\nself.isChecked = [[False for x in range(xLen)] for y in range(yLen)]\nfor yIdx in range(1, yLen - 1):\n for xIdx in range(1, xLen - 1):\n if not self.isChecked[yIdx][xIdx] and board[yIdx][xIdx] == 'O':\n modified = set()\n ... | <|body_start_0|>
if not board:
return
yLen, xLen = (len(board), len(board[0]))
self.isChecked = [[False for x in range(xLen)] for y in range(yLen)]
for yIdx in range(1, yLen - 1):
for xIdx in range(1, xLen - 1):
if not self.isChecked[yIdx][xIdx] an... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def dfsModify(self, yIdx, xIdx, board, modified: set):
"""Modify surrounded 'O' with DFS search"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_065268 | 3,163 | permissive | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "solve",
"signature": "def solve(self, board: List[List[str]]) -> None"
},
{
"docstring": "Modify surrounded 'O' with DFS search",
"name": "dfsModify",
"signature": "def dfsModify(self, yIdx, xIdx, board, mo... | 2 | stack_v2_sparse_classes_30k_train_044926 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def dfsModify(self, yIdx, xIdx, board, modified: set): Modify surrounded... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def dfsModify(self, yIdx, xIdx, board, modified: set): Modify surrounded... | c9d5bb53799f9428d7615e095c89997897b5b8ab | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def dfsModify(self, yIdx, xIdx, board, modified: set):
"""Modify surrounded 'O' with DFS search"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
if not board:
return
yLen, xLen = (len(board), len(board[0]))
self.isChecked = [[False for x in range(xLen)] for y in range(yLen)]
for yId... | the_stack_v2_python_sparse | problems/surrounded-regions/solution.py | HearyShen/leetcode-cn | train | 1 | |
74b1fa3e9a976311979e1c49b3659036856f89ab | [
"database.drop_tables([Customer])\ndatabase.create_tables([Customer])\nLOGGER.info('test setup complete')",
"pass\nadd_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4], self.customer_111[5], self.customer_111[6], self.customer_111[7])\ncustomer ... | <|body_start_0|>
database.drop_tables([Customer])
database.create_tables([Customer])
LOGGER.info('test setup complete')
<|end_body_0|>
<|body_start_1|>
pass
add_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4],... | testing basic operation | SuiteOfTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
<|body_0|>
def test_add_customer(self):
"""test add customer"""
<|body_1|>
def test_search_customer(self):
"""test search customer"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_065269 | 5,744 | no_license | [
{
"docstring": "sets up the database",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test add customer",
"name": "test_add_customer",
"signature": "def test_add_customer(self)"
},
{
"docstring": "test search customer",
"name": "test_search_customer",
... | 6 | stack_v2_sparse_classes_30k_test_002961 | Implement the Python class `SuiteOfTests` described below.
Class description:
testing basic operation
Method signatures and docstrings:
- def setUp(self): sets up the database
- def test_add_customer(self): test add customer
- def test_search_customer(self): test search customer
- def test_delete_customer(self): test... | Implement the Python class `SuiteOfTests` described below.
Class description:
testing basic operation
Method signatures and docstrings:
- def setUp(self): sets up the database
- def test_add_customer(self): test add customer
- def test_search_customer(self): test search customer
- def test_delete_customer(self): test... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
<|body_0|>
def test_add_customer(self):
"""test add customer"""
<|body_1|>
def test_search_customer(self):
"""test search customer"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
database.drop_tables([Customer])
database.create_tables([Customer])
LOGGER.info('test setup complete')
def test_add_customer(self):
"""test add customer"""
pass
... | the_stack_v2_python_sparse | students/mmancini/lesson03/test_basic_operations.py | JavaRod/SP_Python220B_2019 | train | 1 |
0e5958798d47a3ad8ded8cd557b39c33c560e201 | [
"items = ItemModel.objects.all()\nserializer = ItemSerializer(items, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"serializer = ItemSerializer(data=request.data)\nif not serializer.is_valid(raise_exception=True):\n return Response({'message': \"Please Check Item's Context\"}, statu... | <|body_start_0|>
items = ItemModel.objects.all()
serializer = ItemSerializer(items, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
serializer = ItemSerializer(data=request.data)
if not serializer.is_valid(raise_exception=Tr... | Item | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Item:
def get(self, request):
"""get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)"""
<|body_0|>
def post(self, request):
"""create One Item /return => messeage : success or Fail"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_065270 | 3,225 | no_license | [
{
"docstring": "get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "create One Item /return => messeage : success or Fail",
"name": "post",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_032697 | Implement the Python class `Item` described below.
Class description:
Implement the Item class.
Method signatures and docstrings:
- def get(self, request): get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)
- def post(self, request): create One Item /ret... | Implement the Python class `Item` described below.
Class description:
Implement the Item class.
Method signatures and docstrings:
- def get(self, request): get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)
- def post(self, request): create One Item /ret... | 291ec9e7304772769be7bf52ca8511791485bffe | <|skeleton|>
class Item:
def get(self, request):
"""get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)"""
<|body_0|>
def post(self, request):
"""create One Item /return => messeage : success or Fail"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Item:
def get(self, request):
"""get all items's information /return => list of item's (category, name, sell_price, buy_price, image_dir, isinshop)"""
items = ItemModel.objects.all()
serializer = ItemSerializer(items, many=True)
return Response(serializer.data, status=status.HT... | the_stack_v2_python_sparse | backend/Django/items/views.py | starseek34/DailyTown | train | 0 | |
8cc20557e092de21868a15b1f401b583ede632de | [
"device_data = self.target\ndevice_data.is_release_resources_command_executed = False\ndevice_data.is_abort_command_executed = False\ndevice_data.is_obsreset_command_executed = False\ntry:\n this_server = TangoServerHelper.get_instance()\n property_val = this_server.read_property('MccsSubarrayLNFQDN')[0]\n ... | <|body_start_0|>
device_data = self.target
device_data.is_release_resources_command_executed = False
device_data.is_abort_command_executed = False
device_data.is_obsreset_command_executed = False
try:
this_server = TangoServerHelper.get_instance()
property... | A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity. | Restart | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Restart:
"""A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity."""
def do(self):
"""Method to invoke Restart command. return: A tuple containing a return code and a strin... | stack_v2_sparse_classes_75kplus_train_065271 | 2,548 | permissive | [
{
"docstring": "Method to invoke Restart command. return: A tuple containing a return code and a string message indicating status. The message is for information purpose only. rtype: (ResultCode, str) raises: DevFailed if error occurs while invoking command on MCCS Subarray Leaf Node.",
"name": "do",
"s... | 2 | stack_v2_sparse_classes_30k_train_000546 | Implement the Python class `Restart` described below.
Class description:
A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity.
Method signatures and docstrings:
- def do(self): Method to invoke Restart comm... | Implement the Python class `Restart` described below.
Class description:
A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity.
Method signatures and docstrings:
- def do(self): Method to invoke Restart comm... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Restart:
"""A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity."""
def do(self):
"""Method to invoke Restart command. return: A tuple containing a return code and a strin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Restart:
"""A class for SubarrayNode's Restart() command. This command on Subarray Node Low invokes Restart command on MCCS Subarray Leaf Node and restarts the ongoing activity."""
def do(self):
"""Method to invoke Restart command. return: A tuple containing a return code and a string message ind... | the_stack_v2_python_sparse | temp_src/ska_tmc_subarraynode_low/restart_command.py | ska-telescope/tmc-prototype | train | 4 |
faf7ae4f980ec39f523082c71e7282bca66d8e3f | [
"from pyspark.pandas.frame import DataFrame\nfrom pyspark.pandas.series import Series, first_series\nfrom pyspark.pandas.internal import HIDDEN_COLUMNS\noutput = func(self._data.spark.column)\nColumn = get_column_class()\nif not isinstance(output, Column):\n raise ValueError('The output of the function [%s] shou... | <|body_start_0|>
from pyspark.pandas.frame import DataFrame
from pyspark.pandas.series import Series, first_series
from pyspark.pandas.internal import HIDDEN_COLUMNS
output = func(self._data.spark.column)
Column = get_column_class()
if not isinstance(output, Column):
... | SparkSeriesMethods | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparkSeriesMethods:
def apply(self, func: Callable[[PySparkColumn], PySparkColumn]) -> 'ps.Series':
"""Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:... | stack_v2_sparse_classes_75kplus_train_065272 | 42,899 | permissive | [
{
"docstring": "Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:: It forces to lose the index and end up using the default index. It is preferred to use :meth:`Series.spark.tr... | 2 | null | Implement the Python class `SparkSeriesMethods` described below.
Class description:
Implement the SparkSeriesMethods class.
Method signatures and docstrings:
- def apply(self, func: Callable[[PySparkColumn], PySparkColumn]) -> 'ps.Series': Applies a function that takes and returns a Spark column. It allows to nativel... | Implement the Python class `SparkSeriesMethods` described below.
Class description:
Implement the SparkSeriesMethods class.
Method signatures and docstrings:
- def apply(self, func: Callable[[PySparkColumn], PySparkColumn]) -> 'ps.Series': Applies a function that takes and returns a Spark column. It allows to nativel... | 60d8fc49bec5dae1b8cf39a0670cb640b430f520 | <|skeleton|>
class SparkSeriesMethods:
def apply(self, func: Callable[[PySparkColumn], PySparkColumn]) -> 'ps.Series':
"""Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparkSeriesMethods:
def apply(self, func: Callable[[PySparkColumn], PySparkColumn]) -> 'ps.Series':
"""Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:: It forces to... | the_stack_v2_python_sparse | python/pyspark/pandas/spark/accessors.py | apache/spark | train | 39,983 | |
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9 | [
"if not field:\n raise ValueError('Empty field name.')\nif not is_string(field):\n raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))\nif ' ' in field:\n raise ValueError(\"Field name can't contain spaces.\")\nself.__field = field\nspecifications = _get_specifications(... | <|body_start_0|>
if not field:
raise ValueError('Empty field name.')
if not is_string(field):
raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))
if ' ' in field:
raise ValueError("Field name can't contain spaces.")
... | @Requires decorator Defines a required service | Requires | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_75kplus_train_065273 | 41,418 | permissive | [
{
"docstring": "Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If true, injects a list :param optional: If true, this injection is optional :param spec_filter: An LDAP query to filter injected services upon their properties :ra... | 2 | stack_v2_sparse_classes_30k_train_007221 | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If tru... | the_stack_v2_python_sparse | python/src/lib/python/pelix/ipopo/decorators.py | cohorte/cohorte-runtime | train | 3 |
6a35afabc54c0dc6cb20ba1a1e82031652e913eb | [
"self.text_name = kwargs.pop('text_name', 'text')\nself.identity_name = kwargs.pop('identity_name', 'identity')\nsuper(GenericHttpForm, self).__init__(*args, **kwargs)\nself.fields[self.text_name] = forms.CharField()\nself.fields[self.identity_name] = forms.CharField()",
"identity = self.cleaned_data[self.identit... | <|body_start_0|>
self.text_name = kwargs.pop('text_name', 'text')
self.identity_name = kwargs.pop('identity_name', 'identity')
super(GenericHttpForm, self).__init__(*args, **kwargs)
self.fields[self.text_name] = forms.CharField()
self.fields[self.identity_name] = forms.CharField(... | GenericHttpForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
<|body_0|>
def get_incoming_data(self):
"""Returns the connection and text for this message, ... | stack_v2_sparse_classes_75kplus_train_065274 | 1,876 | permissive | [
{
"docstring": "Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Returns the connection and text for this message, based on the field names... | 2 | stack_v2_sparse_classes_30k_train_018901 | Implement the Python class `GenericHttpForm` described below.
Class description:
Implement the GenericHttpForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.
- def get_inc... | Implement the Python class `GenericHttpForm` described below.
Class description:
Implement the GenericHttpForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields.
- def get_inc... | aaa2ddab68e19d979525c3823c3ec0e646e92c83 | <|skeleton|>
class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
<|body_0|>
def get_incoming_data(self):
"""Returns the connection and text for this message, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericHttpForm:
def __init__(self, *args, **kwargs):
"""Saves the identify (phone number) and text field names on self, calls super(), and then adds the required fields."""
self.text_name = kwargs.pop('text_name', 'text')
self.identity_name = kwargs.pop('identity_name', 'identity')
... | the_stack_v2_python_sparse | rapidsms/backends/http/forms.py | rapidsms/rapidsms | train | 409 | |
689b05548684177fcc11e4a84a827d95affd12b5 | [
"for i in range(1, len(channels)):\n with tf.variable_scope('conv{}'.format(i)) as scope:\n kernel = variables.weight_variable(shape=[5, 5, channels[i - 1], channels[i]], stddev=0.05, verbose=self._hparams.verbose)\n conv = tf.nn.conv2d(input_tensor, kernel, [1, 1, 1, 1], padding=self._hparams.padd... | <|body_start_0|>
for i in range(1, len(channels)):
with tf.variable_scope('conv{}'.format(i)) as scope:
kernel = variables.weight_variable(shape=[5, 5, channels[i - 1], channels[i]], stddev=0.05, verbose=self._hparams.verbose)
conv = tf.nn.conv2d(input_tensor, kernel,... | A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units. | ConvModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvModel:
"""A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units."""
def _add_convs(self, input_tensor, channels):
"""Adds the convolution layers. Adds a series ... | stack_v2_sparse_classes_75kplus_train_065275 | 4,900 | permissive | [
{
"docstring": "Adds the convolution layers. Adds a series of convolution layers with ReLU nonlinearity and pooling after each of them. Args: input_tensor: a 4D float tensor as the input to the first convolution. channels: A list of channel sizes for input_tensor and following convolution layers. Number of chan... | 2 | null | Implement the Python class `ConvModel` described below.
Class description:
A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units.
Method signatures and docstrings:
- def _add_convs(self, input_tenso... | Implement the Python class `ConvModel` described below.
Class description:
A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units.
Method signatures and docstrings:
- def _add_convs(self, input_tenso... | 5b98fbb84408d566ae4ef0878008931a65832386 | <|skeleton|>
class ConvModel:
"""A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units."""
def _add_convs(self, input_tensor, channels):
"""Adds the convolution layers. Adds a series ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvModel:
"""A baseline multi GPU Model without capsule layers. The inference graph includes ReLU convolution layers and fully connected layers. The last layer is linear and has 10 units."""
def _add_convs(self, input_tensor, channels):
"""Adds the convolution layers. Adds a series of convolutio... | the_stack_v2_python_sparse | models/conv_model.py | Cerenaut/sparse-unsupervised-capsules | train | 5 |
bc5abbf5c7954c4da2252ac277d9db1ab49fda42 | [
"self.t_dual = self.g\nself.t_net = unstructured_grid.UnstructuredGrid(extra_node_fields=[('value', np.float64), ('dual_cell', np.int32), ('hydro_cell', np.int32)], extra_edge_fields=[('Td', np.float64)])\nself.dual_to_net_node = {}\ncc = g.cells_center()\nfor c in np.nonzero(self.g.cell_clip_mask(self.clip))[0]:\n... | <|body_start_0|>
self.t_dual = self.g
self.t_net = unstructured_grid.UnstructuredGrid(extra_node_fields=[('value', np.float64), ('dual_cell', np.int32), ('hydro_cell', np.int32)], extra_edge_fields=[('Td', np.float64)])
self.dual_to_net_node = {}
cc = g.cells_center()
for c in np... | InterpZhangDual | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpZhangDual:
def build_net(self):
"""Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood."""
<|body_0|>
def set_velocity_on_net(self):
"""Assign per-node velocities"""
<|body_1|>
def set_samples(self, xy... | stack_v2_sparse_classes_75kplus_train_065276 | 21,241 | no_license | [
{
"docstring": "Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood.",
"name": "build_net",
"signature": "def build_net(self)"
},
{
"docstring": "Assign per-node velocities",
"name": "set_velocity_on_net",
"signature": "def set_velocity_on_n... | 3 | stack_v2_sparse_classes_30k_train_051926 | Implement the Python class `InterpZhangDual` described below.
Class description:
Implement the InterpZhangDual class.
Method signatures and docstrings:
- def build_net(self): Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood.
- def set_velocity_on_net(self): Assign per... | Implement the Python class `InterpZhangDual` described below.
Class description:
Implement the InterpZhangDual class.
Method signatures and docstrings:
- def build_net(self): Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood.
- def set_velocity_on_net(self): Assign per... | 30f008596543bb80ec959151598beaefa1125baf | <|skeleton|>
class InterpZhangDual:
def build_net(self):
"""Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood."""
<|body_0|>
def set_velocity_on_net(self):
"""Assign per-node velocities"""
<|body_1|>
def set_samples(self, xy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpZhangDual:
def build_net(self):
"""Build a pseudo grid that has edges for neighbors (like a dual, but including a larger neighborhood."""
self.t_dual = self.g
self.t_net = unstructured_grid.UnstructuredGrid(extra_node_fields=[('value', np.float64), ('dual_cell', np.int32), ('hydr... | the_stack_v2_python_sparse | bathy/interp_zhang.py | rustychris/hor_flow_and_salmon | train | 0 | |
6e7ef100caeaecdd98f0a60d794ecd60934e70d7 | [
"super(ColabTestMixin, cls).setUpClass()\ntesting_startup.TestInit()\nport = portpicker.pick_unused_port()\ncls._server_thread = wsgiapp_testlib.ServerThread(port, name='ServerThread')\ncls._server_thread.StartAndWaitUntilServing()\n_api._API = api.InitHttp(api_endpoint='http://localhost:{}'.format(port))",
"supe... | <|body_start_0|>
super(ColabTestMixin, cls).setUpClass()
testing_startup.TestInit()
port = portpicker.pick_unused_port()
cls._server_thread = wsgiapp_testlib.ServerThread(port, name='ServerThread')
cls._server_thread.StartAndWaitUntilServing()
_api._API = api.InitHttp(api... | A mixin intended for tests that need to leverage GRR's Colab library. | ColabTestMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColabTestMixin:
"""A mixin intended for tests that need to leverage GRR's Colab library."""
def setUpClass(cls) -> None:
"""Performs all initialization needed to interface with GRR's API."""
<|body_0|>
def tearDownClass(cls) -> None:
"""Cleanups all the resources... | stack_v2_sparse_classes_75kplus_train_065277 | 4,924 | permissive | [
{
"docstring": "Performs all initialization needed to interface with GRR's API.",
"name": "setUpClass",
"signature": "def setUpClass(cls) -> None"
},
{
"docstring": "Cleanups all the resources allocated during class initialization.",
"name": "tearDownClass",
"signature": "def tearDownCla... | 2 | stack_v2_sparse_classes_30k_train_051938 | Implement the Python class `ColabTestMixin` described below.
Class description:
A mixin intended for tests that need to leverage GRR's Colab library.
Method signatures and docstrings:
- def setUpClass(cls) -> None: Performs all initialization needed to interface with GRR's API.
- def tearDownClass(cls) -> None: Clean... | Implement the Python class `ColabTestMixin` described below.
Class description:
A mixin intended for tests that need to leverage GRR's Colab library.
Method signatures and docstrings:
- def setUpClass(cls) -> None: Performs all initialization needed to interface with GRR's API.
- def tearDownClass(cls) -> None: Clean... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class ColabTestMixin:
"""A mixin intended for tests that need to leverage GRR's Colab library."""
def setUpClass(cls) -> None:
"""Performs all initialization needed to interface with GRR's API."""
<|body_0|>
def tearDownClass(cls) -> None:
"""Cleanups all the resources... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColabTestMixin:
"""A mixin intended for tests that need to leverage GRR's Colab library."""
def setUpClass(cls) -> None:
"""Performs all initialization needed to interface with GRR's API."""
super(ColabTestMixin, cls).setUpClass()
testing_startup.TestInit()
port = portpick... | the_stack_v2_python_sparse | colab/grr_colab/testing.py | google/grr | train | 4,683 |
ac0df00750e75fc1ef34a23414434c94db189750 | [
"community = request.user.get_admin_community()\nif not community:\n log.user_action(request, request.user, 'Tried to access community admin section without permissions.')\n raise PermissionDenied\nreturn super(CommunityMixin, self).dispatch(request, *args, **kwargs)",
"context = super(CommunityMixin, self)... | <|body_start_0|>
community = request.user.get_admin_community()
if not community:
log.user_action(request, request.user, 'Tried to access community admin section without permissions.')
raise PermissionDenied
return super(CommunityMixin, self).dispatch(request, *args, **kw... | CommunityMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunityMixin:
def dispatch(self, request, *args, **kwargs):
"""Ensures the user is logged in and filters all the users who are not a community administrator."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds the community for which this user is an admin t... | stack_v2_sparse_classes_75kplus_train_065278 | 40,611 | no_license | [
{
"docstring": "Ensures the user is logged in and filters all the users who are not a community administrator.",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Adds the community for which this user is an admin to the request context.",
"na... | 2 | null | Implement the Python class `CommunityMixin` described below.
Class description:
Implement the CommunityMixin class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Ensures the user is logged in and filters all the users who are not a community administrator.
- def get_context_data(se... | Implement the Python class `CommunityMixin` described below.
Class description:
Implement the CommunityMixin class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Ensures the user is logged in and filters all the users who are not a community administrator.
- def get_context_data(se... | 8b7806177e1e245af33b5112c551438b8c0af5d2 | <|skeleton|>
class CommunityMixin:
def dispatch(self, request, *args, **kwargs):
"""Ensures the user is logged in and filters all the users who are not a community administrator."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Adds the community for which this user is an admin t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommunityMixin:
def dispatch(self, request, *args, **kwargs):
"""Ensures the user is logged in and filters all the users who are not a community administrator."""
community = request.user.get_admin_community()
if not community:
log.user_action(request, request.user, 'Tried ... | the_stack_v2_python_sparse | cc3/communityadmin/views.py | qoin-open-source/samen-doen-cc3 | train | 0 | |
e5dd0f28f5ffeacf3f9c6cd64d447b94317ee529 | [
"super().__init__(type, **tags)\nself.filename = None\nif 'doi_prefix' in tags:\n self.name = tags['doi_prefix']\nelif 'service' in tags:\n self.name = tags['service']\nelse:\n self.name = type",
"super().publish(metrics)\nself.filename = join(self.output_path, '{type}_{name}_{now}.json'.format(type=self... | <|body_start_0|>
super().__init__(type, **tags)
self.filename = None
if 'doi_prefix' in tags:
self.name = tags['doi_prefix']
elif 'service' in tags:
self.name = tags['service']
else:
self.name = type
<|end_body_0|>
<|body_start_1|>
sup... | Test class that manages publishing metrics to a JSON file. | JSONFilePublisher | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONFilePublisher:
"""Test class that manages publishing metrics to a JSON file."""
def __init__(self, type, **tags):
"""JSON file provider initialization."""
<|body_0|>
def publish(self, metrics):
"""Publish metrics to JSON file."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_065279 | 1,365 | permissive | [
{
"docstring": "JSON file provider initialization.",
"name": "__init__",
"signature": "def __init__(self, type, **tags)"
},
{
"docstring": "Publish metrics to JSON file.",
"name": "publish",
"signature": "def publish(self, metrics)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037136 | Implement the Python class `JSONFilePublisher` described below.
Class description:
Test class that manages publishing metrics to a JSON file.
Method signatures and docstrings:
- def __init__(self, type, **tags): JSON file provider initialization.
- def publish(self, metrics): Publish metrics to JSON file. | Implement the Python class `JSONFilePublisher` described below.
Class description:
Test class that manages publishing metrics to a JSON file.
Method signatures and docstrings:
- def __init__(self, type, **tags): JSON file provider initialization.
- def publish(self, metrics): Publish metrics to JSON file.
<|skeleton... | 4b9c16f5dfac026ee0e6515e399e25f827dcba74 | <|skeleton|>
class JSONFilePublisher:
"""Test class that manages publishing metrics to a JSON file."""
def __init__(self, type, **tags):
"""JSON file provider initialization."""
<|body_0|>
def publish(self, metrics):
"""Publish metrics to JSON file."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONFilePublisher:
"""Test class that manages publishing metrics to a JSON file."""
def __init__(self, type, **tags):
"""JSON file provider initialization."""
super().__init__(type, **tags)
self.filename = None
if 'doi_prefix' in tags:
self.name = tags['doi_pre... | the_stack_v2_python_sparse | kpiit/publishers/json.py | inveniosoftware-contrib/kpiit | train | 0 |
c6d9d65644db73b45791910010cc63d8c302682b | [
"self.ParseParameters(toggle_param_name=self._TOGGLE_PARAM, required_param_names=self._REQUIRED_PARAMS, optional_param_names=self._OPTIONAL_PARAMS, user_params=user_params)\nself.web = web\nif self.enabled:\n logging.info('Log uploading is enabled')\nelse:\n logging.debug('Log uploading is disabled')\n ret... | <|body_start_0|>
self.ParseParameters(toggle_param_name=self._TOGGLE_PARAM, required_param_names=self._REQUIRED_PARAMS, optional_param_names=self._OPTIONAL_PARAMS, user_params=user_params)
self.web = web
if self.enabled:
logging.info('Log uploading is enabled')
else:
... | Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file util object for uploading logs to distant. _report_file_util_gcs: report file util obj... | LogUploadingFeature | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogUploadingFeature:
"""Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file util object for uploading logs to dista... | stack_v2_sparse_classes_75kplus_train_065280 | 5,446 | no_license | [
{
"docstring": "Initializes the log uploading feature. Args: user_params: A dictionary from parameter name (String) to parameter value. web: (optional) WebFeature, object storing web feature util for test run",
"name": "__init__",
"signature": "def __init__(self, user_params, web=None)"
},
{
"do... | 2 | null | Implement the Python class `LogUploadingFeature` described below.
Class description:
Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file ... | Implement the Python class `LogUploadingFeature` described below.
Class description:
Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file ... | 7095609d6b7db3725cc6285306fc2754307453b0 | <|skeleton|>
class LogUploadingFeature:
"""Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file util object for uploading logs to dista... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogUploadingFeature:
"""Feature object for log uploading functionality. Attributes: enabled: boolean, True if log uploading is enabled, False otherwise. web: (optional) WebFeature, object storing web feature util for test run. _report_file_util: report file util object for uploading logs to distant. _report_f... | the_stack_v2_python_sparse | utils/python/reporting/log_uploading_utils.py | t-head-aosp/platform-test-vts | train | 0 |
a79126ec462ff5b787b189af57da053a51fad5dd | [
"if not email:\n raise ValueError('Students must have an email address.')\nextra_fields['date_joined'] = timezone.now()\nextra_fields['last_login'] = extra_fields['date_joined']\nstudent = self.model(email=self.normalize_email(email), **extra_fields)\nstudent.set_password(password)\nstudent.save()\nreturn studen... | <|body_start_0|>
if not email:
raise ValueError('Students must have an email address.')
extra_fields['date_joined'] = timezone.now()
extra_fields['last_login'] = extra_fields['date_joined']
student = self.model(email=self.normalize_email(email), **extra_fields)
studen... | StudentManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentManager:
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a Student with the given email and password."""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Creates and saves a superuser with the given e... | stack_v2_sparse_classes_75kplus_train_065281 | 4,498 | permissive | [
{
"docstring": "Creates and saves a Student with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password=None, **extra_fields)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "cre... | 2 | null | Implement the Python class `StudentManager` described below.
Class description:
Implement the StudentManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, **extra_fields): Creates and saves a Student with the given email and password.
- def create_superuser(self, email, passwo... | Implement the Python class `StudentManager` described below.
Class description:
Implement the StudentManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, **extra_fields): Creates and saves a Student with the given email and password.
- def create_superuser(self, email, passwo... | 230afc2a54f2293ef888ac250c91f06b8d324c94 | <|skeleton|>
class StudentManager:
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a Student with the given email and password."""
<|body_0|>
def create_superuser(self, email, password, **extra_fields):
"""Creates and saves a superuser with the given e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudentManager:
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a Student with the given email and password."""
if not email:
raise ValueError('Students must have an email address.')
extra_fields['date_joined'] = timezone.now()
extr... | the_stack_v2_python_sparse | profile/managers.py | bobort/cheese | train | 0 | |
9b6aa1307c3a22123aa6636db3c8baa06c2773ca | [
"self.value = value\nself.description = description\nself.default = default",
"v = '\"%s\"' % self.value if type(self.value) is str else str(self.value)\nd = {'value': v}\nd['default'] = ' (Default)' if self.default else ''\nd['description'] = ' %s' % self.description if self.description != None else ''\nd['link'... | <|body_start_0|>
self.value = value
self.description = description
self.default = default
<|end_body_0|>
<|body_start_1|>
v = '"%s"' % self.value if type(self.value) is str else str(self.value)
d = {'value': v}
d['default'] = ' (Default)' if self.default else ''
... | Class representing a value for an Option. | OptionValue | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionValue:
"""Class representing a value for an Option."""
def __init__(self, value, description=None, default=False):
"""Initialisation. @param value The value. @param description (str) A description for this value. @param default (bool) If this value is the default value."""
... | stack_v2_sparse_classes_75kplus_train_065282 | 11,864 | permissive | [
{
"docstring": "Initialisation. @param value The value. @param description (str) A description for this value. @param default (bool) If this value is the default value.",
"name": "__init__",
"signature": "def __init__(self, value, description=None, default=False)"
},
{
"docstring": "Render this ... | 2 | stack_v2_sparse_classes_30k_train_028407 | Implement the Python class `OptionValue` described below.
Class description:
Class representing a value for an Option.
Method signatures and docstrings:
- def __init__(self, value, description=None, default=False): Initialisation. @param value The value. @param description (str) A description for this value. @param d... | Implement the Python class `OptionValue` described below.
Class description:
Class representing a value for an Option.
Method signatures and docstrings:
- def __init__(self, value, description=None, default=False): Initialisation. @param value The value. @param description (str) A description for this value. @param d... | c20c06b85bc04902134ab37442763ef6660a35f5 | <|skeleton|>
class OptionValue:
"""Class representing a value for an Option."""
def __init__(self, value, description=None, default=False):
"""Initialisation. @param value The value. @param description (str) A description for this value. @param default (bool) If this value is the default value."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptionValue:
"""Class representing a value for an Option."""
def __init__(self, value, description=None, default=False):
"""Initialisation. @param value The value. @param description (str) A description for this value. @param default (bool) If this value is the default value."""
self.valu... | the_stack_v2_python_sparse | olof/configuration.py | Roel/Gyrid-server | train | 0 |
8cf4ff0353da79507a8a74169e60bffb8dce068f | [
"address_feature = AddressFeature(date=Date, address=Address, no_of_scc=No_of_SCC, no_of_wcc=No_of_WCC, btc_received=BTC_Received, btc_sent=BTC_Sent, activity_level=Activity_Level, clustering_coeff=Clustering_Coeff, pearsoncc=PearsonCC, maximal_balance=Maximal_Balance, current_balance=Current_Balance)\ndb_session.a... | <|body_start_0|>
address_feature = AddressFeature(date=Date, address=Address, no_of_scc=No_of_SCC, no_of_wcc=No_of_WCC, btc_received=BTC_Received, btc_sent=BTC_Sent, activity_level=Activity_Level, clustering_coeff=Clustering_Coeff, pearsoncc=PearsonCC, maximal_balance=Maximal_Balance, current_balance=Current_Ba... | Class implementing address feature by date | AddressFeatureByDateEndpoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressFeatureByDateEndpoint:
"""Class implementing address feature by date"""
def post(self, Date, Address, No_of_SCC=None, No_of_WCC=None, BTC_Received=None, BTC_Sent=None, Activity_Level=None, Clustering_Coeff=None, PearsonCC=None, Maximal_Balance=None, Current_Balance=None):
"""M... | stack_v2_sparse_classes_75kplus_train_065283 | 5,404 | no_license | [
{
"docstring": "Method for POST request :param Date: :param Address: :param No_of_SCC: :param No_of_WCC: :param BTC_Received: :param BTC_Sent: :param Activity_Level: :param Clustering_Coeff: :param PearsonCC: :param Maximal_Balance: :param Current_Balance:",
"name": "post",
"signature": "def post(self, ... | 3 | null | Implement the Python class `AddressFeatureByDateEndpoint` described below.
Class description:
Class implementing address feature by date
Method signatures and docstrings:
- def post(self, Date, Address, No_of_SCC=None, No_of_WCC=None, BTC_Received=None, BTC_Sent=None, Activity_Level=None, Clustering_Coeff=None, Pears... | Implement the Python class `AddressFeatureByDateEndpoint` described below.
Class description:
Class implementing address feature by date
Method signatures and docstrings:
- def post(self, Date, Address, No_of_SCC=None, No_of_WCC=None, BTC_Received=None, BTC_Sent=None, Activity_Level=None, Clustering_Coeff=None, Pears... | 83a7000c4aa8020481771c0956a9918a335fc2f5 | <|skeleton|>
class AddressFeatureByDateEndpoint:
"""Class implementing address feature by date"""
def post(self, Date, Address, No_of_SCC=None, No_of_WCC=None, BTC_Received=None, BTC_Sent=None, Activity_Level=None, Clustering_Coeff=None, PearsonCC=None, Maximal_Balance=None, Current_Balance=None):
"""M... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressFeatureByDateEndpoint:
"""Class implementing address feature by date"""
def post(self, Date, Address, No_of_SCC=None, No_of_WCC=None, BTC_Received=None, BTC_Sent=None, Activity_Level=None, Clustering_Coeff=None, PearsonCC=None, Maximal_Balance=None, Current_Balance=None):
"""Method for POS... | the_stack_v2_python_sparse | foundations/bitcoin_api/resources/graph/address_feature.py | tskiranmayee/Blockchain-Analysis-Project | train | 0 |
a6c1f1f2f26cce07df3a254f09746128ddd37c65 | [
"self.q = deque([(0, 0)])\nself.food = food[::-1]\nself.w = width\nself.h = height",
"r, c = self.q[-1]\nif direction == 'U':\n nr, nc = (r - 1, c)\nelif direction == 'L':\n nr, nc = (r, c - 1)\nelif direction == 'R':\n nr, nc = (r, c + 1)\nelse:\n nr, nc = (r + 1, c)\nif self.food and [nr, nc] == sel... | <|body_start_0|>
self.q = deque([(0, 0)])
self.food = food[::-1]
self.w = width
self.h = height
<|end_body_0|>
<|body_start_1|>
r, c = self.q[-1]
if direction == 'U':
nr, nc = (r - 1, c)
elif direction == 'L':
nr, nc = (r, c - 1)
e... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""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]. :typ... | stack_v2_sparse_classes_75kplus_train_065284 | 1,600 | 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]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_040132 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 3129438b032d3aeb87c6ac5c4733df0ebc1272ba | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""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]. :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
"""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]. :type width: int :... | the_stack_v2_python_sparse | solu/353. Design Snake Game.py | coolmich/py-leetcode | train | 3 | |
47a85fa77491dc7588f4828becadd070abc5390f | [
"\"\"\"\n Classification 1: consider two neighbors\n i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.\n when i is not robbed, i-1 and i+1 can be any status robbed/un-robbed, it's like the houses are in a line\n when i+1 is not robbed, i and i+2 c... | <|body_start_0|>
"""
Classification 1: consider two neighbors
i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.
when i is not robbed, i-1 and i+1 can be any status robbed/un-robbed, it's like the houses are in a line
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line_case(nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
Classification 1: consider two neighb... | stack_v2_sparse_classes_75kplus_train_065285 | 1,926 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_line_case",
"signature": "def rob_line_case(nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054668 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line_case(nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line_case(nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | b6942c05c27556e5fe47879e8b823845c84c5430 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line_case(nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
"""
Classification 1: consider two neighbors
i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.
when i is not robbed, i-1 and i+1 can b... | the_stack_v2_python_sparse | Algorithms/leetcode/213_house_robber_II.py | leeo1116/PyCharm | train | 0 | |
879c247b73b1abf367c0e2ae2016d3dcdc21d7f8 | [
"active = bot_update.check_valid_host(master, builder, slave) or force\noutput = {'did_run': active, 'patch_failure': False}\nif active:\n properties = {property_name: self.gen_revision(project_name, git_mode) for project_name, property_name in revision_mapping.iteritems()}\n if not git_mode:\n propert... | <|body_start_0|>
active = bot_update.check_valid_host(master, builder, slave) or force
output = {'did_run': active, 'patch_failure': False}
if active:
properties = {property_name: self.gen_revision(project_name, git_mode) for project_name, property_name in revision_mapping.iteritems(... | BotUpdateTestApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
<|body_0|>
def gen_revision(project, GIT_... | stack_v2_sparse_classes_75kplus_train_065286 | 1,905 | no_license | [
{
"docstring": "Deterministically synthesize json.output test data for gclient's --output-json option.",
"name": "output_json",
"signature": "def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False)"
},
{
"docstring": "Hash project... | 2 | stack_v2_sparse_classes_30k_train_022496 | Implement the Python class `BotUpdateTestApi` described below.
Class description:
Implement the BotUpdateTestApi class.
Method signatures and docstrings:
- def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False): Deterministically synthesize json.outpu... | Implement the Python class `BotUpdateTestApi` described below.
Class description:
Implement the BotUpdateTestApi class.
Method signatures and docstrings:
- def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False): Deterministically synthesize json.outpu... | 237c7e2c8fd3cf632f3bcdc9cc5da2d47ea7f153 | <|skeleton|>
class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
<|body_0|>
def gen_revision(project, GIT_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
active = bot_update.check_valid_host(master, builder, slave)... | the_stack_v2_python_sparse | scripts/slave/recipe_modules/bot_update/test_api.py | bopopescu/build_internal | train | 0 | |
9a6a9e4d52efeba94f0a130200924ebf03db354c | [
"if len(word1) == 0 or len(word2) == 0:\n return len(word1) or len(word2)\nreturn min(self.minDistance(word1[1:], word2) + 1, self.minDistance(word1, word2[1:]) + 1, self.minDistance(word1[1:], word2[1:]) + 1 - (word1[0] == word2[0]))",
"if len(word1) == 0 or len(word2) == 0:\n return len(word1) or len(word... | <|body_start_0|>
if len(word1) == 0 or len(word2) == 0:
return len(word1) or len(word2)
return min(self.minDistance(word1[1:], word2) + 1, self.minDistance(word1, word2[1:]) + 1, self.minDistance(word1[1:], word2[1:]) + 1 - (word1[0] == word2[0]))
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""递归算法 :param word1: :param word2: :return:"""
<|body_0|>
def minDistance(self, word1: str, word2: str) -> int:
"""动态规划算法 :param word1: :param word2: :return:"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_065287 | 1,768 | no_license | [
{
"docstring": "递归算法 :param word1: :param word2: :return:",
"name": "minDistance",
"signature": "def minDistance(self, word1: str, word2: str) -> int"
},
{
"docstring": "动态规划算法 :param word1: :param word2: :return:",
"name": "minDistance",
"signature": "def minDistance(self, word1: str, w... | 2 | stack_v2_sparse_classes_30k_train_045995 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: 递归算法 :param word1: :param word2: :return:
- def minDistance(self, word1: str, word2: str) -> int: 动态规划算法 :param word1: :para... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: 递归算法 :param word1: :param word2: :return:
- def minDistance(self, word1: str, word2: str) -> int: 动态规划算法 :param word1: :para... | f88576e6b65992e3624ecbdbe3e5b251b77dfa70 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""递归算法 :param word1: :param word2: :return:"""
<|body_0|>
def minDistance(self, word1: str, word2: str) -> int:
"""动态规划算法 :param word1: :param word2: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""递归算法 :param word1: :param word2: :return:"""
if len(word1) == 0 or len(word2) == 0:
return len(word1) or len(word2)
return min(self.minDistance(word1[1:], word2) + 1, self.minDistance(word1, word2[1:]) + 1, ... | the_stack_v2_python_sparse | mixleet/leecode/72.py | spiritdjy/MixLeetCode | train | 0 | |
320781066fda98cb99ccf78128f12b6bb86fa075 | [
"ind = np.random.randint(len(img))\nr_band = (img[ind, :, :, 0] - np.min(img[ind, :, :, 0])) / (np.max(img[ind, :, :, 0]) - np.min(img[ind, :, :, 0]))\ng_band = (img[ind, :, :, 1] - np.min(img[ind, :, :, 1])) / (np.max(img[ind, :, :, 1]) - np.min(img[ind, :, :, 1]))\nb_band = (img[ind, :, :, 2] - np.min(img[ind, :,... | <|body_start_0|>
ind = np.random.randint(len(img))
r_band = (img[ind, :, :, 0] - np.min(img[ind, :, :, 0])) / (np.max(img[ind, :, :, 0]) - np.min(img[ind, :, :, 0]))
g_band = (img[ind, :, :, 1] - np.min(img[ind, :, :, 1])) / (np.max(img[ind, :, :, 1]) - np.min(img[ind, :, :, 1]))
b_band ... | Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights. | SatPlotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SatPlotter:
"""Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights."""
def plot_image_and_result(self, img, val, result):
"""Straight-forward plot of a result using a model with only the input... | stack_v2_sparse_classes_75kplus_train_065288 | 3,886 | no_license | [
{
"docstring": "Straight-forward plot of a result using a model with only the input image (no other engineered features).",
"name": "plot_image_and_result",
"signature": "def plot_image_and_result(self, img, val, result)"
},
{
"docstring": "Plots images, labels, and prediction probabilities per ... | 3 | stack_v2_sparse_classes_30k_train_034083 | Implement the Python class `SatPlotter` described below.
Class description:
Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights.
Method signatures and docstrings:
- def plot_image_and_result(self, img, val, result): Straight-f... | Implement the Python class `SatPlotter` described below.
Class description:
Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights.
Method signatures and docstrings:
- def plot_image_and_result(self, img, val, result): Straight-f... | 06e51368356c4eda589e7ac3a43f8a94a7cc28ea | <|skeleton|>
class SatPlotter:
"""Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights."""
def plot_image_and_result(self, img, val, result):
"""Straight-forward plot of a result using a model with only the input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SatPlotter:
"""Simple plotting tools for visualizing results of USatellite. May want to reuse as we vary experiments and save various models and their weights."""
def plot_image_and_result(self, img, val, result):
"""Straight-forward plot of a result using a model with only the input image (no ot... | the_stack_v2_python_sparse | usattelite/plot_utils/plotting_utils.py | macdonc2/usatellite | train | 1 |
5f1312f52cf08e214a5d22a1a2a5aa61b1e1121b | [
"end_idxs = []\nidx = 0\nres = ''\nfor s in strs:\n idx += len(s)\n end_idxs.append(str(idx))\n res += s\nend_idx_str = ','.join(end_idxs)\nres = '[' + end_idx_str + ']' + res\nreturn res",
"i = 1\nwhile s[i] != ']':\n i += 1\nend_idx_str = s[1:i]\nend_idxs = end_idx_str.split(',')\nencoded_s = s[i + ... | <|body_start_0|>
end_idxs = []
idx = 0
res = ''
for s in strs:
idx += len(s)
end_idxs.append(str(idx))
res += s
end_idx_str = ','.join(end_idxs)
res = '[' + end_idx_str + ']' + res
return res
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
e... | stack_v2_sparse_classes_75kplus_train_065289 | 1,079 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: List[str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> List[str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_037979 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: List[str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> List[str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: List[str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> List[str]: Decodes a single string to a list of strings.
<|skelet... | 00fd1397b65c68a303fcf963db3e28cd35c1c003 | <|skeleton|>
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
end_idxs = []
idx = 0
res = ''
for s in strs:
idx += len(s)
end_idxs.append(str(idx))
res += s
end_idx_str = ','.join(end_idx... | the_stack_v2_python_sparse | leetcode/271. Encode and Decode Strings.py | cuiy0006/Algorithms | train | 0 | |
b0b32fce8c587402f58f7427c4dbd47a32150724 | [
"self.name = name\nself.event = event_instance\nself.visible = visible\nif inspect.isclass(self.event):\n raise Exception(\"Class given when instance expected for option '{}'\".format(self.name))",
"def _do_apply():\n self.event.apply(game)\nif self.visible:\n return widgets.Button(root, self.name, _do_a... | <|body_start_0|>
self.name = name
self.event = event_instance
self.visible = visible
if inspect.isclass(self.event):
raise Exception("Class given when instance expected for option '{}'".format(self.name))
<|end_body_0|>
<|body_start_1|>
def _do_apply():
s... | The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled. | Option | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled."""
def __init__(self, name, event_instance: 'event.GameEvent', visible: bool=True) -> None:
"""Initialize the option. :param name: The name of the option, used for the te... | stack_v2_sparse_classes_75kplus_train_065290 | 9,983 | permissive | [
{
"docstring": "Initialize the option. :param name: The name of the option, used for the text on the button :param event_instance: A GameEvent instance which can be applied on the button press event :param visible: If the option is visible",
"name": "__init__",
"signature": "def __init__(self, name, eve... | 2 | stack_v2_sparse_classes_30k_train_002693 | Implement the Python class `Option` described below.
Class description:
The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled.
Method signatures and docstrings:
- def __init__(self, name, event_instance: 'event.GameEvent', visible: bool=True) -> None: Initialize the opt... | Implement the Python class `Option` described below.
Class description:
The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled.
Method signatures and docstrings:
- def __init__(self, name, event_instance: 'event.GameEvent', visible: bool=True) -> None: Initialize the opt... | 546b55b97275a05597cd40020846285d7baf7fb0 | <|skeleton|>
class Option:
"""The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled."""
def __init__(self, name, event_instance: 'event.GameEvent', visible: bool=True) -> None:
"""Initialize the option. :param name: The name of the option, used for the te... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Option:
"""The definition of an option on the GameView. An option encodes a name, an event, and if it is enabled."""
def __init__(self, name, event_instance: 'event.GameEvent', visible: bool=True) -> None:
"""Initialize the option. :param name: The name of the option, used for the text on the but... | the_stack_v2_python_sparse | rpg/ui/options.py | tvarney/txtrpg | train | 0 |
3c927c3f7dd7e884df10ae7262a55d8479dae735 | [
"valid_names_to_test = ['Tom', 'tom', ' Tom', 'Tom ', ' tom', 'tom ']\nfor name in valid_names_to_test:\n self.assertTrue(validate_name_part(name))",
"invalid_names_to_test = [\"Tom'\", '123', ' Tom 123', 'Tom#', ' ']\nfor name in invalid_names_to_test:\n self.assertFalse(validate_name_part(name))"
] | <|body_start_0|>
valid_names_to_test = ['Tom', 'tom', ' Tom', 'Tom ', ' tom', 'tom ']
for name in valid_names_to_test:
self.assertTrue(validate_name_part(name))
<|end_body_0|>
<|body_start_1|>
invalid_names_to_test = ["Tom'", '123', ' Tom 123', 'Tom#', ' ']
for name in in... | Test for functions in the function_library.py file | NamePartTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamePartTestCase:
"""Test for functions in the function_library.py file"""
def test_valid_name_part(self):
"""Here is a bunch of values I think should work"""
<|body_0|>
def test_invalid_name_part(self):
"""Here is a bunch of values I think should not work"""
... | stack_v2_sparse_classes_75kplus_train_065291 | 735 | no_license | [
{
"docstring": "Here is a bunch of values I think should work",
"name": "test_valid_name_part",
"signature": "def test_valid_name_part(self)"
},
{
"docstring": "Here is a bunch of values I think should not work",
"name": "test_invalid_name_part",
"signature": "def test_invalid_name_part(... | 2 | stack_v2_sparse_classes_30k_train_012489 | Implement the Python class `NamePartTestCase` described below.
Class description:
Test for functions in the function_library.py file
Method signatures and docstrings:
- def test_valid_name_part(self): Here is a bunch of values I think should work
- def test_invalid_name_part(self): Here is a bunch of values I think s... | Implement the Python class `NamePartTestCase` described below.
Class description:
Test for functions in the function_library.py file
Method signatures and docstrings:
- def test_valid_name_part(self): Here is a bunch of values I think should work
- def test_invalid_name_part(self): Here is a bunch of values I think s... | 7a331478914c6cafd79d8b3c6b18afb95429d52f | <|skeleton|>
class NamePartTestCase:
"""Test for functions in the function_library.py file"""
def test_valid_name_part(self):
"""Here is a bunch of values I think should work"""
<|body_0|>
def test_invalid_name_part(self):
"""Here is a bunch of values I think should not work"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NamePartTestCase:
"""Test for functions in the function_library.py file"""
def test_valid_name_part(self):
"""Here is a bunch of values I think should work"""
valid_names_to_test = ['Tom', 'tom', ' Tom', 'Tom ', ' tom', 'tom ']
for name in valid_names_to_test:
self.ass... | the_stack_v2_python_sparse | week_04-05_lectures/Testing_Your_Functions/test_cases/test_functions.py | sbrohl3/projects | train | 0 |
42451d2b858088437ca224d6e1c7cb347d3a5d85 | [
"dept_queryset = Dept.objects.filter(id=kwargs.get('pk')).first()\nparentId = dept_queryset.parentId if dept_queryset else ''\nqueryset = self.queryset.exclude(parentId=parentId).order_by('orderNum')\nif hasattr(self, 'handle_logging'):\n self.handle_logging(request, *args, **kwargs)\nserializer = self.get_seria... | <|body_start_0|>
dept_queryset = Dept.objects.filter(id=kwargs.get('pk')).first()
parentId = dept_queryset.parentId if dept_queryset else ''
queryset = self.queryset.exclude(parentId=parentId).order_by('orderNum')
if hasattr(self, 'handle_logging'):
self.handle_logging(reques... | 部门管理 的CRUD视图 | DeptModelViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeptModelViewSet:
"""部门管理 的CRUD视图"""
def exclude_list(self, request: Request, *args, **kwargs):
"""过滤剔除同级部门 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def tree_select_list(self, request: Request, *args, **kwargs):
"""递归获取部门树 :param request... | stack_v2_sparse_classes_75kplus_train_065292 | 15,347 | permissive | [
{
"docstring": "过滤剔除同级部门 :param request: :param args: :param kwargs: :return:",
"name": "exclude_list",
"signature": "def exclude_list(self, request: Request, *args, **kwargs)"
},
{
"docstring": "递归获取部门树 :param request: :param args: :param kwargs: :return:",
"name": "tree_select_list",
"... | 3 | stack_v2_sparse_classes_30k_train_020271 | Implement the Python class `DeptModelViewSet` described below.
Class description:
部门管理 的CRUD视图
Method signatures and docstrings:
- def exclude_list(self, request: Request, *args, **kwargs): 过滤剔除同级部门 :param request: :param args: :param kwargs: :return:
- def tree_select_list(self, request: Request, *args, **kwargs): 递... | Implement the Python class `DeptModelViewSet` described below.
Class description:
部门管理 的CRUD视图
Method signatures and docstrings:
- def exclude_list(self, request: Request, *args, **kwargs): 过滤剔除同级部门 :param request: :param args: :param kwargs: :return:
- def tree_select_list(self, request: Request, *args, **kwargs): 递... | 32b598f304bc41eebd4f8173236038120cdfaf87 | <|skeleton|>
class DeptModelViewSet:
"""部门管理 的CRUD视图"""
def exclude_list(self, request: Request, *args, **kwargs):
"""过滤剔除同级部门 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def tree_select_list(self, request: Request, *args, **kwargs):
"""递归获取部门树 :param request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeptModelViewSet:
"""部门管理 的CRUD视图"""
def exclude_list(self, request: Request, *args, **kwargs):
"""过滤剔除同级部门 :param request: :param args: :param kwargs: :return:"""
dept_queryset = Dept.objects.filter(id=kwargs.get('pk')).first()
parentId = dept_queryset.parentId if dept_queryset e... | the_stack_v2_python_sparse | apps/vadmin/permission/views.py | kuangzhanzhizi/ansible-ui-backend | train | 0 |
865c1b6ab8850290f33908899ef890bce4091f2d | [
"if isinstance(value, int):\n try:\n value = self.klass(value)\n except:\n self.error(object, name, value)\nelif isinstance(value, tuple):\n try:\n value = self.klass(*value)\n except:\n self.error(object, name, value)\nif isinstance(value, self.klass):\n return value\nsel... | <|body_start_0|>
if isinstance(value, int):
try:
value = self.klass(value)
except:
self.error(object, name, value)
elif isinstance(value, tuple):
try:
value = self.klass(*value)
except:
self.e... | Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one. | HasMargin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HasMargin:
"""Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one."""
def validate(self, object, name, value):
"""Validates that a specified value is valid for this trait."""
<|body_0|>
def get_default_value(self)... | stack_v2_sparse_classes_75kplus_train_065293 | 15,262 | no_license | [
{
"docstring": "Validates that a specified value is valid for this trait.",
"name": "validate",
"signature": "def validate(self, object, name, value)"
},
{
"docstring": "Returns a tuple of the form: ( default_value_type, default_value ) which describes the default value for this trait.",
"na... | 2 | stack_v2_sparse_classes_30k_train_018104 | Implement the Python class `HasMargin` described below.
Class description:
Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one.
Method signatures and docstrings:
- def validate(self, object, name, value): Validates that a specified value is valid for this trai... | Implement the Python class `HasMargin` described below.
Class description:
Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one.
Method signatures and docstrings:
- def validate(self, object, name, value): Validates that a specified value is valid for this trai... | 5466f5858dbd2f1f082fa0d7417b57c8fb068fad | <|skeleton|>
class HasMargin:
"""Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one."""
def validate(self, object, name, value):
"""Validates that a specified value is valid for this trait."""
<|body_0|>
def get_default_value(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HasMargin:
"""Defines a trait whose value must be a Margin object or an integer or tuple value that can be converted to one."""
def validate(self, object, name, value):
"""Validates that a specified value is valid for this trait."""
if isinstance(value, int):
try:
... | the_stack_v2_python_sparse | maps/build/Traits/enthought/traits/ui/ui_traits.py | m-elhussieny/code | train | 0 |
0c635c16e4453ce03a5fe702978033c32a4b1a2c | [
"if not self.context.get('request').organization:\n raise serializers.ValidationError(detail='Cannot create without an organization')\nattrs['organization'] = self.context.get('request').organization\nreturn attrs",
"bill = validated_data.get('bill')\ngroup = validated_data.get('group')\nqueryset = Wrapper.obj... | <|body_start_0|>
if not self.context.get('request').organization:
raise serializers.ValidationError(detail='Cannot create without an organization')
attrs['organization'] = self.context.get('request').organization
return attrs
<|end_body_0|>
<|body_start_1|>
bill = validated_... | WrapperSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WrapperSerializer:
def validate(self, attrs):
"""We don't allow the frontend to dictate the organization. :param attrs: :return:"""
<|body_0|>
def create(self, validated_data):
"""This is sort of shitty and matt will likely mad, but we have to use a custom `get_or_cr... | stack_v2_sparse_classes_75kplus_train_065294 | 7,295 | no_license | [
{
"docstring": "We don't allow the frontend to dictate the organization. :param attrs: :return:",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "This is sort of shitty and matt will likely mad, but we have to use a custom `get_or_create` logic here because the va... | 2 | null | Implement the Python class `WrapperSerializer` described below.
Class description:
Implement the WrapperSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): We don't allow the frontend to dictate the organization. :param attrs: :return:
- def create(self, validated_data): This is sort of s... | Implement the Python class `WrapperSerializer` described below.
Class description:
Implement the WrapperSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): We don't allow the frontend to dictate the organization. :param attrs: :return:
- def create(self, validated_data): This is sort of s... | 604a5c5d933815ab4b51b3f24b1cbd0b71c18133 | <|skeleton|>
class WrapperSerializer:
def validate(self, attrs):
"""We don't allow the frontend to dictate the organization. :param attrs: :return:"""
<|body_0|>
def create(self, validated_data):
"""This is sort of shitty and matt will likely mad, but we have to use a custom `get_or_cr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WrapperSerializer:
def validate(self, attrs):
"""We don't allow the frontend to dictate the organization. :param attrs: :return:"""
if not self.context.get('request').organization:
raise serializers.ValidationError(detail='Cannot create without an organization')
attrs['orga... | the_stack_v2_python_sparse | capitolzen/proposals/api/app/serializers.py | CapitolZen/CapitolZen-Backend | train | 0 | |
bccfdfe34d520f901c739e1cc6b231c9fcdcb6c2 | [
"if not isinstance(param_name, HyperParameter):\n raise ValueError('Invalid param_name type {}, should be Hyperparameter type.'.format(type(param_name)))\nif not param_name.check_legal(value):\n raise ValueError('Illegal hyperparameter value {}'.format(value))\nreturn object.__new__(cls)",
"self.param_name ... | <|body_start_0|>
if not isinstance(param_name, HyperParameter):
raise ValueError('Invalid param_name type {}, should be Hyperparameter type.'.format(type(param_name)))
if not param_name.check_legal(value):
raise ValueError('Illegal hyperparameter value {}'.format(value))
... | Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value. | ForbiddenEqualsClause | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForbiddenEqualsClause:
"""Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value."""
def __new__(cls, param_name, value):
"""Build new class."""
<|body_0|>
def __init__(self, param_name, value):
"""Init ForbiddenEqualsClause, _dict: {... | stack_v2_sparse_classes_75kplus_train_065295 | 2,311 | permissive | [
{
"docstring": "Build new class.",
"name": "__new__",
"signature": "def __new__(cls, param_name, value)"
},
{
"docstring": "Init ForbiddenEqualsClause, _dict: {'loss': 'hinge'}.",
"name": "__init__",
"signature": "def __init__(self, param_name, value)"
}
] | 2 | null | Implement the Python class `ForbiddenEqualsClause` described below.
Class description:
Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value.
Method signatures and docstrings:
- def __new__(cls, param_name, value): Build new class.
- def __init__(self, param_name, value): Init ForbiddenE... | Implement the Python class `ForbiddenEqualsClause` described below.
Class description:
Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value.
Method signatures and docstrings:
- def __new__(cls, param_name, value): Build new class.
- def __init__(self, param_name, value): Init ForbiddenE... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class ForbiddenEqualsClause:
"""Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value."""
def __new__(cls, param_name, value):
"""Build new class."""
<|body_0|>
def __init__(self, param_name, value):
"""Init ForbiddenEqualsClause, _dict: {... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForbiddenEqualsClause:
"""Forbidden Equals Clause. :param str param_name: hp's name. :param value: hp's value."""
def __new__(cls, param_name, value):
"""Build new class."""
if not isinstance(param_name, HyperParameter):
raise ValueError('Invalid param_name type {}, should be ... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/core/hyperparameter_space/common/forbidden.py | Huawei-Ascend/modelzoo | train | 1 |
114153d53207976669032450fd46630da6b8c20a | [
"assert sampling_type in ['gaussian', 'uniform']\nname_to_transform_func = name_to_transform_func or _NAME_TO_TRANSFORM_FUNC\nlevel_to_arg = level_to_arg or _LEVEL_TO_ARG\ntransform_max_paras = transform_max_paras or _TRANSFORM_MAX_PARAMS\nself.transform_hparas = transform_hparas or TRANSFORM_DEFAULT_HPARAS\nself.s... | <|body_start_0|>
assert sampling_type in ['gaussian', 'uniform']
name_to_transform_func = name_to_transform_func or _NAME_TO_TRANSFORM_FUNC
level_to_arg = level_to_arg or _LEVEL_TO_ARG
transform_max_paras = transform_max_paras or _TRANSFORM_MAX_PARAMS
self.transform_hparas = tran... | AugmentTransform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, A... | stack_v2_sparse_classes_75kplus_train_065296 | 17,662 | permissive | [
{
"docstring": "The AugmentTransform composes a video transform that performs augmentation based on a maximum magnitude. AugmentTransform also offers flexible ways to generate augmentation magnitude based on different sampling strategies. Args: transform_name (str): The name of the video transform function. mag... | 3 | stack_v2_sparse_classes_30k_train_027347 | Implement the Python class `AugmentTransform` described below.
Class description:
Implement the AugmentTransform class.
Method signatures and docstrings:
- def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dic... | Implement the Python class `AugmentTransform` described below.
Class description:
Implement the AugmentTransform class.
Method signatures and docstrings:
- def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dic... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, Any]]=None, sam... | the_stack_v2_python_sparse | pytorchvideo/transforms/augmentations.py | xchani/pytorchvideo | train | 0 | |
c72ebb750c3a0587e7bf67b6fd43f6525c5705a3 | [
"self.project = cw.open_project(project_file)\nself.num_samples = attack_window.stop - attack_window.start\nif attack_direction == AttackDirection.INPUT:\n self.texts = np.vstack(self.project.textins[trace_slice])\nelse:\n self.texts = np.vstack(self.project.textouts[trace_slice])\nself.traces = np.asarray(se... | <|body_start_0|>
self.project = cw.open_project(project_file)
self.num_samples = attack_window.stop - attack_window.start
if attack_direction == AttackDirection.INPUT:
self.texts = np.vstack(self.project.textins[trace_slice])
else:
self.texts = np.vstack(self.proj... | Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple instances (workers) of this class and initializing each worker with a subset of th... | TraceWorker | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraceWorker:
"""Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple instances (workers) of this class and initi... | stack_v2_sparse_classes_75kplus_train_065297 | 23,127 | permissive | [
{
"docstring": "Inits a TraceWorker. Args: project_file: A Chipwhisperer project file. trace_slice: Traces assigned to this worker. attack_window: Samples to process. attack_direction: Attack direction.",
"name": "__init__",
"signature": "def __init__(self, project_file, trace_slice, attack_window, atta... | 4 | stack_v2_sparse_classes_30k_train_038610 | Implement the Python class `TraceWorker` described below.
Class description:
Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple inst... | Implement the Python class `TraceWorker` described below.
Class description:
Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple inst... | e64e76dfd09f8ac23ca8ba42465420e63e3c5381 | <|skeleton|>
class TraceWorker:
"""Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple instances (workers) of this class and initi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TraceWorker:
"""Class for performing distributed computations on power traces. This class provides methods for performing distributed computations on power traces such as computing the mean, the standard deviation, and filtering. After creating multiple instances (workers) of this class and initializing each ... | the_stack_v2_python_sparse | cw/cw305/ceca.py | mfkiwl/ot-sca-side-channel-analysis | train | 0 |
8e79beb2aa31bd126e63deaddf60b57da985beac | [
"if target == trackSum:\n self.res.append(track[:])\n return\nfor i in range(k, len(candidates)):\n if trackSum + candidates[i] > target:\n continue\n track.append(candidates[i])\n trackSum += candidates[i]\n self.backtrack(candidates, i, track, trackSum, target)\n track.pop()\n track... | <|body_start_0|>
if target == trackSum:
self.res.append(track[:])
return
for i in range(k, len(candidates)):
if trackSum + candidates[i] > target:
continue
track.append(candidates[i])
trackSum += candidates[i]
self.b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] ... | stack_v2_sparse_classes_75kplus_train_065298 | 1,096 | no_license | [
{
"docstring": ":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int",
"name": "backtrack",
"signature": "def backtrack(self, candidates, k, track, trackSum, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[Li... | 2 | stack_v2_sparse_classes_30k_train_025626 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, candidates, k, track, trackSum, target): :type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int
- def combinati... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, candidates, k, track, trackSum, target): :type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int
- def combinati... | 532ceca2c7ded27fd446ee540a3c906b4135a257 | <|skeleton|>
class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
if target == trackSum:
self.res.append(track[:])
return
for i in range(k, len(candi... | the_stack_v2_python_sparse | pyland/solutions/sum_to_target_bfs.py | yerassyldanay/leetcode | train | 0 | |
cd1cf625e58385e673ac0ad20f2346e6d7610a25 | [
"configs = None\nconfigsDao = ConfigsDao()\ntry:\n configs = configsDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn configs",
"record = None\nconfigsDao = ConfigsDao()\ntry:\n record = configsDao.edit(args)\nexcept Exception as e:\n abort(500, e)\nreturn record",
"result = False\nids =... | <|body_start_0|>
configs = None
configsDao = ConfigsDao()
try:
configs = configsDao.add(args)
except Exception as e:
abort(500, e)
return configs
<|end_body_0|>
<|body_start_1|>
record = None
configsDao = ConfigsDao()
try:
... | configs module resource main service: add/delete/edit/view | ConfigsAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def get(self, args... | stack_v2_sparse_classes_75kplus_train_065299 | 5,875 | permissive | [
{
"docstring": "add",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "edit",
"name": "put",
"signature": "def put(self, args)"
},
{
"docstring": "delete",
"name": "delete",
"signature": "def delete(self, args)"
},
{
"docstring": "view",
... | 4 | stack_v2_sparse_classes_30k_train_021705 | Implement the Python class `ConfigsAPI` described below.
Class description:
configs module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def delete(self, args): delete
- def get(self, args): view | Implement the Python class `ConfigsAPI` described below.
Class description:
configs module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def delete(self, args): delete
- def get(self, args): view
<|skeleton|>
class ConfigsAPI:
... | 0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86 | <|skeleton|>
class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def get(self, args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
configs = None
configsDao = ConfigsDao()
try:
configs = configsDao.add(args)
except Exception as e:
abort(500, e)
return con... | the_stack_v2_python_sparse | app/modules/configs/resource.py | daitouli/baoaiback | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.