blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a35d7839dde88420998d37a6ba5430e50646e019 | [
"try:\n print('收到修改个人信息请求')\n body = json.loads(self.request.body)\n self.sqlhandler = None\n self.teaUid = body['teaUid']\n self.teaPassword = body['teaPassword']\n self.teaName = body['teaName']\n self.teaSex = body['teaSex']\n self.teaAge = body['teaAge']\n self.teaPhoneNumber = body['... | <|body_start_0|>
try:
print('收到修改个人信息请求')
body = json.loads(self.request.body)
self.sqlhandler = None
self.teaUid = body['teaUid']
self.teaPassword = body['teaPassword']
self.teaName = body['teaName']
self.teaSex = body['teaSex'... | TeaSetInfoRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaSetInfoRequestHandler:
def post(self):
"""获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级"""
<|body_0|>
def SetTeaInfo(self):
"""给学生设置个人信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
print('收到修改个人信息请求')
body = json.loads(self.req... | stack_v2_sparse_classes_36k_train_013900 | 2,411 | no_license | [
{
"docstring": "获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "给学生设置个人信息",
"name": "SetTeaInfo",
"signature": "def SetTeaInfo(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006677 | Implement the Python class `TeaSetInfoRequestHandler` described below.
Class description:
Implement the TeaSetInfoRequestHandler class.
Method signatures and docstrings:
- def post(self): 获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级
- def SetTeaInfo(self): 给学生设置个人信息 | Implement the Python class `TeaSetInfoRequestHandler` described below.
Class description:
Implement the TeaSetInfoRequestHandler class.
Method signatures and docstrings:
- def post(self): 获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级
- def SetTeaInfo(self): 给学生设置个人信息
<|skeleton|>
class TeaSetInfoRequestHandler:
def post(self... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class TeaSetInfoRequestHandler:
def post(self):
"""获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级"""
<|body_0|>
def SetTeaInfo(self):
"""给学生设置个人信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeaSetInfoRequestHandler:
def post(self):
"""获取修改的数据,写入到数据库 不允许修改用户名,不允许修改班级"""
try:
print('收到修改个人信息请求')
body = json.loads(self.request.body)
self.sqlhandler = None
self.teaUid = body['teaUid']
self.teaPassword = body['teaPassword']
... | the_stack_v2_python_sparse | server/teacher/TeaSetInfoRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
3bc21c1ce1f351aec8aac44b3f4194ef74e94be0 | [
"super(focal_loss, self).__init__()\nself.size_average = size_average\nif isinstance(alpha, list):\n assert len(alpha) == num_classes\n self.alpha = torch.Tensor(alpha)\nelse:\n assert alpha < 1\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += 1 - alpha\nself.ga... | <|body_start_0|>
super(focal_loss, self).__init__()
self.size_average = size_average
if isinstance(alpha, list):
assert len(alpha) == num_classes
self.alpha = torch.Tensor(alpha)
else:
assert alpha < 1
self.alpha = torch.zeros(num_classes)
... | focal_loss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样... | stack_v2_sparse_classes_36k_train_013901 | 12,665 | no_license | [
{
"docstring": "focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainnet中设置为2 :param num_classes: 类别数量 :param size_average: 损失计算方式,默认取均值",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_000971 | Implement the Python class `focal_loss` described below.
Class description:
Implement the focal_loss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表... | Implement the Python class `focal_loss` described below.
Class description:
Implement the focal_loss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表... | 3d3e07974a8ba1ffb7c79765aaf37cdb435a611f | <|skeleton|>
class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=3, size_average=True):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainn... | the_stack_v2_python_sparse | code_zjx_round2/model/model_axial.py | Waterbearbear/spark-competition | train | 0 | |
e6bcc6ad5a72b8232fa65fd738a7a639226a9a9e | [
"if request.user.is_authenticated:\n return redirect('/')\ndata = {'login_form': forms.LoginForm()}\nreturn TemplateResponse(request, 'landing/reactivate.html', data)",
"login_form = forms.LoginForm(request.POST)\nusername = login_form.infer_username()\npassword = login_form.data.get('password')\nuser = get_ob... | <|body_start_0|>
if request.user.is_authenticated:
return redirect('/')
data = {'login_form': forms.LoginForm()}
return TemplateResponse(request, 'landing/reactivate.html', data)
<|end_body_0|>
<|body_start_1|>
login_form = forms.LoginForm(request.POST)
username = lo... | now reactivate the user | ReactivateUser | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReactivateUser:
"""now reactivate the user"""
def get(self, request):
"""so you want to rejoin?"""
<|body_0|>
def post(self, request):
"""reactivate that baby"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.user.is_authenticated:
... | stack_v2_sparse_classes_36k_train_013902 | 2,954 | no_license | [
{
"docstring": "so you want to rejoin?",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "reactivate that baby",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `ReactivateUser` described below.
Class description:
now reactivate the user
Method signatures and docstrings:
- def get(self, request): so you want to rejoin?
- def post(self, request): reactivate that baby | Implement the Python class `ReactivateUser` described below.
Class description:
now reactivate the user
Method signatures and docstrings:
- def get(self, request): so you want to rejoin?
- def post(self, request): reactivate that baby
<|skeleton|>
class ReactivateUser:
"""now reactivate the user"""
def get(... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class ReactivateUser:
"""now reactivate the user"""
def get(self, request):
"""so you want to rejoin?"""
<|body_0|>
def post(self, request):
"""reactivate that baby"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReactivateUser:
"""now reactivate the user"""
def get(self, request):
"""so you want to rejoin?"""
if request.user.is_authenticated:
return redirect('/')
data = {'login_form': forms.LoginForm()}
return TemplateResponse(request, 'landing/reactivate.html', data)
... | the_stack_v2_python_sparse | bookwyrm/views/preferences/delete_user.py | bookwyrm-social/bookwyrm | train | 1,398 |
9a11548505fd45bec416ef4344362ecbd17559cd | [
"global n\nn = N\nself.q = Queue.PriorityQueue()\nself.q.put(Ran(0, n - 1))",
"ran = self.q.get()\nl, r = (ran.l, ran.r)\nif l == 0:\n if l + 1 <= r:\n self.q.put(Ran(l + 1, r))\n return l\nelif r == n - 1:\n if r - 1 >= l:\n self.q.put(Ran(l, r - 1))\n return r\nll = r - l + 1\nmid = 0\... | <|body_start_0|>
global n
n = N
self.q = Queue.PriorityQueue()
self.q.put(Ran(0, n - 1))
<|end_body_0|>
<|body_start_1|>
ran = self.q.get()
l, r = (ran.l, ran.r)
if l == 0:
if l + 1 <= r:
self.q.put(Ran(l + 1, r))
return l
... | ExamRoom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
global n
n = N
... | stack_v2_sparse_classes_36k_train_013903 | 3,191 | no_license | [
{
"docstring": ":type N: int",
"name": "__init__",
"signature": "def __init__(self, N)"
},
{
"docstring": ":rtype: int",
"name": "seat",
"signature": "def seat(self)"
},
{
"docstring": ":type p: int :rtype: void",
"name": "leave",
"signature": "def leave(self, p)"
}
] | 3 | null | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void | Implement the Python class `ExamRoom` described below.
Class description:
Implement the ExamRoom class.
Method signatures and docstrings:
- def __init__(self, N): :type N: int
- def seat(self): :rtype: int
- def leave(self, p): :type p: int :rtype: void
<|skeleton|>
class ExamRoom:
def __init__(self, N):
... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class ExamRoom:
def __init__(self, N):
""":type N: int"""
<|body_0|>
def seat(self):
""":rtype: int"""
<|body_1|>
def leave(self, p):
""":type p: int :rtype: void"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExamRoom:
def __init__(self, N):
""":type N: int"""
global n
n = N
self.q = Queue.PriorityQueue()
self.q.put(Ran(0, n - 1))
def seat(self):
""":rtype: int"""
ran = self.q.get()
l, r = (ran.l, ran.r)
if l == 0:
if l + 1 <=... | the_stack_v2_python_sparse | python/leetcode.855.py | CalvinNeo/LeetCode | train | 3 | |
88d48e74ba641805b75f6e941e3cb516f518553f | [
"self.manipulator = m\nself.position = self.manipulator.random()\nself.best = self.position\nself.omega = omega\nself.phi_l = phi_l\nself.phi_g = phi_g\nself.crossover_choice = crossover_choice\nself.velocity = {}\nfor p in self.manipulator.params:\n self.velocity[p.name] = 0",
"m = self.manipulator\nfor p in ... | <|body_start_0|>
self.manipulator = m
self.position = self.manipulator.random()
self.best = self.position
self.omega = omega
self.phi_l = phi_l
self.phi_g = phi_g
self.crossover_choice = crossover_choice
self.velocity = {}
for p in self.manipulator... | HybridParticle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HybridParticle:
def __init__(self, m, crossover_choice, omega=0.5, phi_l=0.5, phi_g=0.5):
"""m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in range [0,1] ; omega=1 means even speed phi_l: influence of the particle's distance to its historial bes... | stack_v2_sparse_classes_36k_train_013904 | 3,090 | permissive | [
{
"docstring": "m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in range [0,1] ; omega=1 means even speed phi_l: influence of the particle's distance to its historial best position, a float in range [0,1] phi_g: influence of the particle's distance to the global best pos... | 2 | stack_v2_sparse_classes_30k_train_019485 | Implement the Python class `HybridParticle` described below.
Class description:
Implement the HybridParticle class.
Method signatures and docstrings:
- def __init__(self, m, crossover_choice, omega=0.5, phi_l=0.5, phi_g=0.5): m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in ... | Implement the Python class `HybridParticle` described below.
Class description:
Implement the HybridParticle class.
Method signatures and docstrings:
- def __init__(self, m, crossover_choice, omega=0.5, phi_l=0.5, phi_g=0.5): m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in ... | 05e2d6b9538c9e2d335a02c48c0f7e77d1c57077 | <|skeleton|>
class HybridParticle:
def __init__(self, m, crossover_choice, omega=0.5, phi_l=0.5, phi_g=0.5):
"""m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in range [0,1] ; omega=1 means even speed phi_l: influence of the particle's distance to its historial bes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HybridParticle:
def __init__(self, m, crossover_choice, omega=0.5, phi_l=0.5, phi_g=0.5):
"""m: a configuraiton manipulator omega: influence of the particle's last velocity, a float in range [0,1] ; omega=1 means even speed phi_l: influence of the particle's distance to its historial best position, a ... | the_stack_v2_python_sparse | opentuner/search/pso.py | jansel/opentuner | train | 328 | |
9b7c3c13d01dda28dcc954102b92bb1438051a38 | [
"number = str(number)\nif len(number) == 13:\n if number[0] == '4':\n return 'Visa'\nelif len(number) == 14:\n if number[:2] == '36':\n return 'MasterCard'\nelif len(number) == 15:\n if number[:2] in ('34', '37'):\n return 'American Express'\nelif len(number) == 16:\n if number[:4] ... | <|body_start_0|>
number = str(number)
if len(number) == 13:
if number[0] == '4':
return 'Visa'
elif len(number) == 14:
if number[:2] == '36':
return 'MasterCard'
elif len(number) == 15:
if number[:2] in ('34', '37'):
... | CreditCardField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditCardField:
def get_cc_type(number):
"""Gets credit card type given number. Based on values from Wikipedia page "Credit card number". http://en.wikipedia.org/w/index.php?title=Credit_card_number"""
<|body_0|>
def clean(self, value):
"""Check if given CC number i... | stack_v2_sparse_classes_36k_train_013905 | 7,064 | permissive | [
{
"docstring": "Gets credit card type given number. Based on values from Wikipedia page \"Credit card number\". http://en.wikipedia.org/w/index.php?title=Credit_card_number",
"name": "get_cc_type",
"signature": "def get_cc_type(number)"
},
{
"docstring": "Check if given CC number is valid and on... | 2 | stack_v2_sparse_classes_30k_train_016486 | Implement the Python class `CreditCardField` described below.
Class description:
Implement the CreditCardField class.
Method signatures and docstrings:
- def get_cc_type(number): Gets credit card type given number. Based on values from Wikipedia page "Credit card number". http://en.wikipedia.org/w/index.php?title=Cre... | Implement the Python class `CreditCardField` described below.
Class description:
Implement the CreditCardField class.
Method signatures and docstrings:
- def get_cc_type(number): Gets credit card type given number. Based on values from Wikipedia page "Credit card number". http://en.wikipedia.org/w/index.php?title=Cre... | 326c035b2f0ef0feae4cd7aa2d4e73fa4a40171a | <|skeleton|>
class CreditCardField:
def get_cc_type(number):
"""Gets credit card type given number. Based on values from Wikipedia page "Credit card number". http://en.wikipedia.org/w/index.php?title=Credit_card_number"""
<|body_0|>
def clean(self, value):
"""Check if given CC number i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreditCardField:
def get_cc_type(number):
"""Gets credit card type given number. Based on values from Wikipedia page "Credit card number". http://en.wikipedia.org/w/index.php?title=Credit_card_number"""
number = str(number)
if len(number) == 13:
if number[0] == '4':
... | the_stack_v2_python_sparse | remit/forms.py | naamara/blink | train | 0 | |
660103519b5e10a914db86f49e99c276b3e22618 | [
"self.done = False\nself.success = False\nself.x_init = init_state[0]\nself.x_lim = 0.0\nself.xd_max = 0.0001\nself.delta_x_min = 0.1\nself.sign = 1 if positive else -1\nself.u_max = self.sign * np.array([1.5])\nself._t_init = False\nself._t0 = None\nself._t_max = 10.0\nself._t_min = 2.0",
"x, _, _, xd, _ = obs\n... | <|body_start_0|>
self.done = False
self.success = False
self.x_init = init_state[0]
self.x_lim = 0.0
self.xd_max = 0.0001
self.delta_x_min = 0.1
self.sign = 1 if positive else -1
self.u_max = self.sign * np.array([1.5])
self._t_init = False
... | Controller for going to one of the joint limits (part of the calibration routine) | GoToLimCtrl | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_013906 | 13,813 | permissive | [
{
"docstring": "Constructor :param init_state: initial state of the system :param positive: direction switch",
"name": "__init__",
"signature": "def __init__(self, init_state: np.ndarray, positive: bool=True)"
},
{
"docstring": "Go to joint limits by applying u_max and save limit value in th_lim... | 2 | null | Implement the Python class `GoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of the system... | Implement the Python class `GoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, init_state: np.ndarray, positive: bool=True): Constructor :param init_state: initial state of the system... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class GoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, init_state: np.ndarray, positive: bool=True):
"""Constructor :param init_state: initial state of the system :param positive: direction switch"""
self.done = False
... | the_stack_v2_python_sparse | Pyrado/pyrado/environments/quanser/quanser_cartpole.py | jacarvalho/SimuRLacra | train | 0 |
5e1e307d01d7f127a87b51c22cdc3118de1aa0f9 | [
"res = []\n\ndef helper(root):\n if not root:\n return\n if root:\n helper(root.left)\n res.append(root.data)\n helper(root.right)\nhelper(root)\nreturn res",
"res = []\nstack = []\np = root\nwhile p or stack:\n while p:\n stack.append(p)\n p = stack.pop()\n res.a... | <|body_start_0|>
res = []
def helper(root):
if not root:
return
if root:
helper(root.left)
res.append(root.data)
helper(root.right)
helper(root)
return res
<|end_body_0|>
<|body_start_1|>
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
"""递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:"""
<|body_0|>
def inorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代 通过栈 时间复杂度为 O(n) 空间复杂度为 O(n) 但是栈有个问题,虽然栈提高... | stack_v2_sparse_classes_36k_train_013907 | 3,517 | no_license | [
{
"docstring": "递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root: TreeNode) -> List[int]"
},
{
"docstring": "迭代 通过栈 时间复杂度为 O(n) 空间复杂度为 O(n) 但是栈有个问题,虽然栈提高了效率,但是嵌套循环非常烧脑,不易理解,容易造成一看就懂 一写就废的情况,而... | 3 | stack_v2_sparse_classes_30k_train_002400 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root: TreeNode) -> List[int]: 递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:
- def inorderTraversal2(self, root: TreeNod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root: TreeNode) -> List[int]: 递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:
- def inorderTraversal2(self, root: TreeNod... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
"""递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:"""
<|body_0|>
def inorderTraversal2(self, root: TreeNode) -> List[int]:
"""迭代 通过栈 时间复杂度为 O(n) 空间复杂度为 O(n) 但是栈有个问题,虽然栈提高... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
"""递归 时间复杂度为 O(n) 空间复杂度为 O(n) 递归可以解决问题,但是考虑到效率,我们通常不推荐使用递归 :param root: :return:"""
res = []
def helper(root):
if not root:
return
if root:
helper(root.left)
... | the_stack_v2_python_sparse | LeetCode_practice/BinaryTree/0094_BinaryTreeInorderTraversal.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
b5303726718e72dcbc078532a7ed19f0047f14e8 | [
"if obj.user_id:\n return self.get_user_member(obj['user'])\nelif obj.group_id:\n return self.get_group_member(obj['group'])",
"profile = user.get('profile', {})\nname = profile.get('full_name') or user.get('username') or _('Untitled')\ndescription = profile.get('affiliations') or ''\nfake_user_obj = Simple... | <|body_start_0|>
if obj.user_id:
return self.get_user_member(obj['user'])
elif obj.group_id:
return self.get_group_member(obj['group'])
<|end_body_0|>
<|body_start_1|>
profile = user.get('profile', {})
name = profile.get('full_name') or user.get('username') or _(... | Public Dump Schema. | PublicDumpSchema | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicDumpSchema:
"""Public Dump Schema."""
def get_member(self, obj):
"""Get a member."""
<|body_0|>
def get_user_member(self, user):
"""Get a user member."""
<|body_1|>
def get_group_member(self, group):
"""Get a group member."""
<|... | stack_v2_sparse_classes_36k_train_013908 | 6,688 | permissive | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, obj)"
},
{
"docstring": "Get a user member.",
"name": "get_user_member",
"signature": "def get_user_member(self, user)"
},
{
"docstring": "Get a group member.",
"name": "get_group_member"... | 3 | stack_v2_sparse_classes_30k_train_017406 | Implement the Python class `PublicDumpSchema` described below.
Class description:
Public Dump Schema.
Method signatures and docstrings:
- def get_member(self, obj): Get a member.
- def get_user_member(self, user): Get a user member.
- def get_group_member(self, group): Get a group member. | Implement the Python class `PublicDumpSchema` described below.
Class description:
Public Dump Schema.
Method signatures and docstrings:
- def get_member(self, obj): Get a member.
- def get_user_member(self, user): Get a user member.
- def get_group_member(self, group): Get a group member.
<|skeleton|>
class PublicDu... | 9a17455c06bf606c19c6b1367e4e3d36bf017be9 | <|skeleton|>
class PublicDumpSchema:
"""Public Dump Schema."""
def get_member(self, obj):
"""Get a member."""
<|body_0|>
def get_user_member(self, user):
"""Get a user member."""
<|body_1|>
def get_group_member(self, group):
"""Get a group member."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicDumpSchema:
"""Public Dump Schema."""
def get_member(self, obj):
"""Get a member."""
if obj.user_id:
return self.get_user_member(obj['user'])
elif obj.group_id:
return self.get_group_member(obj['group'])
def get_user_member(self, user):
"... | the_stack_v2_python_sparse | invenio_communities/members/services/schemas.py | inveniosoftware/invenio-communities | train | 5 |
cccf27816f40af1bff562e2cfdede34100e2c29a | [
"self.labels_file_path = '{}/something-something-v2-labels.json'.format(config.jason_label_path)\nself.train_file_path = '{}/train_videofolder.txt'.format(config.label_path)\nself.valid_file_path = '{}/val_videofolder.txt'.format(config.label_path)\nself.test_file_path = '{}/test_videofolder.txt'.format(config.labe... | <|body_start_0|>
self.labels_file_path = '{}/something-something-v2-labels.json'.format(config.jason_label_path)
self.train_file_path = '{}/train_videofolder.txt'.format(config.label_path)
self.valid_file_path = '{}/val_videofolder.txt'.format(config.label_path)
self.test_file_path = '{}... | Used to load video metadata. | MetadataLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataLoader:
"""Used to load video metadata."""
def __init__(self, config):
"""Constructor."""
<|body_0|>
def load_metadata(self):
"""Load labels. Returns: Dict with keys "train", "valid", "test". Each key maps to a dicts, with each keys being sample ids. Each... | stack_v2_sparse_classes_36k_train_013909 | 2,484 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Load labels. Returns: Dict with keys \"train\", \"valid\", \"test\". Each key maps to a dicts, with each keys being sample ids. Each key maps to a dict with keys \"n_frames\", \"label\... | 3 | stack_v2_sparse_classes_30k_train_016776 | Implement the Python class `MetadataLoader` described below.
Class description:
Used to load video metadata.
Method signatures and docstrings:
- def __init__(self, config): Constructor.
- def load_metadata(self): Load labels. Returns: Dict with keys "train", "valid", "test". Each key maps to a dicts, with each keys b... | Implement the Python class `MetadataLoader` described below.
Class description:
Used to load video metadata.
Method signatures and docstrings:
- def __init__(self, config): Constructor.
- def load_metadata(self): Load labels. Returns: Dict with keys "train", "valid", "test". Each key maps to a dicts, with each keys b... | 26de9802912415f5ecb85b8ede816cd5ede50e7b | <|skeleton|>
class MetadataLoader:
"""Used to load video metadata."""
def __init__(self, config):
"""Constructor."""
<|body_0|>
def load_metadata(self):
"""Load labels. Returns: Dict with keys "train", "valid", "test". Each key maps to a dicts, with each keys being sample ids. Each... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetadataLoader:
"""Used to load video metadata."""
def __init__(self, config):
"""Constructor."""
self.labels_file_path = '{}/something-something-v2-labels.json'.format(config.jason_label_path)
self.train_file_path = '{}/train_videofolder.txt'.format(config.label_path)
sel... | the_stack_v2_python_sparse | Video_Based_Human_Activity_Recognition/data_utils/metadata_loader.py | jotix16/Courses | train | 0 |
390b55ad55a201edb5db7cb6bbd8448294d25856 | [
"self._rep = rep\nself._output_sizes = output_sizes\nself._type = att_type\nself._scale = scale\nself._normalise = normalise\nif self._type == 'multihead':\n self._num_heads = num_heads",
"if self._rep == 'identity':\n k, q = (x1, x2)\nelif self._rep == 'mlp':\n k = batch_mlp(x1, self._output_sizes)\n ... | <|body_start_0|>
self._rep = rep
self._output_sizes = output_sizes
self._type = att_type
self._scale = scale
self._normalise = normalise
if self._type == 'multihead':
self._num_heads = num_heads
<|end_body_0|>
<|body_start_1|>
if self._rep == 'identit... | The Attention module. | Attention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated represen... | stack_v2_sparse_classes_36k_train_013910 | 32,302 | permissive | [
{
"docstring": "Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the context data. Args: rep: transformation to apply to contexts before computing attention. One of: ['identity', 'mlp']. output_size... | 2 | stack_v2_sparse_classes_30k_train_016869 | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Creates a attention module. Takes in context inputs, target inputs and representations of each c... | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Creates a attention module. Takes in context inputs, target inputs and representations of each c... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated represen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the... | the_stack_v2_python_sparse | t2t_bert/utils/tensor2tensor/layers/gaussian_process.py | yyht/BERT | train | 37 |
1d5e8229f47988dcbc8983930d245867d0239341 | [
"if not matrix:\n return\nm = len(matrix)\nn = len(matrix[0])\nrow = [1 for i in range(m)]\ncol = [1 for i in range(n)]\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] == 0:\n row[i] = 0\n col[j] = 0\nfor i in range(m):\n for j in range(n):\n if row[i] == 0 or... | <|body_start_0|>
if not matrix:
return
m = len(matrix)
n = len(matrix[0])
row = [1 for i in range(m)]
col = [1 for i in range(n)]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row[i] = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_36k_train_013911 | 2,025 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes1",
"signature": "def setZeroes1(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place inst... | 2 | stack_v2_sparse_classes_30k_train_015590 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes(self, matrix): :type matrix: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes(self, matrix): :type matrix: List... | eedf73b5f167025a97f0905d3718b6eab2ee3e09 | <|skeleton|>
class Solution:
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
if not matrix:
return
m = len(matrix)
n = len(matrix[0])
row = [1 for i in range(m)]
col = [1 for i in ra... | the_stack_v2_python_sparse | Array/73_Set_Matrix_Zeroes.py | xiaomojie/LeetCode | train | 0 | |
367eb3000bdf0665075d665868f1d142ede6bc0b | [
"self.number_filters_first_layer = number_filters_first_layer\nself.filter_shape = filter_shape\nself.scaling_factor = scaling_factor\nself.number_scaling = number_scaling\nself.resize_method = resize_method\nself.normalization = normalization\nself.regularization_scale = regularization_scale\nself.number_channels ... | <|body_start_0|>
self.number_filters_first_layer = number_filters_first_layer
self.filter_shape = filter_shape
self.scaling_factor = scaling_factor
self.number_scaling = number_scaling
self.resize_method = resize_method
self.normalization = normalization
self.regu... | Base model for a convolutional autoencoder | EncoderDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderDecoder:
"""Base model for a convolutional autoencoder"""
def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, normalization=tf.contrib.layers.instance_norm, regularization... | stack_v2_sparse_classes_36k_train_013912 | 24,456 | permissive | [
{
"docstring": "Initialize a model",
"name": "__init__",
"signature": "def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, normalization=tf.contrib.layers.instance_norm, regularization_scale... | 4 | stack_v2_sparse_classes_30k_test_000506 | Implement the Python class `EncoderDecoder` described below.
Class description:
Base model for a convolutional autoencoder
Method signatures and docstrings:
- def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEI... | Implement the Python class `EncoderDecoder` described below.
Class description:
Base model for a convolutional autoencoder
Method signatures and docstrings:
- def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEI... | 4d22e3ef90ef842d6b390074a8b5deedc7658a2b | <|skeleton|>
class EncoderDecoder:
"""Base model for a convolutional autoencoder"""
def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, normalization=tf.contrib.layers.instance_norm, regularization... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderDecoder:
"""Base model for a convolutional autoencoder"""
def __init__(self, number_filters_first_layer=64, filter_shape=(3, 3), scaling_factor=(2, 2), number_scaling=3, resize_method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, normalization=tf.contrib.layers.instance_norm, regularization_scale=0.1, n... | the_stack_v2_python_sparse | pyinsar/processing/machine_learning/neural_networks/anomaly_identification.py | MITeaps/pyinsar | train | 11 |
68cc1f9b71262520f022be5f6590957fb196284f | [
"if default is None:\n default = DEFAULT.copy()\n default.update(SPECTRAL_DEFAULT)\n default.update(WAVECAL_DEFAULT)\nsuper().__init__(default=default, config=config, pipecal_config=pipecal_config)",
"config = super().to_config()\nconfig['wavecal'] = True\nconfig['spatcal'] = False\nconfig['slitcorr'] = ... | <|body_start_0|>
if default is None:
default = DEFAULT.copy()
default.update(SPECTRAL_DEFAULT)
default.update(WAVECAL_DEFAULT)
super().__init__(default=default, config=config, pipecal_config=pipecal_config)
<|end_body_0|>
<|body_start_1|>
config = super().to_... | Reduction parameters for the FLITECAM grism wavecal pipeline. | FLITECAMWavecalParameters | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults fo... | stack_v2_sparse_classes_36k_train_013913 | 15,967 | permissive | [
{
"docstring": "Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular observation modes, or dates, etc. Parameters ---------- config : dict-like, optional Reduction mode and auxiliary file configuration mapping, as returned from the so... | 5 | stack_v2_sparse_classes_30k_train_019362 | Implement the Python class `FLITECAMWavecalParameters` described below.
Class description:
Reduction parameters for the FLITECAM grism wavecal pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config... | Implement the Python class `FLITECAMWavecalParameters` described below.
Class description:
Reduction parameters for the FLITECAM grism wavecal pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular ... | the_stack_v2_python_sparse | sofia_redux/pipeline/sofia/parameters/flitecam_wavecal_parameters.py | SOFIA-USRA/sofia_redux | train | 12 |
92aa9b9f5032dceb6c8f78f1a45d0be7bd2bc026 | [
"images = tf.zeros(shape=(batch_size, image_size, image_size, 1), dtype=tf.float32)\nlabels = tf.zeros(shape=(batch_size,), dtype=tf.int32)\nreturn io.encode_samples(images, labels)",
"weights = io.decode_weights(encoded)\nself.assertLen(weights, num_weights)\nfor weight in weights:\n self.assertEqual(weight.s... | <|body_start_0|>
images = tf.zeros(shape=(batch_size, image_size, image_size, 1), dtype=tf.float32)
labels = tf.zeros(shape=(batch_size,), dtype=tf.int32)
return io.encode_samples(images, labels)
<|end_body_0|>
<|body_start_1|>
weights = io.decode_weights(encoded)
self.assertLen... | UtilTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilTest:
def _encode_samples(self, batch_size, image_size, io):
"""Creates empty images and labels and encodes for Transformer."""
<|body_0|>
def _check_weights(self, encoded, num_weights, image_size, io):
"""Decodes weights and checks their number and their shapes.... | stack_v2_sparse_classes_36k_train_013914 | 2,805 | permissive | [
{
"docstring": "Creates empty images and labels and encodes for Transformer.",
"name": "_encode_samples",
"signature": "def _encode_samples(self, batch_size, image_size, io)"
},
{
"docstring": "Decodes weights and checks their number and their shapes.",
"name": "_check_weights",
"signatu... | 4 | null | Implement the Python class `UtilTest` described below.
Class description:
Implement the UtilTest class.
Method signatures and docstrings:
- def _encode_samples(self, batch_size, image_size, io): Creates empty images and labels and encodes for Transformer.
- def _check_weights(self, encoded, num_weights, image_size, i... | Implement the Python class `UtilTest` described below.
Class description:
Implement the UtilTest class.
Method signatures and docstrings:
- def _encode_samples(self, batch_size, image_size, io): Creates empty images and labels and encodes for Transformer.
- def _check_weights(self, encoded, num_weights, image_size, i... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class UtilTest:
def _encode_samples(self, batch_size, image_size, io):
"""Creates empty images and labels and encodes for Transformer."""
<|body_0|>
def _check_weights(self, encoded, num_weights, image_size, io):
"""Decodes weights and checks their number and their shapes.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UtilTest:
def _encode_samples(self, batch_size, image_size, io):
"""Creates empty images and labels and encodes for Transformer."""
images = tf.zeros(shape=(batch_size, image_size, image_size, 1), dtype=tf.float32)
labels = tf.zeros(shape=(batch_size,), dtype=tf.int32)
return i... | the_stack_v2_python_sparse | hypertransformer/tf/core/util_test.py | Jimmy-INL/google-research | train | 1 | |
cf08b228515edd237900325924e46222ab9b99c3 | [
"s = str(s)\nself._array = sorted([s[i:] for i in xrange(len(s))])\nself._lcp = [0]\nfor i in xrange(1, len(self._array)):\n prefix = SuffixArray._find_lcp(self._array[i], self._array[i - 1])\n self._lcp.append(prefix)",
"if not (isinstance(s1, str) and isinstance(s2, str)):\n raise TypeError\nif len(s2)... | <|body_start_0|>
s = str(s)
self._array = sorted([s[i:] for i in xrange(len(s))])
self._lcp = [0]
for i in xrange(1, len(self._array)):
prefix = SuffixArray._find_lcp(self._array[i], self._array[i - 1])
self._lcp.append(prefix)
<|end_body_0|>
<|body_start_1|>
... | An array that keeps track of suffixes. | SuffixArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuffixArray:
"""An array that keeps track of suffixes."""
def __init__(self, s):
"""Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixArray. If s is not a string, it will be converted to one w... | stack_v2_sparse_classes_36k_train_013915 | 4,526 | no_license | [
{
"docstring": "Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixArray. If s is not a string, it will be converted to one with str(). Must be comprised of ASCII characters. Raises: TypeError: array is not an iterable, c... | 4 | stack_v2_sparse_classes_30k_train_005670 | Implement the Python class `SuffixArray` described below.
Class description:
An array that keeps track of suffixes.
Method signatures and docstrings:
- def __init__(self, s): Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixA... | Implement the Python class `SuffixArray` described below.
Class description:
An array that keeps track of suffixes.
Method signatures and docstrings:
- def __init__(self, s): Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixA... | bf622efcfad26f95696aa0bb72edb8fadfb2f717 | <|skeleton|>
class SuffixArray:
"""An array that keeps track of suffixes."""
def __init__(self, s):
"""Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixArray. If s is not a string, it will be converted to one w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuffixArray:
"""An array that keeps track of suffixes."""
def __init__(self, s):
"""Creates a new, sorted SuffixArray of the suffixes for string s. Suffixes are case sensitive. Args: s: The string from which to form the SuffixArray. If s is not a string, it will be converted to one with str(). Mu... | the_stack_v2_python_sparse | suffix/suffix_tree.py | mmweber2/adm | train | 3 |
c689d555dafd748662f579a3234dd6a6c2bf0087 | [
"self.nums = nums\nself.accumulate = []\nfor index, num in enumerate(nums):\n if index > 0:\n self.accumulate.append(self.accumulate[index - 1] + num)\n else:\n self.accumulate.append(num)",
"if i == 0:\n return self.accumulate[j]\nreturn self.accumulate[j] - self.accumulate[i - 1]"
] | <|body_start_0|>
self.nums = nums
self.accumulate = []
for index, num in enumerate(nums):
if index > 0:
self.accumulate.append(self.accumulate[index - 1] + num)
else:
self.accumulate.append(num)
<|end_body_0|>
<|body_start_1|>
if i... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = nums
self.accumulate = []
for i... | stack_v2_sparse_classes_36k_train_013916 | 1,180 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 232ad0f2b326ddbf021991a551cd38d39ceccd8f | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
self.accumulate = []
for index, num in enumerate(nums):
if index > 0:
self.accumulate.append(self.accumulate[index - 1] + num)
else:
self.acc... | the_stack_v2_python_sparse | leetcode/59_303.py | lanzhiwang/common_algorithm | train | 0 | |
d5604cf5a3efe2ddaaf470ec84e89351bce40812 | [
"super(ScaledDotProductAttention, self).__init__()\nself.scala = numpy.power(num_dim, 0.5)\nself.dropout = nn.Dropout(dropout_rate)\nself.softmax = nn.Softmax()",
"attn = torch.bmm(query, key.transpose(1, 2)) / self.scala\nattn = self.dropout(attn)\nbatch_size, num_q, num_v = attn.size()\nattn = attn.view(-1, num... | <|body_start_0|>
super(ScaledDotProductAttention, self).__init__()
self.scala = numpy.power(num_dim, 0.5)
self.dropout = nn.Dropout(dropout_rate)
self.softmax = nn.Softmax()
<|end_body_0|>
<|body_start_1|>
attn = torch.bmm(query, key.transpose(1, 2)) / self.scala
attn = ... | ScaledDotProductAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledDotProductAttention:
def __init__(self, num_dim, dropout_rate=0.1):
"""num_dim: the number of dimension of each query word query word and key should have the same num_dim number of dimension of value vector can be different"""
<|body_0|>
def forward(self, query, key, v... | stack_v2_sparse_classes_36k_train_013917 | 4,134 | no_license | [
{
"docstring": "num_dim: the number of dimension of each query word query word and key should have the same num_dim number of dimension of value vector can be different",
"name": "__init__",
"signature": "def __init__(self, num_dim, dropout_rate=0.1)"
},
{
"docstring": "input: query: (batch_size... | 2 | null | Implement the Python class `ScaledDotProductAttention` described below.
Class description:
Implement the ScaledDotProductAttention class.
Method signatures and docstrings:
- def __init__(self, num_dim, dropout_rate=0.1): num_dim: the number of dimension of each query word query word and key should have the same num_d... | Implement the Python class `ScaledDotProductAttention` described below.
Class description:
Implement the ScaledDotProductAttention class.
Method signatures and docstrings:
- def __init__(self, num_dim, dropout_rate=0.1): num_dim: the number of dimension of each query word query word and key should have the same num_d... | be85ee0c1fa915ae08ffb857643f9429a7749c0e | <|skeleton|>
class ScaledDotProductAttention:
def __init__(self, num_dim, dropout_rate=0.1):
"""num_dim: the number of dimension of each query word query word and key should have the same num_dim number of dimension of value vector can be different"""
<|body_0|>
def forward(self, query, key, v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaledDotProductAttention:
def __init__(self, num_dim, dropout_rate=0.1):
"""num_dim: the number of dimension of each query word query word and key should have the same num_dim number of dimension of value vector can be different"""
super(ScaledDotProductAttention, self).__init__()
sel... | the_stack_v2_python_sparse | models/Attention.py | HuangYiran/MasterArbeit | train | 1 | |
d76edd4d845021995ac3407d4001f661936d28f1 | [
"gsn = copy.copy(gsn)\ngsn.__class__ = cls\ngsn.input_idx = input_idx\ngsn.label_idx = label_idx or gsn.nlayers - 1\nreturn gsn",
"wb = trials - len(self.aes)\nif wb <= 0:\n return 0\nelse:\n return wb",
"clamped = np.ones(minibatch.shape, dtype=np.float32)\ndata = self.get_samples([(self.input_idx, minib... | <|body_start_0|>
gsn = copy.copy(gsn)
gsn.__class__ = cls
gsn.input_idx = input_idx
gsn.label_idx = label_idx or gsn.nlayers - 1
return gsn
<|end_body_0|>
<|body_start_1|>
wb = trials - len(self.aes)
if wb <= 0:
return 0
else:
retu... | This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors. | JointGSN | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointGSN:
"""This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors."""
def convert(cls, gsn, input_idx=0, label_idx=None):
"""'convert' essentially serves as the constructor fo... | stack_v2_sparse_classes_36k_train_013918 | 36,324 | permissive | [
{
"docstring": "'convert' essentially serves as the constructor for JointGSN. Parameters ---------- gsn : GSN input_idx : int The index of the layer which serves as the \"input\" to the network. During classification, this layer will be given. Defaults to 0. label_idx : int The index of the layer which serves a... | 5 | null | Implement the Python class `JointGSN` described below.
Class description:
This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors.
Method signatures and docstrings:
- def convert(cls, gsn, input_idx=0, label_idx=... | Implement the Python class `JointGSN` described below.
Class description:
This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors.
Method signatures and docstrings:
- def convert(cls, gsn, input_idx=0, label_idx=... | 96edb376ced1b828962c749240059903686da549 | <|skeleton|>
class JointGSN:
"""This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors."""
def convert(cls, gsn, input_idx=0, label_idx=None):
"""'convert' essentially serves as the constructor fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JointGSN:
"""This class only provides a few convenient methods on top of the GSN class above. This class should be used when learning the joint distribution between 2 vectors."""
def convert(cls, gsn, input_idx=0, label_idx=None):
"""'convert' essentially serves as the constructor for JointGSN. P... | the_stack_v2_python_sparse | pylearn2/models/gsn.py | Coderx7/pylearn2 | train | 1 |
ae85a0038e9bc4120cbd847f29a14d052de53fbc | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nif layer_past ... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
... | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None, layer_past=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_013919 | 16,634 | permissive | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None, layer_past=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010102 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None, layer_past=None): I... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None, layer_past=None): I... | 6a774be5c27b1a5eecf4bcfff55249acf6c2fd5f | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None, layer_past=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_mo... | the_stack_v2_python_sparse | captioning/models/cachedTransformer.py | ruotianluo/ImageCaptioning.pytorch | train | 1,247 | |
bf3d7eb22bcab8c2f00de4049bb79f55223e9791 | [
"super(TimeSeriesOHCAnomaly, self).__init__(config=config, taskName='timeSeriesOHCAnomaly', componentName='ocean', tags=['timeSeries', 'ohc'])\nsectionName = 'timeSeriesOHCAnomaly'\nregionNames = config.getExpression(sectionName, 'regions')\nmovingAveragePoints = config.getint(sectionName, 'movingAveragePoints')\ns... | <|body_start_0|>
super(TimeSeriesOHCAnomaly, self).__init__(config=config, taskName='timeSeriesOHCAnomaly', componentName='ocean', tags=['timeSeries', 'ohc'])
sectionName = 'timeSeriesOHCAnomaly'
regionNames = config.getExpression(sectionName, 'regions')
movingAveragePoints = config.geti... | Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz | TimeSeriesOHCAnomaly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeriesOHCAnomaly:
"""Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz"""
def __init__(self, config, mpasTimeSeriesTask, refConfig=None):
"""Construct the analysis task. Parameters ---------- c... | stack_v2_sparse_classes_36k_train_013920 | 5,921 | no_license | [
{
"docstring": "Construct the analysis task. Parameters ---------- config : ``MpasAnalysisConfigParser`` Configuration options mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output refConfig : ``MpasAnalysisConfigParser``, optional Configuration options for ... | 2 | stack_v2_sparse_classes_30k_train_010082 | Implement the Python class `TimeSeriesOHCAnomaly` described below.
Class description:
Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz
Method signatures and docstrings:
- def __init__(self, config, mpasTimeSeriesTask, refConfig=No... | Implement the Python class `TimeSeriesOHCAnomaly` described below.
Class description:
Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz
Method signatures and docstrings:
- def __init__(self, config, mpasTimeSeriesTask, refConfig=No... | e56da52b9885a79c051e2f0f7c2619e14caf8a21 | <|skeleton|>
class TimeSeriesOHCAnomaly:
"""Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz"""
def __init__(self, config, mpasTimeSeriesTask, refConfig=None):
"""Construct the analysis task. Parameters ---------- c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeSeriesOHCAnomaly:
"""Performs analysis of ocean heat content (OHC) from time-series output. Authors ------- Xylar Asay-Davis, Milena Veneziani, Greg Streletz"""
def __init__(self, config, mpasTimeSeriesTask, refConfig=None):
"""Construct the analysis task. Parameters ---------- config : ``Mpa... | the_stack_v2_python_sparse | mpas_analysis/ocean/time_series_ohc_anomaly.py | zengxiaoqing/MPAS-Analysis | train | 0 |
4f0684f3f4211dccd83ca4632673de6fa1960894 | [
"dic = defaultdict(list)\nres = []\nfor x, y in edges:\n dic[x].append(y)\n dic[y].append(x)\ncur_min = float('inf')\nfor node in range(n):\n q = deque([(node, 0)])\n visited = []\n while q:\n root, height = q.popleft()\n visited.append(root)\n for nei in dic[root]:\n ... | <|body_start_0|>
dic = defaultdict(list)
res = []
for x, y in edges:
dic[x].append(y)
dic[y].append(x)
cur_min = float('inf')
for node in range(n):
q = deque([(node, 0)])
visited = []
while q:
root, heigh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findMi... | stack_v2_sparse_classes_36k_train_013921 | 3,311 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: List[int]",
"name": "findMinHeightTrees",
"signature": "def findMinHeightTrees(self, n, edges)"
},
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: List[int]",
"name": "findMinHeightTrees",
"signature": "d... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: List[int]
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: List[int]
- def findMinHeightTrees(self, n, edges): :type n: int :type edges: List[List[... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findMi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinHeightTrees(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: List[int]"""
dic = defaultdict(list)
res = []
for x, y in edges:
dic[x].append(y)
dic[y].append(x)
cur_min = float('inf')
for node in r... | the_stack_v2_python_sparse | 0310_Minimum_Height_Trees.py | bingli8802/leetcode | train | 0 | |
21a802b48685982220130e6ed33d38d531a9b33e | [
"if not self.VTKObject.GetPoints():\n return None\narray = vtkDataArrayToVTKArray(self.VTKObject.GetPoints().GetData(), self)\narray.Association = ArrayAssociation.POINT\nreturn array",
"from ..vtkCommonCore import vtkPoints\nif isinstance(pts, vtkPoints):\n p = pts\nelse:\n pts = numpyTovtkDataArray(pts... | <|body_start_0|>
if not self.VTKObject.GetPoints():
return None
array = vtkDataArrayToVTKArray(self.VTKObject.GetPoints().GetData(), self)
array.Association = ArrayAssociation.POINT
return array
<|end_body_0|>
<|body_start_1|>
from ..vtkCommonCore import vtkPoints
... | This is a python friendly wrapper of a vtkPointSet that defines a few useful properties. | PointSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointSet:
"""This is a python friendly wrapper of a vtkPointSet that defines a few useful properties."""
def GetPoints(self):
"""Returns the points as a VTKArray instance. Returns None if the dataset has implicit points."""
<|body_0|>
def SetPoints(self, pts):
""... | stack_v2_sparse_classes_36k_train_013922 | 47,641 | permissive | [
{
"docstring": "Returns the points as a VTKArray instance. Returns None if the dataset has implicit points.",
"name": "GetPoints",
"signature": "def GetPoints(self)"
},
{
"docstring": "Given a VTKArray instance, sets the points of the dataset.",
"name": "SetPoints",
"signature": "def Set... | 2 | stack_v2_sparse_classes_30k_train_010714 | Implement the Python class `PointSet` described below.
Class description:
This is a python friendly wrapper of a vtkPointSet that defines a few useful properties.
Method signatures and docstrings:
- def GetPoints(self): Returns the points as a VTKArray instance. Returns None if the dataset has implicit points.
- def ... | Implement the Python class `PointSet` described below.
Class description:
This is a python friendly wrapper of a vtkPointSet that defines a few useful properties.
Method signatures and docstrings:
- def GetPoints(self): Returns the points as a VTKArray instance. Returns None if the dataset has implicit points.
- def ... | dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271 | <|skeleton|>
class PointSet:
"""This is a python friendly wrapper of a vtkPointSet that defines a few useful properties."""
def GetPoints(self):
"""Returns the points as a VTKArray instance. Returns None if the dataset has implicit points."""
<|body_0|>
def SetPoints(self, pts):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointSet:
"""This is a python friendly wrapper of a vtkPointSet that defines a few useful properties."""
def GetPoints(self):
"""Returns the points as a VTKArray instance. Returns None if the dataset has implicit points."""
if not self.VTKObject.GetPoints():
return None
... | the_stack_v2_python_sparse | Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py | Kitware/VTK | train | 2,253 |
127714ce156fff22f4aa04e51f44721c6d7181dc | [
"super(CustomTestCase, self).setUp()\nself.imgs = []\nself.dpi = Settings.DPI\nself.beg = time.time()",
"super(CustomTestCase, self).setUp()\nif hasattr(self, 'beg'):\n end = time.time()\n delta = end - self.beg\n m, s = divmod(delta, 60)\n h, m = divmod(m, 60)\n print(f'Last {h:0>2.0f}:{m:0>2.0f}:... | <|body_start_0|>
super(CustomTestCase, self).setUp()
self.imgs = []
self.dpi = Settings.DPI
self.beg = time.time()
<|end_body_0|>
<|body_start_1|>
super(CustomTestCase, self).setUp()
if hasattr(self, 'beg'):
end = time.time()
delta = end - self.be... | 重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间 | CustomTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomTestCase:
"""重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间"""
def setUp(self) -> None:
"""初始化截图列表,屏幕dpi,记录开始时间 :return: None"""
<|body_0|>
def tearDown(self) -> None:
"""记录结束时间,计算用例执行持续时间 :return: None"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_013923 | 1,116 | no_license | [
{
"docstring": "初始化截图列表,屏幕dpi,记录开始时间 :return: None",
"name": "setUp",
"signature": "def setUp(self) -> None"
},
{
"docstring": "记录结束时间,计算用例执行持续时间 :return: None",
"name": "tearDown",
"signature": "def tearDown(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_003627 | Implement the Python class `CustomTestCase` described below.
Class description:
重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间
Method signatures and docstrings:
- def setUp(self) -> None: 初始化截图列表,屏幕dpi,记录开始时间 :return: None
- def tearDown(self) -> None: 记录结束时间,计算用例执行持续时间 :return: None | Implement the Python class `CustomTestCase` described below.
Class description:
重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间
Method signatures and docstrings:
- def setUp(self) -> None: 初始化截图列表,屏幕dpi,记录开始时间 :return: None
- def tearDown(self) -> None: 记录结束时间,计算用例执行持续时间 :return: None
<|skeleton|>
class Custo... | ee4871b1324cb5047a3284d1491184dfb0e21ca5 | <|skeleton|>
class CustomTestCase:
"""重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间"""
def setUp(self) -> None:
"""初始化截图列表,屏幕dpi,记录开始时间 :return: None"""
<|body_0|>
def tearDown(self) -> None:
"""记录结束时间,计算用例执行持续时间 :return: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomTestCase:
"""重写setUp和tearDown方法,自动初始化截图列表,屏幕dpi,记录开始结束时间,计算用例执行持续时间"""
def setUp(self) -> None:
"""初始化截图列表,屏幕dpi,记录开始时间 :return: None"""
super(CustomTestCase, self).setUp()
self.imgs = []
self.dpi = Settings.DPI
self.beg = time.time()
def tearDown(self) ... | the_stack_v2_python_sparse | Utils/CustomUnittest/CustomTestCase.py | zghnwsq/EasySelenium | train | 0 |
49c711a66990b4bd81a69f1af3e9258b63d849e4 | [
"portfolio_value = 0.0\nfor item in balance:\n if item['name'] == MAIN_CURRENCY:\n portfolio_value += item['value']\n else:\n value = item['value'] * prices.get(item['name'], 0)\n if value >= min_trade_value:\n portfolio_value += value\nreturn portfolio_value",
"sorted_global... | <|body_start_0|>
portfolio_value = 0.0
for item in balance:
if item['name'] == MAIN_CURRENCY:
portfolio_value += item['value']
else:
value = item['value'] * prices.get(item['name'], 0)
if value >= min_trade_value:
... | Index | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Index:
def get_portfolio_value(self, balance, prices, min_trade_value):
"""Computes total amount that the portfolio is worth."""
<|body_0|>
def get_top_assets(self, exchange_market_data, global_market_data, value_key=ValueKeys.MARKET_CAP, top_limit=TOP_LIMIT):
"""Use... | stack_v2_sparse_classes_36k_train_013924 | 5,169 | permissive | [
{
"docstring": "Computes total amount that the portfolio is worth.",
"name": "get_portfolio_value",
"signature": "def get_portfolio_value(self, balance, prices, min_trade_value)"
},
{
"docstring": "Uses global market data to choose the best coins from the exchange's market.",
"name": "get_to... | 5 | stack_v2_sparse_classes_30k_val_000960 | Implement the Python class `Index` described below.
Class description:
Implement the Index class.
Method signatures and docstrings:
- def get_portfolio_value(self, balance, prices, min_trade_value): Computes total amount that the portfolio is worth.
- def get_top_assets(self, exchange_market_data, global_market_data,... | Implement the Python class `Index` described below.
Class description:
Implement the Index class.
Method signatures and docstrings:
- def get_portfolio_value(self, balance, prices, min_trade_value): Computes total amount that the portfolio is worth.
- def get_top_assets(self, exchange_market_data, global_market_data,... | a4518cfc7869bf054115465aad1e31d9f8921927 | <|skeleton|>
class Index:
def get_portfolio_value(self, balance, prices, min_trade_value):
"""Computes total amount that the portfolio is worth."""
<|body_0|>
def get_top_assets(self, exchange_market_data, global_market_data, value_key=ValueKeys.MARKET_CAP, top_limit=TOP_LIMIT):
"""Use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Index:
def get_portfolio_value(self, balance, prices, min_trade_value):
"""Computes total amount that the portfolio is worth."""
portfolio_value = 0.0
for item in balance:
if item['name'] == MAIN_CURRENCY:
portfolio_value += item['value']
else:
... | the_stack_v2_python_sparse | index.py | mihneadb/crypto-index | train | 2 | |
a13a2ecb0cd7c0bebe278951c7f0406fad3582aa | [
"super(subMemberObjectNode, self).__init__(subMember, tree, container)\nself._treeItemId = tree.AppendItem(parentTreeItemId, '')\nif tree.isAutoVisible():\n tree.EnsureVisible(self._treeItemId)",
"nodeData = self._tree.GetItemPyData(self._treeItemId)\nif nodeData is None:\n raise AttributeError('No data att... | <|body_start_0|>
super(subMemberObjectNode, self).__init__(subMember, tree, container)
self._treeItemId = tree.AppendItem(parentTreeItemId, '')
if tree.isAutoVisible():
tree.EnsureVisible(self._treeItemId)
<|end_body_0|>
<|body_start_1|>
nodeData = self._tree.GetItemPyData(s... | Private class. Information for a submember node that wraps a single object. | subMemberObjectNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class subMemberObjectNode:
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
<|body_0|>
def getObject(se... | stack_v2_sparse_classes_36k_train_013925 | 11,787 | no_license | [
{
"docstring": "Create a new node inside the tree that wraps the specified submember",
"name": "__init__",
"signature": "def __init__(self, subMember, tree, container, parentTreeItemId)"
},
{
"docstring": "Returns the object associated with this node, or None if no object is associated.",
"n... | 3 | stack_v2_sparse_classes_30k_train_010050 | Implement the Python class `subMemberObjectNode` described below.
Class description:
Private class. Information for a submember node that wraps a single object.
Method signatures and docstrings:
- def __init__(self, subMember, tree, container, parentTreeItemId): Create a new node inside the tree that wraps the specif... | Implement the Python class `subMemberObjectNode` described below.
Class description:
Private class. Information for a submember node that wraps a single object.
Method signatures and docstrings:
- def __init__(self, subMember, tree, container, parentTreeItemId): Create a new node inside the tree that wraps the specif... | f5ecde937663091fd324c9d22fd72542d4eb1e16 | <|skeleton|>
class subMemberObjectNode:
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
<|body_0|>
def getObject(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class subMemberObjectNode:
"""Private class. Information for a submember node that wraps a single object."""
def __init__(self, subMember, tree, container, parentTreeItemId):
"""Create a new node inside the tree that wraps the specified submember"""
super(subMemberObjectNode, self).__init__(sub... | the_stack_v2_python_sparse | Python/App/Proxys/NodeData.py | kujira70/simbicon | train | 3 |
4376d13f7146e98bc561c9c88a953ad60ea85fab | [
"super(Dataset, self).__init__(resource_id=dataset_id, resource_type=resource.ResourceType.DATASET, name=name, display_name=display_name, parent=parent, locations=locations, lifecycle_state=lifecycle_state)\nself.full_name = full_name\nself.data = data",
"dataset_dict = json.loads(json_string)\ndataset_id = datas... | <|body_start_0|>
super(Dataset, self).__init__(resource_id=dataset_id, resource_type=resource.ResourceType.DATASET, name=name, display_name=display_name, parent=parent, locations=locations, lifecycle_state=lifecycle_state)
self.full_name = full_name
self.data = data
<|end_body_0|>
<|body_start_... | Dataset resource. | Dataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Dataset resource."""
def __init__(self, dataset_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=DatasetLifecycleState.UNSPECIFIED):
"""Initialize. Args: dataset_id (int): The dataset id. full_name (str): The full r... | stack_v2_sparse_classes_36k_train_013926 | 3,182 | permissive | [
{
"docstring": "Initialize. Args: dataset_id (int): The dataset id. full_name (str): The full resource name and ancestry. data (str): Resource representation of the dataset. name (str): The dataset's unique GCP name, with the format \"datasets/{id}\". display_name (str): The dataset's display name. locations (L... | 2 | null | Implement the Python class `Dataset` described below.
Class description:
Dataset resource.
Method signatures and docstrings:
- def __init__(self, dataset_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=DatasetLifecycleState.UNSPECIFIED): Initialize. Args: data... | Implement the Python class `Dataset` described below.
Class description:
Dataset resource.
Method signatures and docstrings:
- def __init__(self, dataset_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=DatasetLifecycleState.UNSPECIFIED): Initialize. Args: data... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Dataset:
"""Dataset resource."""
def __init__(self, dataset_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=DatasetLifecycleState.UNSPECIFIED):
"""Initialize. Args: dataset_id (int): The dataset id. full_name (str): The full r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Dataset resource."""
def __init__(self, dataset_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=DatasetLifecycleState.UNSPECIFIED):
"""Initialize. Args: dataset_id (int): The dataset id. full_name (str): The full resource name ... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_type/dataset.py | kevensen/forseti-security | train | 1 |
48e6e50a51cd078c1bb44c6d184d1b990277dae5 | [
"dphi2 = scan.get_oscillation(deg=False)[1] / 2.0\ntau, zeta = self._calculate_tau_and_zeta(crystal, beam, detector, goniometer, scan, reflections)\nself.e1 = (tau + dphi2) * flex.abs(zeta) / math.sqrt(2.0)\nself.e2 = (tau - dphi2) * flex.abs(zeta) / math.sqrt(2.0)",
"from dials.algorithms.shoebox import MaskCode... | <|body_start_0|>
dphi2 = scan.get_oscillation(deg=False)[1] / 2.0
tau, zeta = self._calculate_tau_and_zeta(crystal, beam, detector, goniometer, scan, reflections)
self.e1 = (tau + dphi2) * flex.abs(zeta) / math.sqrt(2.0)
self.e2 = (tau - dphi2) * flex.abs(zeta) / math.sqrt(2.0)
<|end_bod... | Calculate the fraction of observed intensity for different sigma_m. | FractionOfObservedIntensity | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FractionOfObservedIntensity:
"""Calculate the fraction of observed intensity for different sigma_m."""
def __init__(self, crystal, beam, detector, goniometer, scan, reflections):
"""Initialise the algorithm. Calculate the list of tau and zetas. Params: reflections The list of reflect... | stack_v2_sparse_classes_36k_train_013927 | 27,074 | permissive | [
{
"docstring": "Initialise the algorithm. Calculate the list of tau and zetas. Params: reflections The list of reflections experiment The experiment object",
"name": "__init__",
"signature": "def __init__(self, crystal, beam, detector, goniometer, scan, reflections)"
},
{
"docstring": "Calculate... | 3 | stack_v2_sparse_classes_30k_train_019448 | Implement the Python class `FractionOfObservedIntensity` described below.
Class description:
Calculate the fraction of observed intensity for different sigma_m.
Method signatures and docstrings:
- def __init__(self, crystal, beam, detector, goniometer, scan, reflections): Initialise the algorithm. Calculate the list ... | Implement the Python class `FractionOfObservedIntensity` described below.
Class description:
Calculate the fraction of observed intensity for different sigma_m.
Method signatures and docstrings:
- def __init__(self, crystal, beam, detector, goniometer, scan, reflections): Initialise the algorithm. Calculate the list ... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class FractionOfObservedIntensity:
"""Calculate the fraction of observed intensity for different sigma_m."""
def __init__(self, crystal, beam, detector, goniometer, scan, reflections):
"""Initialise the algorithm. Calculate the list of tau and zetas. Params: reflections The list of reflect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FractionOfObservedIntensity:
"""Calculate the fraction of observed intensity for different sigma_m."""
def __init__(self, crystal, beam, detector, goniometer, scan, reflections):
"""Initialise the algorithm. Calculate the list of tau and zetas. Params: reflections The list of reflections experime... | the_stack_v2_python_sparse | src/dials/algorithms/profile_model/gaussian_rs/calculator.py | dials/dials | train | 71 |
23c84408a54a3675d5438be265381b7ca081466a | [
"if not fields:\n raise ValueError('At least one field must be provided')\nif not fields:\n raise ValueError('At least one field must be provided')\nselects = []\nfor field in fields:\n if isinstance(field, list):\n selects.append(','.join(field))\n else:\n selects.append(field)\nself._req... | <|body_start_0|>
if not fields:
raise ValueError('At least one field must be provided')
if not fields:
raise ValueError('At least one field must be provided')
selects = []
for field in fields:
if isinstance(field, list):
selects.append(... | Represent a rich search query again an Azure Search index. | SearchQuery | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchQuery:
"""Represent a rich search query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueErro... | stack_v2_sparse_classes_36k_train_013928 | 4,488 | permissive | [
{
"docstring": "Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError",
"name": "order_by",
"signature": "def order_by(self, *fields: str) -> None"
},
{
"docstring": "Update the `select` ... | 2 | stack_v2_sparse_classes_30k_train_008892 | Implement the Python class `SearchQuery` described below.
Class description:
Represent a rich search query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the query resu... | Implement the Python class `SearchQuery` described below.
Class description:
Represent a rich search query again an Azure Search index.
Method signatures and docstrings:
- def order_by(self, *fields: str) -> None: Update the `orderby` property for the search results. :param fields: A list of fields for the query resu... | c2ca191e736bb06bfbbbc9493e8325763ba990bb | <|skeleton|>
class SearchQuery:
"""Represent a rich search query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueErro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchQuery:
"""Represent a rich search query again an Azure Search index."""
def order_by(self, *fields: str) -> None:
"""Update the `orderby` property for the search results. :param fields: A list of fields for the query result to be ordered by. :type fields: str :raises: ValueError"""
... | the_stack_v2_python_sparse | sdk/search/azure-search-documents/azure/search/documents/_queries.py | Azure/azure-sdk-for-python | train | 4,046 |
b26b54294098642bd23d1d94f06aceae87838865 | [
"data = []\nif not root:\n return []\n\ndef dfs(node: TreeNode):\n print(node.val)\n data.append(node.val)\n if node.left:\n dfs(node.left)\n if node.right:\n data.append('R')\n data.append(node.val)\n dfs(node.right)\ndfs(root)\nreturn data",
"print(data)\nif len(data) ... | <|body_start_0|>
data = []
if not root:
return []
def dfs(node: TreeNode):
print(node.val)
data.append(node.val)
if node.left:
dfs(node.left)
if node.right:
data.append('R')
data.append(n... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_013929 | 2,061 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: s... | 15f73238453ef046752049c2361bf0a254e300d7 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
data = []
if not root:
return []
def dfs(node: TreeNode):
print(node.val)
data.append(node.val)
if node.left:
... | the_stack_v2_python_sparse | serialize and deserialize.py | jmshin111/alogrithm-test | train | 0 | |
b7dfcb88c01a9156018343f186993bdfa062652c | [
"ret = [1] * len(nums)\nprod = 1\nfor i in xrange(len(nums)):\n ret[i] = prod\n prod *= nums[i]\nprod = 1\nfor i in xrange(len(nums) - 1, -1, -1):\n ret[i] *= prod\n prod *= nums[i]\nreturn ret",
"ret = [1] * len(nums)\nfor i in xrange(1, len(nums)):\n ret[i] = ret[i - 1] * nums[i - 1]\nfor i in xr... | <|body_start_0|>
ret = [1] * len(nums)
prod = 1
for i in xrange(len(nums)):
ret[i] = prod
prod *= nums[i]
prod = 1
for i in xrange(len(nums) - 1, -1, -1):
ret[i] *= prod
prod *= nums[i]
return ret
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = [1] * len(nums)... | stack_v2_sparse_classes_36k_train_013930 | 957 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Soluti... | 1a0dbcabb0f454a4fdcc31af9b919f5d30664335 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def productExceptSelf(self, nums):
""":type nums: List[int] :rtype: List[int]"""
ret = [1] * len(nums)
prod = 1
for i in xrange(len(nums)):
ret[i] = prod
prod *= nums[i]
prod = 1
for i in xrange(len(nums) - 1, -1, -1):
... | the_stack_v2_python_sparse | 238. Product of Array Except Self.py | haomingchan0811/Leetcode | train | 0 | |
2a22485845e27007b8d94fa51e2827223229abc5 | [
"self.dict_1 = {'a': 1, 'b': 2, 'c': 3}\nself.dict_2 = {'b': 2, 'a': 1, 'c': 3}\nself.dict_3 = {'a': 4, 'b': 5, 'c': 6}\nself.dict_4 = {'d': 1, 'e': 2, 'f': 3}\nself.list_1 = [1, 2, 3, 9, 10]\nself.list_2 = [1, 3, 3, 4, 19]\nself.list_3 = [1, 5, 8, 3]\nself.list_4 = [-x for x in self.list_1]\nself.list_5 = [-x for ... | <|body_start_0|>
self.dict_1 = {'a': 1, 'b': 2, 'c': 3}
self.dict_2 = {'b': 2, 'a': 1, 'c': 3}
self.dict_3 = {'a': 4, 'b': 5, 'c': 6}
self.dict_4 = {'d': 1, 'e': 2, 'f': 3}
self.list_1 = [1, 2, 3, 9, 10]
self.list_2 = [1, 3, 3, 4, 19]
self.list_3 = [1, 5, 8, 3]
... | Unit test class for ancillary utilities. | AncillaryUtilsTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AncillaryUtilsTestCase:
"""Unit test class for ancillary utilities."""
def setUp(self):
"""Sets up attributes."""
<|body_0|>
def test_compare_dict(self):
"""Test compare_dict function."""
<|body_1|>
def test_nondecreasing(self):
"""Unit tests... | stack_v2_sparse_classes_36k_train_013931 | 2,664 | permissive | [
{
"docstring": "Sets up attributes.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test compare_dict function.",
"name": "test_compare_dict",
"signature": "def test_compare_dict(self)"
},
{
"docstring": "Unit tests for is_nondecreasing.",
"name": "test_n... | 6 | stack_v2_sparse_classes_30k_train_004656 | Implement the Python class `AncillaryUtilsTestCase` described below.
Class description:
Unit test class for ancillary utilities.
Method signatures and docstrings:
- def setUp(self): Sets up attributes.
- def test_compare_dict(self): Test compare_dict function.
- def test_nondecreasing(self): Unit tests for is_nondecr... | Implement the Python class `AncillaryUtilsTestCase` described below.
Class description:
Unit test class for ancillary utilities.
Method signatures and docstrings:
- def setUp(self): Sets up attributes.
- def test_compare_dict(self): Test compare_dict function.
- def test_nondecreasing(self): Unit tests for is_nondecr... | 3eef7d30bcc2e56f2221a624bd8ec7f933f81e40 | <|skeleton|>
class AncillaryUtilsTestCase:
"""Unit test class for ancillary utilities."""
def setUp(self):
"""Sets up attributes."""
<|body_0|>
def test_compare_dict(self):
"""Test compare_dict function."""
<|body_1|>
def test_nondecreasing(self):
"""Unit tests... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AncillaryUtilsTestCase:
"""Unit test class for ancillary utilities."""
def setUp(self):
"""Sets up attributes."""
self.dict_1 = {'a': 1, 'b': 2, 'c': 3}
self.dict_2 = {'b': 2, 'a': 1, 'c': 3}
self.dict_3 = {'a': 4, 'b': 5, 'c': 6}
self.dict_4 = {'d': 1, 'e': 2, 'f'... | the_stack_v2_python_sparse | dragonfly/utils/unittest_ancillary_utils.py | dragonfly/dragonfly | train | 868 |
54e597374cd1f1d0218523704c4666c5e35aff79 | [
"if not exists(CHROME_DRIVER_BIN):\n print('--------------')\n print('ERROR: Could not find chromedriver at (' + CHROME_DRIVER_BIN + ')')\n print('Please install it through your distributions package manager and set the correct path in config.py')\n exit(1)",
"chrome_options = webdriver.ChromeOptions(... | <|body_start_0|>
if not exists(CHROME_DRIVER_BIN):
print('--------------')
print('ERROR: Could not find chromedriver at (' + CHROME_DRIVER_BIN + ')')
print('Please install it through your distributions package manager and set the correct path in config.py')
exit(1... | Driver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
def check_if_installed():
"""Check if the driver has been installed (and is located at specified location). Quits the script if not"""
<|body_0|>
def init_driver() -> webdriver.Chrome:
"""Initializes chromedriver"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_013932 | 1,249 | permissive | [
{
"docstring": "Check if the driver has been installed (and is located at specified location). Quits the script if not",
"name": "check_if_installed",
"signature": "def check_if_installed()"
},
{
"docstring": "Initializes chromedriver",
"name": "init_driver",
"signature": "def init_drive... | 2 | stack_v2_sparse_classes_30k_train_018616 | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def check_if_installed(): Check if the driver has been installed (and is located at specified location). Quits the script if not
- def init_driver() -> webdriver.Chrome: Initializes ... | Implement the Python class `Driver` described below.
Class description:
Implement the Driver class.
Method signatures and docstrings:
- def check_if_installed(): Check if the driver has been installed (and is located at specified location). Quits the script if not
- def init_driver() -> webdriver.Chrome: Initializes ... | a9d91bf29e7de3faa23d098d69ac6265bcf2c0b5 | <|skeleton|>
class Driver:
def check_if_installed():
"""Check if the driver has been installed (and is located at specified location). Quits the script if not"""
<|body_0|>
def init_driver() -> webdriver.Chrome:
"""Initializes chromedriver"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
def check_if_installed():
"""Check if the driver has been installed (and is located at specified location). Quits the script if not"""
if not exists(CHROME_DRIVER_BIN):
print('--------------')
print('ERROR: Could not find chromedriver at (' + CHROME_DRIVER_BIN +... | the_stack_v2_python_sparse | facebookcli/driver.py | Senth/facebook-cli | train | 0 | |
792005fead7cd1fb915de7faf8fa1eab4d1e830a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AgreementAcceptance()",
"from .agreement_acceptance_state import AgreementAcceptanceState\nfrom .entity import Entity\nfrom .agreement_acceptance_state import AgreementAcceptanceState\nfrom .entity import Entity\nfields: Dict[str, Call... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AgreementAcceptance()
<|end_body_0|>
<|body_start_1|>
from .agreement_acceptance_state import AgreementAcceptanceState
from .entity import Entity
from .agreement_acceptance_state... | AgreementAcceptance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgreementAcceptance:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AgreementAcceptance:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k_train_013933 | 5,972 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AgreementAcceptance",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `AgreementAcceptance` described below.
Class description:
Implement the AgreementAcceptance class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AgreementAcceptance: Creates a new instance of the appropriate class based on d... | Implement the Python class `AgreementAcceptance` described below.
Class description:
Implement the AgreementAcceptance class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AgreementAcceptance: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AgreementAcceptance:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AgreementAcceptance:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgreementAcceptance:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AgreementAcceptance:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/agreement_acceptance.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
29a56c9904628fc9b23a56666e349e410beb5471 | [
"self._derivatives = derivatives\nfor param_str in params:\n if not hasattr(self, param_str):\n setattr(self, param_str, self._make_param_function(param_str))\nsuper().__init__(params=params)",
"def param_function(ext: BatchGrad, module: Module, g_inp: Tuple[Tensor], g_out: Tuple[Tensor], bpQuantities: ... | <|body_start_0|>
self._derivatives = derivatives
for param_str in params:
if not hasattr(self, param_str):
setattr(self, param_str, self._make_param_function(param_str))
super().__init__(params=params)
<|end_body_0|>
<|body_start_1|>
def param_function(ext: B... | Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface for parameter "param1":: param... | BatchGradBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchGradBase:
"""Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the... | stack_v2_sparse_classes_36k_train_013934 | 3,051 | permissive | [
{
"docstring": "Initializes all methods. If the param method has already been defined, it is left unchanged. Args: derivatives: Derivatives object used to apply parameter Jacobians. params: List of parameter names.",
"name": "__init__",
"signature": "def __init__(self, derivatives: BaseParameterDerivati... | 2 | stack_v2_sparse_classes_30k_train_010020 | Implement the Python class `BatchGradBase` described below.
Class description:
Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional e... | Implement the Python class `BatchGradBase` described below.
Class description:
Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional e... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class BatchGradBase:
"""Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchGradBase:
"""Calculates the batch_grad derivative. Passes the calls for the parameters to the derivatives class. Implements functions with method names from params. If child class wants to overwrite these methods - for example to support an additional external module - it can do so using the interface fo... | the_stack_v2_python_sparse | backpack/extensions/firstorder/batch_grad/batch_grad_base.py | f-dangel/backpack | train | 505 |
9ea1c2746cd676d8a16df87e9b920ae9f6c52dd6 | [
"seq_length = 4\nnum_predictions = 2\nxlnet_base = _get_xlnet_base()\nxlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)\ninputs = dict(input_word_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32, name='input_word_ids'), input_type_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.in... | <|body_start_0|>
seq_length = 4
num_predictions = 2
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)
inputs = dict(input_word_ids=tf.keras.layers.Input(shape=(seq_length,), dtype=tf.int32, name='input_word_ids'), input_type_ids=tf.ker... | XLNetPretrainerTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserialize(self):
... | stack_v2_sparse_classes_36k_train_013935 | 13,124 | permissive | [
{
"docstring": "Validates that the Keras object can be created.",
"name": "test_xlnet_trainer",
"signature": "def test_xlnet_trainer(self)"
},
{
"docstring": "Validates that the Keras object can be invoked.",
"name": "test_xlnet_tensor_call",
"signature": "def test_xlnet_tensor_call(self... | 3 | stack_v2_sparse_classes_30k_train_008298 | Implement the Python class `XLNetPretrainerTest` described below.
Class description:
Implement the XLNetPretrainerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validates that the Keras object can be created.
- def test_xlnet_tensor_call(self): Validates that the Keras object can be inv... | Implement the Python class `XLNetPretrainerTest` described below.
Class description:
Implement the XLNetPretrainerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validates that the Keras object can be created.
- def test_xlnet_tensor_call(self): Validates that the Keras object can be inv... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserialize(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XLNetPretrainerTest:
def test_xlnet_trainer(self):
"""Validates that the Keras object can be created."""
seq_length = 4
num_predictions = 2
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetPretrainer(network=xlnet_base)
inputs = dict(input_word_id... | the_stack_v2_python_sparse | models/official/nlp/modeling/models/xlnet_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
ece8ece4f75df2572e803e9bffc890bb4a9f6073 | [
"val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)\nself.assertEqual(val, Decimal('3.5'))\nval = round_decimal(val=3.4, places=5, roundfactor=-0.5, normalize=True)\nself.assertEqual(val, Decimal('3'))\nval = round_decimal(val=0, places=5, roundfactor=-0.5, normalize=False)\nself.assertEqual(va... | <|body_start_0|>
val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)
self.assertEqual(val, Decimal('3.5'))
val = round_decimal(val=3.4, places=5, roundfactor=-0.5, normalize=True)
self.assertEqual(val, Decimal('3'))
val = round_decimal(val=0, places=5, roundfa... | TestRoundedDecimals | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
<|body_0|>
def testTruncDecimal(self):
"""Test trunc_decimal's rounding behavior."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val =... | stack_v2_sparse_classes_36k_train_013936 | 3,005 | permissive | [
{
"docstring": "Test Partial Unit Rounding Decimal Conversion behavior",
"name": "testRoundingDecimals",
"signature": "def testRoundingDecimals(self)"
},
{
"docstring": "Test trunc_decimal's rounding behavior.",
"name": "testTruncDecimal",
"signature": "def testTruncDecimal(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000747 | Implement the Python class `TestRoundedDecimals` described below.
Class description:
Implement the TestRoundedDecimals class.
Method signatures and docstrings:
- def testRoundingDecimals(self): Test Partial Unit Rounding Decimal Conversion behavior
- def testTruncDecimal(self): Test trunc_decimal's rounding behavior. | Implement the Python class `TestRoundedDecimals` described below.
Class description:
Implement the TestRoundedDecimals class.
Method signatures and docstrings:
- def testRoundingDecimals(self): Test Partial Unit Rounding Decimal Conversion behavior
- def testTruncDecimal(self): Test trunc_decimal's rounding behavior.... | cd8ce63fdb94f1a7cf095a79edfb8350d0ea2938 | <|skeleton|>
class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
<|body_0|>
def testTruncDecimal(self):
"""Test trunc_decimal's rounding behavior."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRoundedDecimals:
def testRoundingDecimals(self):
"""Test Partial Unit Rounding Decimal Conversion behavior"""
val = round_decimal(val=3.4, places=5, roundfactor=0.5, normalize=True)
self.assertEqual(val, Decimal('3.5'))
val = round_decimal(val=3.4, places=5, roundfactor=-0.... | the_stack_v2_python_sparse | satchmo/apps/satchmo_utils/tests.py | twidi/satchmo | train | 2 | |
53685b4dccb641ea5d11ed199971c3222b883dc8 | [
"while True:\n container = scan_q.get()\n self.process_container(container)\n scan_q.task_done()",
"j = journal.Reader(path='/host/var/log/journal')\nj.log_level(journal.LOG_INFO)\nj.this_boot()\nj.add_match(_SYSTEMD_UNIT=u'atomic-openshift-node.service')\nj.seek_tail()\nj.get_previous()\npollobj = selec... | <|body_start_0|>
while True:
container = scan_q.get()
self.process_container(container)
scan_q.task_done()
<|end_body_0|>
<|body_start_1|>
j = journal.Reader(path='/host/var/log/journal')
j.log_level(journal.LOG_INFO)
j.this_boot()
j.add_match... | Class to receive and report scan results. | PlegEventListener | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
<|body_0|>
def catch_creates(scan_q):
"""Watch the host node journal for creates."""
<|body_1|>
def process_container(cont... | stack_v2_sparse_classes_36k_train_013937 | 3,450 | permissive | [
{
"docstring": "Worker thread function.",
"name": "scan_worker",
"signature": "def scan_worker(self, scan_q)"
},
{
"docstring": "Watch the host node journal for creates.",
"name": "catch_creates",
"signature": "def catch_creates(scan_q)"
},
{
"docstring": "Check if provided conta... | 4 | stack_v2_sparse_classes_30k_train_007019 | Implement the Python class `PlegEventListener` described below.
Class description:
Class to receive and report scan results.
Method signatures and docstrings:
- def scan_worker(self, scan_q): Worker thread function.
- def catch_creates(scan_q): Watch the host node journal for creates.
- def process_container(containe... | Implement the Python class `PlegEventListener` described below.
Class description:
Class to receive and report scan results.
Method signatures and docstrings:
- def scan_worker(self, scan_q): Worker thread function.
- def catch_creates(scan_q): Watch the host node journal for creates.
- def process_container(containe... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
<|body_0|>
def catch_creates(scan_q):
"""Watch the host node journal for creates."""
<|body_1|>
def process_container(cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
while True:
container = scan_q.get()
self.process_container(container)
scan_q.task_done()
def catch_creates(scan_q):
... | the_stack_v2_python_sparse | docker/oso-image-inspector/src/scripts/orchestrator | openshift/openshift-tools | train | 170 |
212d5fc81d362958553b39a4c0a1aab69d27db91 | [
"tracks: List[Dict[str, Any]] = []\ntracks = VehicleTracks.IDs(self, tracks)\ntracks = VehicleTracks.Table(self, tracks)\nUtility.WriteFile(self, f'{self.eXAssets}/vehicleTracks.json', tracks)\nlog.info(f'Compiled {len(tracks):,} Vehicle Tracks')",
"ids: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAsse... | <|body_start_0|>
tracks: List[Dict[str, Any]] = []
tracks = VehicleTracks.IDs(self, tracks)
tracks = VehicleTracks.Table(self, tracks)
Utility.WriteFile(self, f'{self.eXAssets}/vehicleTracks.json', tracks)
log.info(f'Compiled {len(tracks):,} Vehicle Tracks')
<|end_body_0|>
<|bod... | Vehicle Tracks XAssets. | VehicleTracks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehicleTracks:
"""Vehicle Tracks XAssets."""
def Compile(self: Any) -> None:
"""Compile the Vehicle Track XAssets."""
<|body_0|>
def IDs(self: Any, tracks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/vehicle_track_ids.csv XAsset."""
... | stack_v2_sparse_classes_36k_train_013938 | 2,862 | permissive | [
{
"docstring": "Compile the Vehicle Track XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the loot/vehicle_track_ids.csv XAsset.",
"name": "IDs",
"signature": "def IDs(self: Any, tracks: List[Dict[str, Any]]) -> List[Dict[str, Any]]"... | 3 | stack_v2_sparse_classes_30k_train_019757 | Implement the Python class `VehicleTracks` described below.
Class description:
Vehicle Tracks XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Vehicle Track XAssets.
- def IDs(self: Any, tracks: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/vehicle_track_ids.c... | Implement the Python class `VehicleTracks` described below.
Class description:
Vehicle Tracks XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Vehicle Track XAssets.
- def IDs(self: Any, tracks: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/vehicle_track_ids.c... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class VehicleTracks:
"""Vehicle Tracks XAssets."""
def Compile(self: Any) -> None:
"""Compile the Vehicle Track XAssets."""
<|body_0|>
def IDs(self: Any, tracks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/vehicle_track_ids.csv XAsset."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VehicleTracks:
"""Vehicle Tracks XAssets."""
def Compile(self: Any) -> None:
"""Compile the Vehicle Track XAssets."""
tracks: List[Dict[str, Any]] = []
tracks = VehicleTracks.IDs(self, tracks)
tracks = VehicleTracks.Table(self, tracks)
Utility.WriteFile(self, f'{se... | the_stack_v2_python_sparse | ModernWarfare/XAssets/vehicleTracks.py | dbuentello/Hyde | train | 0 |
a29e25f302d2364307da149b16f1026b16c39a8e | [
"def helper(i, j):\n if i == j:\n return nums[i]\n if (i, j) in memo:\n return memo[i, j]\n score = max(nums[j] - helper(i, j - 1), nums[i] - helper(i + 1, j))\n memo[i, j] = score\n return score\nmemo = {}\nreturn helper(0, len(nums) - 1) >= 0",
"n = len(nums)\ndp = nums[:]\nfor s in... | <|body_start_0|>
def helper(i, j):
if i == j:
return nums[i]
if (i, j) in memo:
return memo[i, j]
score = max(nums[j] - helper(i, j - 1), nums[i] - helper(i + 1, j))
memo[i, j] = score
return score
memo = {}
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def predictTheWinner_Solution_1(self, nums: List[int]) -> bool:
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def predictTheWinner_Solution_2(self, nums: List[int]) -> bool:
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def predictT... | stack_v2_sparse_classes_36k_train_013939 | 5,385 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "predictTheWinner_Solution_1",
"signature": "def predictTheWinner_Solution_1(self, nums: List[int]) -> bool"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "predictTheWinner_Solution_2",
"signature": "def predi... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def predictTheWinner_Solution_1(self, nums: List[int]) -> bool: :type nums: List[int] :rtype: bool
- def predictTheWinner_Solution_2(self, nums: List[int]) -> bool: :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def predictTheWinner_Solution_1(self, nums: List[int]) -> bool: :type nums: List[int] :rtype: bool
- def predictTheWinner_Solution_2(self, nums: List[int]) -> bool: :type nums: L... | f2621cd76822a922c49b60f32931f26cce1c571d | <|skeleton|>
class Solution:
def predictTheWinner_Solution_1(self, nums: List[int]) -> bool:
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def predictTheWinner_Solution_2(self, nums: List[int]) -> bool:
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def predictT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def predictTheWinner_Solution_1(self, nums: List[int]) -> bool:
""":type nums: List[int] :rtype: bool"""
def helper(i, j):
if i == j:
return nums[i]
if (i, j) in memo:
return memo[i, j]
score = max(nums[j] - helper(i... | the_stack_v2_python_sparse | Dynamic_Programming/021_leetcode_P_486_PredictTheWinner/Solution.py | Keshav1506/competitive_programming | train | 0 | |
dcee80352c93df7f9dccfef14c15ea31dd7bfe88 | [
"super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)",
"h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred"
] | <|body_start_0|>
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
<|end_body_1|>
| TwoLayerNet | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_36k_train_013940 | 1,980 | permissive | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d... | 2 | stack_v2_sparse_classes_30k_train_002065 | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | 02f6ceba1b9e6428d1fb7a0b765c828c1a1a5f7a | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forw... | the_stack_v2_python_sparse | deepml/pytorch-examples02/nn/two_layer_net_module.py | databooks/databook | train | 23 | |
21b80de28a1487f3254ee247d598c872f89396a1 | [
"super(SymmetricCrossEntropyLoss, self).__init__()\nself.alpha = alpha\nself.beta = beta",
"num_classes = input_.shape[1]\ntarget_one_hot = F.one_hot(target, num_classes).float()\nassert target_one_hot.shape == input_.shape\ninput_ = torch.clamp(input_, min=1e-07, max=1.0)\ntarget_one_hot = torch.clamp(target_one... | <|body_start_0|>
super(SymmetricCrossEntropyLoss, self).__init__()
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
num_classes = input_.shape[1]
target_one_hot = F.one_hot(target, num_classes).float()
assert target_one_hot.shape == input_.shape
... | The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112 | SymmetricCrossEntropyLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0... | stack_v2_sparse_classes_36k_train_013941 | 3,544 | permissive | [
{
"docstring": "Args: alpha(float): corresponds to overfitting issue of CE beta(float): corresponds to flexible exploration on the robustness of RCE",
"name": "__init__",
"signature": "def __init__(self, alpha: float=1.0, beta: float=1.0)"
},
{
"docstring": "Calculates loss between ``input_`` an... | 2 | stack_v2_sparse_classes_30k_train_020424 | Implement the Python class `SymmetricCrossEntropyLoss` described below.
Class description:
The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112
Met... | Implement the Python class `SymmetricCrossEntropyLoss` described below.
Class description:
The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112
Met... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0, beta: float... | the_stack_v2_python_sparse | catalyst/contrib/losses/ce.py | catalyst-team/catalyst | train | 3,038 |
76f9b2dabf8e91810c16c02f10edc48858557929 | [
"input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape\nrand_min, rand_max = rand_range\nself.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes])\nself.num_trials = num_trials\nself.num_input_per_trial = nu... | <|body_start_0|>
input_shapes = [input_shape] if isinstance(input_shape, tuple) else input_shape
rand_min, rand_max = rand_range
self.sample_input = tuple([((rand_max - rand_min) * torch.rand(*input_shape) + rand_min).type(input_dtype) for input_shape in input_shapes])
self.num_trials = ... | AvgOnnxLatency | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the... | stack_v2_sparse_classes_36k_train_013942 | 4,455 | permissive | [
{
"docstring": "Measure the average ONNX Latency (in millseconds) of a model Args: input_shape (Union[Tuple, List[Tuple]]): Model Input shape or list of model input shapes. num_trials (int, optional): Number of trials. Defaults to 15. num_input (int, optional): Number of input per trial. Defaults to 15. input_d... | 3 | stack_v2_sparse_classes_30k_train_019645 | Implement the Python class `AvgOnnxLatency` described below.
Class description:
Implement the AvgOnnxLatency class.
Method signatures and docstrings:
- def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float... | Implement the Python class `AvgOnnxLatency` described below.
Class description:
Implement the AvgOnnxLatency class.
Method signatures and docstrings:
- def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float... | 95d6e19a1523a701b3fbc249dd1a7d1e7ba44aee | <|skeleton|>
class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvgOnnxLatency:
def __init__(self, input_shape: Union[Tuple, List[Tuple]], num_trials: int=15, num_input: int=15, input_dtype: str='torch.FloatTensor', rand_range: Tuple[float, float]=(0.0, 1.0), export_kwargs: Optional[Dict]=None, inf_session_kwargs: Optional[Dict]=None):
"""Measure the average ONNX ... | the_stack_v2_python_sparse | tasks/facial_landmark_detection/latency.py | microsoft/archai | train | 439 | |
8d4a7674d4d269f5e27f8d2dc6d4868214ea8c9e | [
"self.buckets = 1000\nself.itemsPerBucket = 1001\nself.table = [[] for _ in range(self.buckets)]",
"if not self.contains(key):\n hashKey = key % self.buckets\n if len(self.table[hashKey]) <= 0:\n self.table[hashKey] = [False] * self.itemsPerBucket\n self.table[hashKey][key / self.buckets] = True",... | <|body_start_0|>
self.buckets = 1000
self.itemsPerBucket = 1001
self.table = [[] for _ in range(self.buckets)]
<|end_body_0|>
<|body_start_1|>
if not self.contains(key):
hashKey = key % self.buckets
if len(self.table[hashKey]) <= 0:
self.table[has... | MyHashSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, key):
""":type key: int :rtype: None"""
<|body_1|>
def remove(self, key):
""":type key: int :rtype: None"""
<|body_2|>
def contains(se... | stack_v2_sparse_classes_36k_train_013943 | 1,333 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type key: int :rtype: None",
"name": "add",
"signature": "def add(self, key)"
},
{
"docstring": ":type key: int :rtype: None",
"name": "remove",
... | 4 | stack_v2_sparse_classes_30k_train_015784 | Implement the Python class `MyHashSet` described below.
Class description:
Implement the MyHashSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, key): :type key: int :rtype: None
- def remove(self, key): :type key: int :rtype: None
- def contains(s... | Implement the Python class `MyHashSet` described below.
Class description:
Implement the MyHashSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def add(self, key): :type key: int :rtype: None
- def remove(self, key): :type key: int :rtype: None
- def contains(s... | 58b65c4282c5ccd0f66ec670954973422f3b6afd | <|skeleton|>
class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def add(self, key):
""":type key: int :rtype: None"""
<|body_1|>
def remove(self, key):
""":type key: int :rtype: None"""
<|body_2|>
def contains(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyHashSet:
def __init__(self):
"""Initialize your data structure here."""
self.buckets = 1000
self.itemsPerBucket = 1001
self.table = [[] for _ in range(self.buckets)]
def add(self, key):
""":type key: int :rtype: None"""
if not self.contains(key):
... | the_stack_v2_python_sparse | 20190131/705_Design_HashSet.py | zdsh/leetcode | train | 0 | |
f0a90cb1b2c37b63c33ca8b97150147cf402e6e4 | [
"AbstractWriter.__init__(self)\nself._fields = fields\nself.fields_format = None\nself.format = outformat\nself.encoding = encoding\nif outformat is not None:\n pattern = re.compile('%\\\\(([a-z]+)\\\\)')\n _fields = pattern.findall(outformat)\n self.fields_format = lambda kdoc: outformat % {field: kdoc[fi... | <|body_start_0|>
AbstractWriter.__init__(self)
self._fields = fields
self.fields_format = None
self.format = outformat
self.encoding = encoding
if outformat is not None:
pattern = re.compile('%\\(([a-z]+)\\)')
_fields = pattern.findall(outformat)
... | Write a repr. of documents on the standart output | ScreenWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScreenWriter:
"""Write a repr. of documents on the standart output"""
def __init__(self, fields=None, outformat=None, encoding='utf8'):
"""@param fields: print only the indicated fields (all if None) @param outformat : pythonic dict format "docnum:%(docnum)s title:%(title)s " % {'doc... | stack_v2_sparse_classes_36k_train_013944 | 5,392 | no_license | [
{
"docstring": "@param fields: print only the indicated fields (all if None) @param outformat : pythonic dict format \"docnum:%(docnum)s title:%(title)s \" % {'docnum':'any', 'title': 'boo'} > docnum:any title:boo",
"name": "__init__",
"signature": "def __init__(self, fields=None, outformat=None, encodi... | 2 | stack_v2_sparse_classes_30k_train_018988 | Implement the Python class `ScreenWriter` described below.
Class description:
Write a repr. of documents on the standart output
Method signatures and docstrings:
- def __init__(self, fields=None, outformat=None, encoding='utf8'): @param fields: print only the indicated fields (all if None) @param outformat : pythonic... | Implement the Python class `ScreenWriter` described below.
Class description:
Write a repr. of documents on the standart output
Method signatures and docstrings:
- def __init__(self, fields=None, outformat=None, encoding='utf8'): @param fields: print only the indicated fields (all if None) @param outformat : pythonic... | 27e1d8b79e2511a2515c6df85609a3aebdcad6d8 | <|skeleton|>
class ScreenWriter:
"""Write a repr. of documents on the standart output"""
def __init__(self, fields=None, outformat=None, encoding='utf8'):
"""@param fields: print only the indicated fields (all if None) @param outformat : pythonic dict format "docnum:%(docnum)s title:%(title)s " % {'doc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScreenWriter:
"""Write a repr. of documents on the standart output"""
def __init__(self, fields=None, outformat=None, encoding='utf8'):
"""@param fields: print only the indicated fields (all if None) @param outformat : pythonic dict format "docnum:%(docnum)s title:%(title)s " % {'docnum':'any', '... | the_stack_v2_python_sparse | cello/writers.py | ynnk/cello | train | 1 |
0b93c4b698d0bef25bebec47b0fc6d77b689bdd3 | [
"input_xml_string = get_sample_xml_string()\nelement_tree = ET.parse(StringIO(input_xml_string))\nout = StringIO()\nelement_tree.write(out)\noutput_xml_string = out.getvalue()\nself.assertEquals(input_xml_string, output_xml_string)",
"input_xml_string = get_sample_xml_string()\nmixture_model = deserialize_mixture... | <|body_start_0|>
input_xml_string = get_sample_xml_string()
element_tree = ET.parse(StringIO(input_xml_string))
out = StringIO()
element_tree.write(out)
output_xml_string = out.getvalue()
self.assertEquals(input_xml_string, output_xml_string)
<|end_body_0|>
<|body_start_... | TestDirectRna | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDirectRna:
def test_sample_xml_string(self):
"""Verify that creating the sample xml string does not cause an exception."""
<|body_0|>
def test_serialization(self):
"""Verify that serialization and deserialization works."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_013945 | 11,087 | no_license | [
{
"docstring": "Verify that creating the sample xml string does not cause an exception.",
"name": "test_sample_xml_string",
"signature": "def test_sample_xml_string(self)"
},
{
"docstring": "Verify that serialization and deserialization works.",
"name": "test_serialization",
"signature":... | 2 | null | Implement the Python class `TestDirectRna` described below.
Class description:
Implement the TestDirectRna class.
Method signatures and docstrings:
- def test_sample_xml_string(self): Verify that creating the sample xml string does not cause an exception.
- def test_serialization(self): Verify that serialization and ... | Implement the Python class `TestDirectRna` described below.
Class description:
Implement the TestDirectRna class.
Method signatures and docstrings:
- def test_sample_xml_string(self): Verify that creating the sample xml string does not cause an exception.
- def test_serialization(self): Verify that serialization and ... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class TestDirectRna:
def test_sample_xml_string(self):
"""Verify that creating the sample xml string does not cause an exception."""
<|body_0|>
def test_serialization(self):
"""Verify that serialization and deserialization works."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDirectRna:
def test_sample_xml_string(self):
"""Verify that creating the sample xml string does not cause an exception."""
input_xml_string = get_sample_xml_string()
element_tree = ET.parse(StringIO(input_xml_string))
out = StringIO()
element_tree.write(out)
... | the_stack_v2_python_sparse | DirectRna.py | argriffing/xgcode | train | 1 | |
e97aac7faa47fc2208cbe17cea3e9917e2b1707d | [
"self.made = made\nself.shooter = shooter\nself.team = team\nself.location = location\nself.assister = assister\nself.quarter = quarter",
"if self.quarter == 1:\n minutes = int(time.split(':')[0])\n minutes += 20\n seconds = time.split(':')[1]\n self.time = str(minutes + ':' + seconds)\nelse:\n sel... | <|body_start_0|>
self.made = made
self.shooter = shooter
self.team = team
self.location = location
self.assister = assister
self.quarter = quarter
<|end_body_0|>
<|body_start_1|>
if self.quarter == 1:
minutes = int(time.split(':')[0])
minu... | Shot | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shot:
def __init__(self, made, shooter, team, location, assister, quarter):
"""-player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far from the basket with basket location being [0,0] -assister is a Player class object"""
... | stack_v2_sparse_classes_36k_train_013946 | 5,106 | permissive | [
{
"docstring": "-player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far from the basket with basket location being [0,0] -assister is a Player class object",
"name": "__init__",
"signature": "def __init__(self, made, shooter, team, location, assi... | 2 | stack_v2_sparse_classes_30k_train_021438 | Implement the Python class `Shot` described below.
Class description:
Implement the Shot class.
Method signatures and docstrings:
- def __init__(self, made, shooter, team, location, assister, quarter): -player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far fr... | Implement the Python class `Shot` described below.
Class description:
Implement the Shot class.
Method signatures and docstrings:
- def __init__(self, made, shooter, team, location, assister, quarter): -player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far fr... | 75eee203746d169021c32e580bd184c22c51e1ea | <|skeleton|>
class Shot:
def __init__(self, made, shooter, team, location, assister, quarter):
"""-player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far from the basket with basket location being [0,0] -assister is a Player class object"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shot:
def __init__(self, made, shooter, team, location, assister, quarter):
"""-player is a Player class object -made is a string, either 'made' or 'missed' -location is a list showing how far from the basket with basket location being [0,0] -assister is a Player class object"""
self.made = ma... | the_stack_v2_python_sparse | ShotData/shot-data.py | samueltphd/CatsStats | train | 0 | |
bb1b1932492c568a3117bdff4f149386c95123f5 | [
"super(TabularNetBasic, self).__init__()\nself.fc1 = nn.Linear(meta_channels, 16)\nself.fc2 = nn.Linear(16, 8)\nself.fc3 = nn.Linear(8, out_channels)\nself.typenet = 'meta'\nself.sigmoid = nn.Sigmoid()",
"x = F.selu(self.fc1(x))\nx = F.selu(self.fc2(x))\nx = self.sigmoid(self.fc3(x))\nreturn x"
] | <|body_start_0|>
super(TabularNetBasic, self).__init__()
self.fc1 = nn.Linear(meta_channels, 16)
self.fc2 = nn.Linear(16, 8)
self.fc3 = nn.Linear(8, out_channels)
self.typenet = 'meta'
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
x = F.selu(self.fc... | Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_features=8, bias=True) (2): Linear(in_features=8, out_features=3, bias=True) (3): Sigmoi... | TabularNetBasic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabularNetBasic:
"""Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_features=8, bias=True) (2): Linear(in_feature... | stack_v2_sparse_classes_36k_train_013947 | 5,888 | no_license | [
{
"docstring": ":param meta_channels : int, metadata parameters size :param out_channels : int, number of output classes - default : out_channels = 2",
"name": "__init__",
"signature": "def __init__(self, meta_channels: int, out_channels: int=2) -> None"
},
{
"docstring": ":param x : torch.Tenso... | 2 | stack_v2_sparse_classes_30k_train_003330 | Implement the Python class `TabularNetBasic` described below.
Class description:
Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_featur... | Implement the Python class `TabularNetBasic` described below.
Class description:
Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_featur... | 9189d2eeb748b1e539a1062a09a06b38a09780de | <|skeleton|>
class TabularNetBasic:
"""Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_features=8, bias=True) (2): Linear(in_feature... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TabularNetBasic:
"""Basic neural network class for metadata. The output returns a sigmoid of size out_channels. Neural network structure : (classifier): (0): Linear(in_features=meta_channels, out_features=16, bias=True) (1): Linear(in_features=16, out_features=8, bias=True) (2): Linear(in_features=8, out_feat... | the_stack_v2_python_sparse | Simulations/helpers/model/baseline.py | emmahoggett/Error_class_lenstronomy | train | 1 |
6da0cb332487b42897331ba993693676ef3937f0 | [
"if root:\n self.flatten(root.right)\n self.flatten(root.left)\n print(root.val)\n root.right = self.nex\n root.left = None\n self.nex = root",
"if not root:\n return root\n\ndef dfs(root):\n if root:\n arr.append(root)\n dfs(root.left)\n dfs(root.right)\narr = []\ndum... | <|body_start_0|>
if root:
self.flatten(root.right)
self.flatten(root.left)
print(root.val)
root.right = self.nex
root.left = None
self.nex = root
<|end_body_0|>
<|body_start_1|>
if not root:
return root
def dfs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root:
... | stack_v2_sparse_classes_36k_train_013948 | 1,503 | no_license | [
{
"docstring": "思路: 1. 记录中间变量",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_000199 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 思路: 1. 记录中间变量
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 思路: 1. 记录中间变量
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
<|skeleton|>
class So... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
<|body_0|>
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""思路: 1. 记录中间变量"""
if root:
self.flatten(root.right)
self.flatten(root.left)
print(root.val)
root.right = self.nex
root.left = None
self.nex = root
def flatten(sel... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/114. 二叉树展开为链表.py | yiming1012/MyLeetCode | train | 2 | |
b73edc27839e60164b2314d602b95e1d862c82ab | [
"total = float(sum(self.count.values()))\nfor i, v in self.count.items():\n self[i] = v / total",
"s = ''\nfor i in sorted(self):\n s += i\nreturn s",
"self.alphabet = alphabet\nif dict_type == COUNT:\n self.count = in_dict\n self._freq_from_count()\nelif dict_type == FREQ:\n self.count = {}\n ... | <|body_start_0|>
total = float(sum(self.count.values()))
for i, v in self.count.items():
self[i] = v / total
<|end_body_0|>
<|body_start_1|>
s = ''
for i in sorted(self):
s += i
return s
<|end_body_1|>
<|body_start_2|>
self.alphabet = alphabet
... | Define class to handle frequency tables or letter count files. | FreqTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FreqTable:
"""Define class to handle frequency tables or letter count files."""
def _freq_from_count(self):
"""Calculate frequency from count values (PRIVATE)."""
<|body_0|>
def _alphabet_from_input(self):
"""Order the alphabet (PRIVATE)."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_013949 | 2,821 | permissive | [
{
"docstring": "Calculate frequency from count values (PRIVATE).",
"name": "_freq_from_count",
"signature": "def _freq_from_count(self)"
},
{
"docstring": "Order the alphabet (PRIVATE).",
"name": "_alphabet_from_input",
"signature": "def _alphabet_from_input(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_011818 | Implement the Python class `FreqTable` described below.
Class description:
Define class to handle frequency tables or letter count files.
Method signatures and docstrings:
- def _freq_from_count(self): Calculate frequency from count values (PRIVATE).
- def _alphabet_from_input(self): Order the alphabet (PRIVATE).
- d... | Implement the Python class `FreqTable` described below.
Class description:
Define class to handle frequency tables or letter count files.
Method signatures and docstrings:
- def _freq_from_count(self): Calculate frequency from count values (PRIVATE).
- def _alphabet_from_input(self): Order the alphabet (PRIVATE).
- d... | 595c5c46794ae08a1f19716636eac7430cededa1 | <|skeleton|>
class FreqTable:
"""Define class to handle frequency tables or letter count files."""
def _freq_from_count(self):
"""Calculate frequency from count values (PRIVATE)."""
<|body_0|>
def _alphabet_from_input(self):
"""Order the alphabet (PRIVATE)."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FreqTable:
"""Define class to handle frequency tables or letter count files."""
def _freq_from_count(self):
"""Calculate frequency from count values (PRIVATE)."""
total = float(sum(self.count.values()))
for i, v in self.count.items():
self[i] = v / total
def _alph... | the_stack_v2_python_sparse | env/Lib/site-packages/Bio/SubsMat/FreqTable.py | abner-lucas/tp-cruzi-db | train | 2 |
c3534b26e310b67407140712672adf0d2963268f | [
"if self.overwrite:\n raise ValueError('Overwrite does not work with downloading directories through wget. Please, remove the unwanted data manually')\ncommand = ['wget'] + wget_options + self.overwrite_options + [f'--directory-prefix={self.local_folder}', '--recursive', '--no-directories', f'{server_path}']\nlo... | <|body_start_0|>
if self.overwrite:
raise ValueError('Overwrite does not work with downloading directories through wget. Please, remove the unwanted data manually')
command = ['wget'] + wget_options + self.overwrite_options + [f'--directory-prefix={self.local_folder}', '--recursive', '--no-d... | Data downloader based on wget. | WGetDownloader | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
<|body_0|>
def download_file(self... | stack_v2_sparse_classes_36k_train_013950 | 3,289 | permissive | [
{
"docstring": "Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget",
"name": "download_folder",
"signature": "def download_folder(self, server_path, wget_options)"
},
{
"docstring": "Download file. Parameters ---------- se... | 3 | null | Implement the Python class `WGetDownloader` described below.
Class description:
Data downloader based on wget.
Method signatures and docstrings:
- def download_folder(self, server_path, wget_options): Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options f... | Implement the Python class `WGetDownloader` described below.
Class description:
Data downloader based on wget.
Method signatures and docstrings:
- def download_folder(self, server_path, wget_options): Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options f... | 0d2b68d6614c667141207affd7834cc49d34b203 | <|skeleton|>
class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
<|body_0|>
def download_file(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
if self.overwrite:
raise ValueError('Ov... | the_stack_v2_python_sparse | esmvaltool/cmorizers/data/downloaders/wget.py | ESMValGroup/ESMValTool | train | 196 |
8a11dc62c58145b6788693ef8d5eb54bb68ee311 | [
"if not head:\n return True\nmid = self.middleNode(head)\nl1 = head\nl2 = mid.next\nmid.next = None\nl2 = self.reverseList(l2)\nwhile l2:\n if l1.val != l2.val:\n return False\n l1 = l1.next\n l2 = l2.next\nreturn True",
"slow = fast = head\nwhile fast.next and fast.next.next:\n fast = fast.... | <|body_start_0|>
if not head:
return True
mid = self.middleNode(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = self.reverseList(l2)
while l2:
if l1.val != l2.val:
return False
l1 = l1.next
l2 = l2... | 快慢指针,找中点翻转列表 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def middleNode(self, head: ListNode) -> ListNode:
"""查找中点 :param head: :return:"""
<|body_1|>
def reverseList(self, head: ListNode) -> ListN... | stack_v2_sparse_classes_36k_train_013951 | 1,891 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": "查找中点 :param head: :return:",
"name": "middleNode",
"signature": "def middleNode(self, head: ListNode) -> ListNode"
},
{
"docstring": "翻转列表 :p... | 3 | stack_v2_sparse_classes_30k_train_019781 | Implement the Python class `Solution` described below.
Class description:
快慢指针,找中点翻转列表
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def middleNode(self, head: ListNode) -> ListNode: 查找中点 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode:... | Implement the Python class `Solution` described below.
Class description:
快慢指针,找中点翻转列表
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def middleNode(self, head: ListNode) -> ListNode: 查找中点 :param head: :return:
- def reverseList(self, head: ListNode) -> ListNode:... | aeaa6c84033a1a02dba0c6dfe194f5bd6d82bce5 | <|skeleton|>
class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def middleNode(self, head: ListNode) -> ListNode:
"""查找中点 :param head: :return:"""
<|body_1|>
def reverseList(self, head: ListNode) -> ListN... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""快慢指针,找中点翻转列表"""
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
if not head:
return True
mid = self.middleNode(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = self.reverseList(l2)
while l2:
... | the_stack_v2_python_sparse | letcode_234_回文链表.py | a313071162/letcode | train | 3 |
919cc4e5efa5b8fac7ea50e9b2e720279c093c3b | [
"home_dir = os.path.expanduser('~')\ncredential_dir = os.path.join(home_dir, '.credentials')\nif not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\ncredential_path = os.path.join(credential_dir, GmailApiUsage.APPLICATION_NAME + '.json')\nstore = Storage(credential_path)\ncredentials = store.get()... | <|body_start_0|>
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, GmailApiUsage.APPLICATION_NAME + '.json')
stor... | GmailApiUsage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GmailApiUsage:
def get_credentials():
"""Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_013952 | 3,464 | permissive | [
{
"docstring": "Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.",
"name": "get_credentials",
"signature": "def get_credentials()"
}... | 4 | stack_v2_sparse_classes_30k_train_003542 | Implement the Python class `GmailApiUsage` described below.
Class description:
Implement the GmailApiUsage class.
Method signatures and docstrings:
- def get_credentials(): Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to o... | Implement the Python class `GmailApiUsage` described below.
Class description:
Implement the GmailApiUsage class.
Method signatures and docstrings:
- def get_credentials(): Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to o... | f714ed8172aa290d3f13ff8b7f09f888a5b33640 | <|skeleton|>
class GmailApiUsage:
def get_credentials():
"""Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GmailApiUsage:
def get_credentials():
"""Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential."""
home_dir = os.path.expanduser('... | the_stack_v2_python_sparse | incubation-python/relative_scheduler/modules/gmailapiusage.py | yk0242/incubation | train | 1 | |
ce43b92f5b3b349459131776dc4053f9c0fb9126 | [
"fs = self._parse_fs(fs)\nif rotate_u:\n tmpdat = self.reshape(veldat[0] + 1j * veldat[1])\n tmpdat *= np.exp(-1j * np.angle(tmpdat.mean(-1)))\n if noise[0] != noise[1]:\n print('Warning: noise levels different for u,v. This means noise-correction cannot be done here when rotatin... | <|body_start_0|>
fs = self._parse_fs(fs)
if rotate_u:
tmpdat = self.reshape(veldat[0] + 1j * veldat[1])
tmpdat *= np.exp(-1j * np.angle(tmpdat.mean(-1)))
if noise[0] != noise[1]:
print('Warning: noise levels different for u,v. This means ... | VelBinnerSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VelBinnerSpec:
def calc_vel_psd(self, veldat, fs=None, rotate_u=False, noise=[0, 0, 0], n_pad=None, window='hann'):
"""Calculate the psd of velocity. Parameters ---------- veldat : np.ndarray The raw velocity data. fs : float (optional) The sample rate (default: from the binner). rotate_... | stack_v2_sparse_classes_36k_train_013953 | 15,509 | permissive | [
{
"docstring": "Calculate the psd of velocity. Parameters ---------- veldat : np.ndarray The raw velocity data. fs : float (optional) The sample rate (default: from the binner). rotate_u : bool (optional) If True, each 'bin' of horizontal velocity is rotated into its principal axis prior to calculating the psd.... | 2 | stack_v2_sparse_classes_30k_train_010191 | Implement the Python class `VelBinnerSpec` described below.
Class description:
Implement the VelBinnerSpec class.
Method signatures and docstrings:
- def calc_vel_psd(self, veldat, fs=None, rotate_u=False, noise=[0, 0, 0], n_pad=None, window='hann'): Calculate the psd of velocity. Parameters ---------- veldat : np.nd... | Implement the Python class `VelBinnerSpec` described below.
Class description:
Implement the VelBinnerSpec class.
Method signatures and docstrings:
- def calc_vel_psd(self, veldat, fs=None, rotate_u=False, noise=[0, 0, 0], n_pad=None, window='hann'): Calculate the psd of velocity. Parameters ---------- veldat : np.nd... | d807d0188f9e5f11845bc3f9efc7d154f729850a | <|skeleton|>
class VelBinnerSpec:
def calc_vel_psd(self, veldat, fs=None, rotate_u=False, noise=[0, 0, 0], n_pad=None, window='hann'):
"""Calculate the psd of velocity. Parameters ---------- veldat : np.ndarray The raw velocity data. fs : float (optional) The sample rate (default: from the binner). rotate_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VelBinnerSpec:
def calc_vel_psd(self, veldat, fs=None, rotate_u=False, noise=[0, 0, 0], n_pad=None, window='hann'):
"""Calculate the psd of velocity. Parameters ---------- veldat : np.ndarray The raw velocity data. fs : float (optional) The sample rate (default: from the binner). rotate_u : bool (opti... | the_stack_v2_python_sparse | dolfyn/data/velocity_legacy.py | MRE-Code-Hub/dolfyn | train | 0 | |
33b9cdb7c8a8d0a9f5cd248d4b7582b140825625 | [
"num_heads, head_size = (2, 2)\nfrom_seq_length = 4\nbatch_size = 3\ninit_decode_length = 0\ncache = _create_cache(batch_size, init_decode_length, num_heads, head_size)\nlayer = attention.CachedAttention(num_heads=num_heads, key_dim=head_size)\nfrom_data = tf.zeros((batch_size, from_seq_length, 8), dtype=np.float32... | <|body_start_0|>
num_heads, head_size = (2, 2)
from_seq_length = 4
batch_size = 3
init_decode_length = 0
cache = _create_cache(batch_size, init_decode_length, num_heads, head_size)
layer = attention.CachedAttention(num_heads=num_heads, key_dim=head_size)
from_data... | CachedAttentionTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
<|body_0|>
def test_padded_decode(self):
"""Test with a mask tensor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num_heads, head_size = (2, 2)
from_seq_... | stack_v2_sparse_classes_36k_train_013954 | 3,761 | permissive | [
{
"docstring": "Test with a mask tensor.",
"name": "test_masked_attention",
"signature": "def test_masked_attention(self)"
},
{
"docstring": "Test with a mask tensor.",
"name": "test_padded_decode",
"signature": "def test_padded_decode(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011100 | Implement the Python class `CachedAttentionTest` described below.
Class description:
Implement the CachedAttentionTest class.
Method signatures and docstrings:
- def test_masked_attention(self): Test with a mask tensor.
- def test_padded_decode(self): Test with a mask tensor. | Implement the Python class `CachedAttentionTest` described below.
Class description:
Implement the CachedAttentionTest class.
Method signatures and docstrings:
- def test_masked_attention(self): Test with a mask tensor.
- def test_padded_decode(self): Test with a mask tensor.
<|skeleton|>
class CachedAttentionTest:
... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
<|body_0|>
def test_padded_decode(self):
"""Test with a mask tensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedAttentionTest:
def test_masked_attention(self):
"""Test with a mask tensor."""
num_heads, head_size = (2, 2)
from_seq_length = 4
batch_size = 3
init_decode_length = 0
cache = _create_cache(batch_size, init_decode_length, num_heads, head_size)
layer... | the_stack_v2_python_sparse | models/official/nlp/modeling/layers/attention_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
2a0f1758b49a14d0ea3e0886e74fd3e3e7f18c6b | [
"username = self.cleaned_data['username']\nif User.objects.filter(username=username).exists():\n raise forms.ValidationError('用户名已存在')\nreturn username",
"email = self.cleaned_data['email']\nif User.objects.filter(email=email).exists():\n raise forms.ValidationError('邮箱已存在')\nreturn email",
"password = se... | <|body_start_0|>
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError('用户名已存在')
return username
<|end_body_0|>
<|body_start_1|>
email = self.cleaned_data['email']
if User.objects.filter(email=email).... | 注册表单 | RegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
<|body_0|>
def clean_email(self):
"""验证邮箱 :return:"""
<|body_1|>
def clean_password_again(self):
"""验证两次输入的密码是否一致 :return:"""
<|body_2|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_013955 | 10,740 | no_license | [
{
"docstring": "验证用户名 :return:",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "验证邮箱 :return:",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "验证两次输入的密码是否一致 :return:",
"name": "clean_password_again",
"s... | 3 | stack_v2_sparse_classes_30k_train_004716 | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证用户名 :return:
- def clean_email(self): 验证邮箱 :return:
- def clean_password_again(self): 验证两次输入的密码是否一致 :return: | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证用户名 :return:
- def clean_email(self): 验证邮箱 :return:
- def clean_password_again(self): 验证两次输入的密码是否一致 :return:
<|skeleton|>
class RegisterForm:
"""注册表单"""
def clea... | 01b949144ae55eab57d6da7054f061e31ba8457b | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
<|body_0|>
def clean_email(self):
"""验证邮箱 :return:"""
<|body_1|>
def clean_password_again(self):
"""验证两次输入的密码是否一致 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError('用户名已存在')
return username
def clean_email(self):
"""验证邮... | the_stack_v2_python_sparse | accounts/forms.py | oldestcrab/my_blog | train | 0 |
4bfce75251e9be1422e99e8890b65567d20bb59e | [
"self.name = 'SVRModel'\nsuper(SVRModel, self).__init__(self.name, use_logger)\nif self.use_logger:\n self.logger = ml.SciopeLogger().get_logger()\n self.logger.info('Support Vector Regression model initialized')",
"cs = [0.001, 0.01, 0.1, 1, 10]\ngammas = [0.001, 0.01, 0.1, 1]\nparam_grid = {'C': cs, 'gamm... | <|body_start_0|>
self.name = 'SVRModel'
super(SVRModel, self).__init__(self.name, use_logger)
if self.use_logger:
self.logger = ml.SciopeLogger().get_logger()
self.logger.info('Support Vector Regression model initialized')
<|end_body_0|>
<|body_start_1|>
cs = [0.... | We use the sklearn SVM implementation here. | SVRModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default ... | stack_v2_sparse_classes_36k_train_013956 | 3,383 | permissive | [
{
"docstring": "Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default False",
"name": "__init__",
"signature": "def __init__(self, use_logger=False)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_020403 | Implement the Python class `SVRModel` described below.
Class description:
We use the sklearn SVM implementation here.
Method signatures and docstrings:
- def __init__(self, use_logger=False): Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Con... | Implement the Python class `SVRModel` described below.
Class description:
We use the sklearn SVM implementation here.
Method signatures and docstrings:
- def __init__(self, use_logger=False): Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Con... | 5122107dedcee9c39458e83d853ec35f91268780 | <|skeleton|>
class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVRModel:
"""We use the sklearn SVM implementation here."""
def __init__(self, use_logger=False):
"""Initialize the model. Parameters ---------- name : string Model name; set by the derived class use_logger : bool, optional Controls whether logging is enabled or disabled, by default False"""
... | the_stack_v2_python_sparse | sciope/models/svm_regressor.py | rmjiang7/sciope | train | 0 |
3c58da696a26f28cf48bca9f77e455ec019e67f9 | [
"super(UnmanagedInstanceGroupMigration, self).__init__()\nself.instance_group = self.build_instance_group()\nself.instance_migration_handlers = []\nself.migration_status = MigrationStatus(0)",
"instance_group_helper = InstanceGroupHelper(self.compute, self.project, self.instance_group_name, self.region, self.zone... | <|body_start_0|>
super(UnmanagedInstanceGroupMigration, self).__init__()
self.instance_group = self.build_instance_group()
self.instance_migration_handlers = []
self.migration_status = MigrationStatus(0)
<|end_body_0|>
<|body_start_1|>
instance_group_helper = InstanceGroupHelper... | UnmanagedInstanceGroupMigration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_36k_train_013957 | 6,427 | permissive | [
{
"docstring": "Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetwork_name: target subnetwork preserve_external_ip: whether to preserve instances' external IPs zone: zone of a zonal instance group region: region of regio... | 4 | stack_v2_sparse_classes_30k_train_021178 | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | Implement the Python class `UnmanagedInstanceGroupMigration` described below.
Class description:
Implement the UnmanagedInstanceGroupMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initia... | 1132e44d696ab9da4d1079ebc3d32ed4382cdc28 | <|skeleton|>
class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnmanagedInstanceGroupMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subne... | the_stack_v2_python_sparse | vm_network_migration/handlers/instance_group_migration/unmanaged_instance_group_migration.py | googleinterns/vm-network-migration | train | 1 | |
626f13e024481f7df32207f8483a6a8bd566bcc7 | [
"if H <= len(piles):\n return max(piles)\n\ndef is_affordable(k):\n return sum(((p - 1) // k + 1 for p in piles)) <= H\nlow, high = (1, max(piles))\nwhile low < high:\n mid = low + (high - low) // 2\n if is_affordable(mid):\n high = mid\n else:\n low = mid + 1\nreturn low",
"if H <= l... | <|body_start_0|>
if H <= len(piles):
return max(piles)
def is_affordable(k):
return sum(((p - 1) // k + 1 for p in piles)) <= H
low, high = (1, max(piles))
while low < high:
mid = low + (high - low) // 2
if is_affordable(mid):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
<|body_0|>
def minEatingSpeedFailed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式... | stack_v2_sparse_classes_36k_train_013958 | 1,510 | no_license | [
{
"docstring": ":type piles: List[int] :type H: int :rtype: int 典型的type 2",
"name": "minEatingSpeed",
"signature": "def minEatingSpeed(self, piles, H)"
},
{
"docstring": ":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式 最後外面回傳 low",
"name"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 典型的type 2
- def minEatingSpeedFailed(self, piles, H): :type piles: List[int] :type H: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 典型的type 2
- def minEatingSpeedFailed(self, piles, H): :type piles: List[int] :type H: int :rty... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
<|body_0|>
def minEatingSpeedFailed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 我的版本,多做了 sort 但其實沒啥用 然後這個不是 type 2 type 2 不會有 == 的條件式... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 典型的type 2"""
if H <= len(piles):
return max(piles)
def is_affordable(k):
return sum(((p - 1) // k + 1 for p in piles)) <= H
low, high = (1, max(piles))
... | the_stack_v2_python_sparse | cs_notes/binary_search/koko_eating_bananas.py | hwc1824/LeetCodeSolution | train | 0 | |
52d78c7087c4575bc523b278c612b6890cef622d | [
"if head is None:\n return None\nnext_node = None\nwhile head is not None:\n tmp = head.next\n head.next = next_node\n next_node = head\n head = tmp\nreturn next_node",
"if head is None:\n return None\ndummy_node = ListNode(0)\ndummy_node.next = head\nwhile head.next is not None:\n tmp = head... | <|body_start_0|>
if head is None:
return None
next_node = None
while head is not None:
tmp = head.next
head.next = next_node
next_node = head
head = tmp
return next_node
<|end_body_0|>
<|body_start_1|>
if head is None:
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList2(self, head):
""":type head: ListNode :rtype: ListNode [1, 2, 3, 4] x -> 1 x -> 2 -> 1"""
<|body_1|>
def reverseList(self, head):
""":t... | stack_v2_sparse_classes_36k_train_013959 | 1,455 | permissive | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList1",
"signature": "def reverseList1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode [1, 2, 3, 4] x -> 1 x -> 2 -> 1",
"name": "reverseList2",
"signature": "def reverseList2(self, head)"
},
... | 3 | stack_v2_sparse_classes_30k_train_015779 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): :type head: ListNode :rtype: ListNode
- def reverseList2(self, head): :type head: ListNode :rtype: ListNode [1, 2, 3, 4] x -> 1 x -> 2 -> 1
- def re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head): :type head: ListNode :rtype: ListNode
- def reverseList2(self, head): :type head: ListNode :rtype: ListNode [1, 2, 3, 4] x -> 1 x -> 2 -> 1
- def re... | 57fe0de95881255393e0d6817e75bfae8f5744dc | <|skeleton|>
class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseList2(self, head):
""":type head: ListNode :rtype: ListNode [1, 2, 3, 4] x -> 1 x -> 2 -> 1"""
<|body_1|>
def reverseList(self, head):
""":t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList1(self, head):
""":type head: ListNode :rtype: ListNode"""
if head is None:
return None
next_node = None
while head is not None:
tmp = head.next
head.next = next_node
next_node = head
head = tm... | the_stack_v2_python_sparse | 0201-0250/0206-ReverseLinkedList/ReverseLinkedList.py | Sun-Zhen/leetcode | train | 0 | |
032505289b688c7a1c1558d4c5e43acf538f7c86 | [
"if isinstance(vgg_file_paths, str):\n vgg_file_paths = [vgg_file_paths]\nself.vgg_file_paths = vgg_file_paths\n\"Paths to vgg json files, e.g. 'C:/vgg.json\"\nself.silent = True\n'Suppress console messages'\nsuper().__init__(*args, **kwargs)",
"for vgg_file in self.vgg_file_paths:\n try:\n _vgg.load... | <|body_start_0|>
if isinstance(vgg_file_paths, str):
vgg_file_paths = [vgg_file_paths]
self.vgg_file_paths = vgg_file_paths
"Paths to vgg json files, e.g. 'C:/vgg.json"
self.silent = True
'Suppress console messages'
super().__init__(*args, **kwargs)
<|end_body... | Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpipes.filters, passed as filters=... transforms: Keyword argument containing l... | VGGImages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGGImages:
"""Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpipes.filters, passed as filters=... tran... | stack_v2_sparse_classes_36k_train_013960 | 47,799 | no_license | [
{
"docstring": "(str|list, list|None, dict|None) -> void",
"name": "__init__",
"signature": "def __init__(self, vgg_file_paths, *args, **kwargs)"
},
{
"docstring": "(bool, int, dict|None) -> ndarray|None, str, dict Generate images and paths, dict will be empty. file_attr_match: a dictionary whic... | 2 | null | Implement the Python class `VGGImages` described below.
Class description:
Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpi... | Implement the Python class `VGGImages` described below.
Class description:
Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpi... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class VGGImages:
"""Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpipes.filters, passed as filters=... tran... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGGImages:
"""Generate images only specified in a VGG file. This does not generate ROIs. vgg_file_paths: Full paths to vgg files, e.g. 'c:/vgg.json' ['c:/vgg.json','c:/vgg_other.json'] filters: Keyword argument containing a list of filter function from imgpipes.filters, passed as filters=... transforms: Keywo... | the_stack_v2_python_sparse | opencvlib/imgpipes/generators.py | gmonkman/python | train | 0 |
9c597c7e37b7613fd90c3c3371f6f05a696fc50d | [
"def countLeft(node):\n count = 0\n if node.left:\n nodes = [node.left]\n while nodes:\n cur = nodes.pop()\n count += 1\n if cur.left:\n nodes.append(cur.left)\n if cur.right:\n nodes.append(cur.right)\n return count\nl... | <|body_start_0|>
def countLeft(node):
count = 0
if node.left:
nodes = [node.left]
while nodes:
cur = nodes.pop()
count += 1
if cur.left:
nodes.append(cur.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root, k):
""":type root: TreeNode :type k: int :rtype: int"""
<|body_0|>
def kthSmallest2(self, root, k):
""":type root: TreeNode :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def countLeft(... | stack_v2_sparse_classes_36k_train_013961 | 1,708 | no_license | [
{
"docstring": ":type root: TreeNode :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root, k)"
},
{
"docstring": ":type root: TreeNode :type k: int :rtype: int",
"name": "kthSmallest2",
"signature": "def kthSmallest2(self, root, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root, k): :type root: TreeNode :type k: int :rtype: int
- def kthSmallest2(self, root, k): :type root: TreeNode :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root, k): :type root: TreeNode :type k: int :rtype: int
- def kthSmallest2(self, root, k): :type root: TreeNode :type k: int :rtype: int
<|skeleton|>
class... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def kthSmallest(self, root, k):
""":type root: TreeNode :type k: int :rtype: int"""
<|body_0|>
def kthSmallest2(self, root, k):
""":type root: TreeNode :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, root, k):
""":type root: TreeNode :type k: int :rtype: int"""
def countLeft(node):
count = 0
if node.left:
nodes = [node.left]
while nodes:
cur = nodes.pop()
count +=... | the_stack_v2_python_sparse | 230. Kth Smallest Element in a BST/ksmall.py | Macielyoung/LeetCode | train | 1 | |
7d36fe5f8d3b3968cb22a90d86638ad74b98d016 | [
"if not index_number:\n raise ValueError(_('The Index number must be set'))\nemail = self.normalize_email(extra_fields.get('email'))\nuser = self.model(index_number=index_number, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.se... | <|body_start_0|>
if not index_number:
raise ValueError(_('The Index number must be set'))
email = self.normalize_email(extra_fields.get('email'))
user = self.model(index_number=index_number, **extra_fields)
user.set_password(password)
user.save()
return user
<... | Custom user model manager where index_number is the unique identifiers for authentication instead of usernames. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where index_number is the unique identifiers for authentication instead of usernames."""
def create_user(self, index_number, password, **extra_fields):
"""Create and save a User with the given index_number and password."""
<|bod... | stack_v2_sparse_classes_36k_train_013962 | 2,974 | no_license | [
{
"docstring": "Create and save a User with the given index_number and password.",
"name": "create_user",
"signature": "def create_user(self, index_number, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given index_number and password.",
"name": "create_su... | 2 | stack_v2_sparse_classes_30k_train_010918 | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where index_number is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, index_number, password, **extra_fields): Create and save a User w... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where index_number is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, index_number, password, **extra_fields): Create and save a User w... | fbde094fe7a9e5539c964276b7ca8ef7cfccb513 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where index_number is the unique identifiers for authentication instead of usernames."""
def create_user(self, index_number, password, **extra_fields):
"""Create and save a User with the given index_number and password."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
"""Custom user model manager where index_number is the unique identifiers for authentication instead of usernames."""
def create_user(self, index_number, password, **extra_fields):
"""Create and save a User with the given index_number and password."""
if not index_numbe... | the_stack_v2_python_sparse | account/models.py | akwasidennis/students_activities | train | 0 |
6c1b57c9b3387e879699050202c6fb6b02662782 | [
"sys.stdout.write('\\nDownloading the repository of soletta...')\nsys.stdout.flush()\nsoletta_url = 'https://github.com/solettaproject/soletta.git'\nget_test_module_repo(soletta_url, 'soletta')\nsys.stdout.write('\\nCopying necessary files to target device...')\nsys.stdout.flush()\nbinding = 'i2c'\ncopy_test_files(... | <|body_start_0|>
sys.stdout.write('\nDownloading the repository of soletta...')
sys.stdout.flush()
soletta_url = 'https://github.com/solettaproject/soletta.git'
get_test_module_repo(soletta_url, 'soletta')
sys.stdout.write('\nCopying necessary files to target device...')
... | @class solettai2cApiTest Update suite.js for testing | solettai2cApiTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
<|body_0|>
def test_sol_i2c_api(self):
"""Execute the soletta upstream test cases. @fn test_sol_... | stack_v2_sparse_classes_36k_train_013963 | 2,887 | permissive | [
{
"docstring": "Copy all files related to testing to device @fn setup @param self",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Execute the soletta upstream test cases. @fn test_sol_platform_service_api @param self",
"name": "test_sol_i2c_api",
"signature": "def te... | 3 | stack_v2_sparse_classes_30k_val_000213 | Implement the Python class `solettai2cApiTest` described below.
Class description:
@class solettai2cApiTest Update suite.js for testing
Method signatures and docstrings:
- def setUp(self): Copy all files related to testing to device @fn setup @param self
- def test_sol_i2c_api(self): Execute the soletta upstream test... | Implement the Python class `solettai2cApiTest` described below.
Class description:
@class solettai2cApiTest Update suite.js for testing
Method signatures and docstrings:
- def setUp(self): Copy all files related to testing to device @fn setup @param self
- def test_sol_i2c_api(self): Execute the soletta upstream test... | e7f0006b7549907671be82a3b1f6b743217b1a90 | <|skeleton|>
class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
<|body_0|>
def test_sol_i2c_api(self):
"""Execute the soletta upstream test cases. @fn test_sol_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
sys.stdout.write('\nDownloading the repository of soletta...')
sys.stdout.flush()
soletta_url = 'https://g... | the_stack_v2_python_sparse | lib/oeqa/runtime/nodejs/soletta_i2c_api_upstream.py | ostroproject/meta-iotqa | train | 1 |
a6060b88ff1e3462eb3798a40fc36c6d73cfc12e | [
"payload = {'name': name, 'billing_email': billing_email, 'admin_email': admin_email, 'plan_id': plan_id}\nr = self.request('post', '{}/{}'.format(ADMIN_RESOURCE_URL, ORG_RESOURCE_URL), payload=payload)\nself.check_and_raise(r)",
"payload = {'cloud_provider': 'GCP', 'org_name': org_name, 'cluster_name': cluster_n... | <|body_start_0|>
payload = {'name': name, 'billing_email': billing_email, 'admin_email': admin_email, 'plan_id': plan_id}
r = self.request('post', '{}/{}'.format(ADMIN_RESOURCE_URL, ORG_RESOURCE_URL), payload=payload)
self.check_and_raise(r)
<|end_body_0|>
<|body_start_1|>
payload = {'c... | AdminClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminClient:
def create_org(self, name, billing_email, admin_email, plan_id=0):
"""Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 characters) billing_email -- billing_email of the new org admin_email -- email for first admin user of org ... | stack_v2_sparse_classes_36k_train_013964 | 5,249 | no_license | [
{
"docstring": "Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 characters) billing_email -- billing_email of the new org admin_email -- email for first admin user of org plan_id (optional) -- id of plan for org; default plan has ID 0",
"name": "create_org",... | 6 | null | Implement the Python class `AdminClient` described below.
Class description:
Implement the AdminClient class.
Method signatures and docstrings:
- def create_org(self, name, billing_email, admin_email, plan_id=0): Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 charact... | Implement the Python class `AdminClient` described below.
Class description:
Implement the AdminClient class.
Method signatures and docstrings:
- def create_org(self, name, billing_email, admin_email, plan_id=0): Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 charact... | 3aa64414c47534534bc6063185e3e6692a97e8a5 | <|skeleton|>
class AdminClient:
def create_org(self, name, billing_email, admin_email, plan_id=0):
"""Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 characters) billing_email -- billing_email of the new org admin_email -- email for first admin user of org ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminClient:
def create_org(self, name, billing_email, admin_email, plan_id=0):
"""Create a new org at the server Keyword arguments: name -- name of the new org (must be at least 4 characters) billing_email -- billing_email of the new org admin_email -- email for first admin user of org plan_id (optio... | the_stack_v2_python_sparse | env/Lib/site-packages/spell/api/admin_client.py | Kendubu1/NLP-Flask-Website | train | 0 | |
213540831ee82252ddb77e8b42e3cce542a13f3a | [
"parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')\nparser.add_argument('--radon-show-closures', default=False, action='store_true', help='Increase complexity on closures.')\ntry:\n parser.add_argument('--max-complexity', default=10, type=int, help='... | <|body_start_0|>
parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')
parser.add_argument('--radon-show-closures', default=False, action='store_true', help='Increase complexity on closures.')
try:
parser.add_argument('--max-... | Radon runner. | Linter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Check code with Radon."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser.add_argum... | stack_v2_sparse_classes_36k_train_013965 | 2,192 | permissive | [
{
"docstring": "Add --max-complexity option.",
"name": "add_args",
"signature": "def add_args(cls, parser: ArgumentParser)"
},
{
"docstring": "Check code with Radon.",
"name": "run_check",
"signature": "def run_check(self, ctx: RunContext)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010549 | Implement the Python class `Linter` described below.
Class description:
Radon runner.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Check code with Radon. | Implement the Python class `Linter` described below.
Class description:
Radon runner.
Method signatures and docstrings:
- def add_args(cls, parser: ArgumentParser): Add --max-complexity option.
- def run_check(self, ctx: RunContext): Check code with Radon.
<|skeleton|>
class Linter:
"""Radon runner."""
def ... | 53ad214de0aa9534e59bcd5f97d9d723d16cfdb8 | <|skeleton|>
class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
<|body_0|>
def run_check(self, ctx: RunContext):
"""Check code with Radon."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linter:
"""Radon runner."""
def add_args(cls, parser: ArgumentParser):
"""Add --max-complexity option."""
parser.add_argument('--radon-no-assert', default=False, action='store_true', help='Ignore `assert` statements.')
parser.add_argument('--radon-show-closures', default=False, ac... | the_stack_v2_python_sparse | pylama/lint/pylama_radon.py | klen/pylama | train | 1,022 |
15f2e9e902c8692cc303f2a4144aa6b7ed59b34c | [
"EasyFrame.__init__(self, 'Check Button Demo')\nself.firstCB = self.addCheckbutton(text='First', row=0, column=0, command=self.first)\nself.secondCB = self.addCheckbutton(text='Second', row=1, column=0, command=self.second)",
"if self.firstCB.isChecked():\n message = 'First has been checked'\nelse:\n messag... | <|body_start_0|>
EasyFrame.__init__(self, 'Check Button Demo')
self.firstCB = self.addCheckbutton(text='First', row=0, column=0, command=self.first)
self.secondCB = self.addCheckbutton(text='Second', row=1, column=0, command=self.second)
<|end_body_0|>
<|body_start_1|>
if self.firstCB.i... | When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment. | CheckbuttonDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckbuttonDemo:
"""When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def first(self):
"""Display a message ... | stack_v2_sparse_classes_36k_train_013966 | 1,593 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display a message box with the state of the check button.",
"name": "first",
"signature": "def first(self)"
},
{
"docstring": "Display a message box with the... | 3 | null | Implement the Python class `CheckbuttonDemo` described below.
Class description:
When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def first(self... | Implement the Python class `CheckbuttonDemo` described below.
Class description:
When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def first(self... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class CheckbuttonDemo:
"""When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def first(self):
"""Display a message ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckbuttonDemo:
"""When the display button is pressed, shows the label of the selected radio button. The button group has a default vertical alignment."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, 'Check Button Demo')
self.firstCB = self.a... | the_stack_v2_python_sparse | gui/breezy/checkbuttondemo.py | lforet/robomow | train | 11 |
ab24d41ec794daaf1830290ca1617280290551a5 | [
"record = set()\nfor num in nums:\n if num in record:\n return True\n record.add(num)\nreturn False",
"dd = Counter(nums)\nif len(dd) > 0 and max(dd.values()) > 1:\n return True\nreturn False"
] | <|body_start_0|>
record = set()
for num in nums:
if num in record:
return True
record.add(num)
return False
<|end_body_0|>
<|body_start_1|>
dd = Counter(nums)
if len(dd) > 0 and max(dd.values()) > 1:
return True
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
record = set()
for num... | stack_v2_sparse_classes_36k_train_013967 | 813 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "containsDuplicate",
"signature": "def containsDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "containsDuplicate1",
"signature": "def containsDuplicate1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): :type nums: List[int] :rtype: bool
- def containsDuplicate1(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): :type nums: List[int] :rtype: bool
- def containsDuplicate1(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
... | c55b0cfd2967a2221c27ed738e8de15034775945 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplicate1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsDuplicate(self, nums):
""":type nums: List[int] :rtype: bool"""
record = set()
for num in nums:
if num in record:
return True
record.add(num)
return False
def containsDuplicate1(self, nums):
""":type num... | the_stack_v2_python_sparse | PycharmProjects/leetcode/Find/containsDuplicate217.py | crystal30/DataStructure | train | 0 | |
19574eebed72aa9210e4eda1fdb1e799edda2400 | [
"if not isinstance(calls, list):\n raise ValueError('Calls must be a list.')\nself.stages = []\nif not calls:\n return\ntry:\n for _ in range(0, len(calls) + 1):\n fileno, path = tempfile.mkstemp(prefix='ContextedRunner-')\n os.close(fileno)\n os.chmod(path, stat.S_IRWXU)\n self... | <|body_start_0|>
if not isinstance(calls, list):
raise ValueError('Calls must be a list.')
self.stages = []
if not calls:
return
try:
for _ in range(0, len(calls) + 1):
fileno, path = tempfile.mkstemp(prefix='ContextedRunner-')
... | Run a series of programs that maintain the same PID and context by using exec to call each other. | ChainedExecRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChainedExecRunner:
"""Run a series of programs that maintain the same PID and context by using exec to call each other."""
def __init__(self, calls, argv=[], stdin=None):
"""The 'calls' argument is an array of dictionaries. Each dictionary contains an entry called "call," a string th... | stack_v2_sparse_classes_36k_train_013968 | 19,203 | permissive | [
{
"docstring": "The 'calls' argument is an array of dictionaries. Each dictionary contains an entry called \"call,\" a string that names the program to be run, and another called \"input\" which is an arbitrary blob of data (usually a dictionary) that can be converted into JSON and passed through to the program... | 2 | null | Implement the Python class `ChainedExecRunner` described below.
Class description:
Run a series of programs that maintain the same PID and context by using exec to call each other.
Method signatures and docstrings:
- def __init__(self, calls, argv=[], stdin=None): The 'calls' argument is an array of dictionaries. Eac... | Implement the Python class `ChainedExecRunner` described below.
Class description:
Run a series of programs that maintain the same PID and context by using exec to call each other.
Method signatures and docstrings:
- def __init__(self, calls, argv=[], stdin=None): The 'calls' argument is an array of dictionaries. Eac... | f6d04c0455e5be4d490df16ec1acb377f9025d9f | <|skeleton|>
class ChainedExecRunner:
"""Run a series of programs that maintain the same PID and context by using exec to call each other."""
def __init__(self, calls, argv=[], stdin=None):
"""The 'calls' argument is an array of dictionaries. Each dictionary contains an entry called "call," a string th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChainedExecRunner:
"""Run a series of programs that maintain the same PID and context by using exec to call each other."""
def __init__(self, calls, argv=[], stdin=None):
"""The 'calls' argument is an array of dictionaries. Each dictionary contains an entry called "call," a string that names the ... | the_stack_v2_python_sparse | python-pscheduler/pscheduler/pscheduler/program.py | perfsonar/pscheduler | train | 53 |
2de2527395f849e7b1bd3459b8ff611bb6f626d9 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"exp_s_prev = tf.expand_dims(s_prev, axis=1)\nscore = self.V(tf.nn.tanh(self.W(exp_s_prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(score, axis=1)\nco... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
exp_s_prev = tf.expand_dims(s_prev, axis=1)
score = self.V(tf.nn.tanh(self... | Self attention class | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self attention class"""
def __init__(self, units):
"""Class constructor. Args: units (int): the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Args: s_prev (tensor): of shape (batch, units)... | stack_v2_sparse_classes_36k_train_013969 | 1,429 | no_license | [
{
"docstring": "Class constructor. Args: units (int): the number of hidden units in the alignment model.",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "Args: s_prev (tensor): of shape (batch, units) containing the previous decoder hidden state. hidden_states (t... | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
Self attention class
Method signatures and docstrings:
- def __init__(self, units): Class constructor. Args: units (int): the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): Args: s_prev (tensor): of... | Implement the Python class `SelfAttention` described below.
Class description:
Self attention class
Method signatures and docstrings:
- def __init__(self, units): Class constructor. Args: units (int): the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): Args: s_prev (tensor): of... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class SelfAttention:
"""Self attention class"""
def __init__(self, units):
"""Class constructor. Args: units (int): the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Args: s_prev (tensor): of shape (batch, units)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self attention class"""
def __init__(self, units):
"""Class constructor. Args: units (int): the number of hidden units in the alignment model."""
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(un... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
46682b443a236631018e7fd5b11a67d01df03995 | [
"self.classifiers = classifiers\nself.named_classifiers = {key: value for key, value in _name_estimators(classifiers)}\nself.vote = vote\nself.weights = weights\nself.lablenc_ = LabelEncoder()\nself.classifiers_ = []\nself.classes_ = []",
"if self.vote not in ('probability', 'classlabel'):\n raise ValueError(\... | <|body_start_0|>
self.classifiers = classifiers
self.named_classifiers = {key: value for key, value in _name_estimators(classifiers)}
self.vote = vote
self.weights = weights
self.lablenc_ = LabelEncoder()
self.classifiers_ = []
self.classes_ = []
<|end_body_0|>
<... | A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class labels. Else if 'probability', the argmax of the s... | MajorityVoteClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityVoteClassifier:
"""A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class ... | stack_v2_sparse_classes_36k_train_013970 | 9,495 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, classifiers, vote='classlabel', weights=None)"
},
{
"docstring": "Fit classifiers. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Matrix of training samples. y : array-like,... | 5 | stack_v2_sparse_classes_30k_train_011604 | Implement the Python class `MajorityVoteClassifier` described below.
Class description:
A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the pred... | Implement the Python class `MajorityVoteClassifier` described below.
Class description:
A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the pred... | 957c49300ae59571eda590ddf13e7e092fdd96aa | <|skeleton|>
class MajorityVoteClassifier:
"""A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MajorityVoteClassifier:
"""A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class labels. Else ... | the_stack_v2_python_sparse | research/ml_analysis/dev_work/majority_vote.py | mccarvik/python_for_finance | train | 3 |
afdd744afea3fa4d376f7c58f3eb10658edffa0c | [
"if t1 and t2:\n t1.val += t2.val\n t1.left = self.mergeTrees(t1.left, t2.left)\n t1.right = self.mergeTrees(t1.right, t2.right)\n return t1\nelse:\n return t1 or t2",
"if not (t1 and t2):\n return t1 or t2\nroot = TreeNode(t1.val + t2.val)\nroot.left = self.mergeTreesNew(t1.left, t2.left)\nroot... | <|body_start_0|>
if t1 and t2:
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
else:
return t1 or t2
<|end_body_0|>
<|body_start_1|>
if not (t1 and t2):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTrees(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_0|>
def mergeTreesNew(self, t1, t2):
"""This Function will create a new Tree. :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_013971 | 1,063 | no_license | [
{
"docstring": ":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode",
"name": "mergeTrees",
"signature": "def mergeTrees(self, t1, t2)"
},
{
"docstring": "This Function will create a new Tree. :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode",
"name": "mergeTreesNew",
"signature... | 2 | stack_v2_sparse_classes_30k_train_020185 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode
- def mergeTreesNew(self, t1, t2): This Function will create a new Tree. :type t1: TreeNode :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1, t2): :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode
- def mergeTreesNew(self, t1, t2): This Function will create a new Tree. :type t1: TreeNode :... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def mergeTrees(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_0|>
def mergeTreesNew(self, t1, t2):
"""This Function will create a new Tree. :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTrees(self, t1, t2):
""":type t1: TreeNode :type t2: TreeNode :rtype: TreeNode"""
if t1 and t2:
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
else:... | the_stack_v2_python_sparse | cs_notes/tree/recursive/merged_two_binary_trees.py | hwc1824/LeetCodeSolution | train | 0 | |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\ncurrent_page = int(request.query_params.get('current_page', 1))\nrows_per_page = int(request.query_params.get('rows_per_page', 1000))\nserializer = CardSerializer(username, repo_base, request)\nres = serializer.describe_card(repo_name, card_name, current_page, rows_per_page,... | <|body_start_0|>
username = request.user.get_username()
current_page = int(request.query_params.get('current_page', 1))
rows_per_page = int(request.query_params.get('rows_per_page', 1000))
serializer = CardSerializer(username, repo_base, request)
res = serializer.describe_card(re... | Card | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Card:
def get(self, request, repo_base, repo_name, card_name, format=None):
"""See the query and query results of a single card. The results of the card query is exactly what the repo base owner would see. We've had trouble with getting the SWING demo framework to preview this correctly.... | stack_v2_sparse_classes_36k_train_013972 | 31,465 | permissive | [
{
"docstring": "See the query and query results of a single card. The results of the card query is exactly what the repo base owner would see. We've had trouble with getting the SWING demo framework to preview this correctly. Try going to a card url. i.e. /api/v1/repos/REPO_BASE/REPO_NAME/cards/CARD_NAME/?&curr... | 3 | stack_v2_sparse_classes_30k_train_000811 | Implement the Python class `Card` described below.
Class description:
Implement the Card class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, card_name, format=None): See the query and query results of a single card. The results of the card query is exactly what the repo base owner ... | Implement the Python class `Card` described below.
Class description:
Implement the Card class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, card_name, format=None): See the query and query results of a single card. The results of the card query is exactly what the repo base owner ... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Card:
def get(self, request, repo_base, repo_name, card_name, format=None):
"""See the query and query results of a single card. The results of the card query is exactly what the repo base owner would see. We've had trouble with getting the SWING demo framework to preview this correctly.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Card:
def get(self, request, repo_base, repo_name, card_name, format=None):
"""See the query and query results of a single card. The results of the card query is exactly what the repo base owner would see. We've had trouble with getting the SWING demo framework to preview this correctly. Try going to ... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
fffee148c2e7f9b57a7c47ad301924b0cc2eef2d | [
"uid = self.env.user.id\nemp = self.env['hr.employee'].sudo().search([('user_id', '=', uid)])\nif emp:\n url = self.env['ali.dindin.system.conf'].search([('key', '=', 'get_user_blackboard')]).value\n token = self.env['ali.dindin.system.conf'].search([('key', '=', 'token')]).value\n data = {'userid': emp[0]... | <|body_start_0|>
uid = self.env.user.id
emp = self.env['hr.employee'].sudo().search([('user_id', '=', uid)])
if emp:
url = self.env['ali.dindin.system.conf'].search([('key', '=', 'get_user_blackboard')]).value
token = self.env['ali.dindin.system.conf'].search([('key', '='... | DinDinBlackboard | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinDinBlackboard:
def get_blackboard_by_user(self):
"""根据当前用户获取公告信息 :return:"""
<|body_0|>
def get_update_information(self):
"""获取更新公告信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
uid = self.env.user.id
emp = self.env['hr.emplo... | stack_v2_sparse_classes_36k_train_013973 | 2,400 | permissive | [
{
"docstring": "根据当前用户获取公告信息 :return:",
"name": "get_blackboard_by_user",
"signature": "def get_blackboard_by_user(self)"
},
{
"docstring": "获取更新公告信息 :return:",
"name": "get_update_information",
"signature": "def get_update_information(self)"
}
] | 2 | null | Implement the Python class `DinDinBlackboard` described below.
Class description:
Implement the DinDinBlackboard class.
Method signatures and docstrings:
- def get_blackboard_by_user(self): 根据当前用户获取公告信息 :return:
- def get_update_information(self): 获取更新公告信息 :return: | Implement the Python class `DinDinBlackboard` described below.
Class description:
Implement the DinDinBlackboard class.
Method signatures and docstrings:
- def get_blackboard_by_user(self): 根据当前用户获取公告信息 :return:
- def get_update_information(self): 获取更新公告信息 :return:
<|skeleton|>
class DinDinBlackboard:
def get_b... | deaf38151d022a621096e84c8495b1a51265a991 | <|skeleton|>
class DinDinBlackboard:
def get_blackboard_by_user(self):
"""根据当前用户获取公告信息 :return:"""
<|body_0|>
def get_update_information(self):
"""获取更新公告信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DinDinBlackboard:
def get_blackboard_by_user(self):
"""根据当前用户获取公告信息 :return:"""
uid = self.env.user.id
emp = self.env['hr.employee'].sudo().search([('user_id', '=', uid)])
if emp:
url = self.env['ali.dindin.system.conf'].search([('key', '=', 'get_user_blackboard')])... | the_stack_v2_python_sparse | dindin_dashboard/models/blackboard.py | 007gzs/odooDingDing | train | 2 | |
69d4e6d61421f973d9a8e275417f3fad82825188 | [
"self.readm_batchsize = readm_batchsize\nself.cooccur_batchsize = readm_batchsize * batchsize_ratio\nself.batchsize_ratio = batchsize_ratio\nself.outcome = outcome\nself.cooccur_df = cooccur_df\nself.readm_df = readm_df\nself.shuffle = shuffle\nself.__scaling_factor = scaling_factor\nself.__count_cap = count_cap\ns... | <|body_start_0|>
self.readm_batchsize = readm_batchsize
self.cooccur_batchsize = readm_batchsize * batchsize_ratio
self.batchsize_ratio = batchsize_ratio
self.outcome = outcome
self.cooccur_df = cooccur_df
self.readm_df = readm_df
self.shuffle = shuffle
se... | Generates data from two datasets | DoubleBatchGenerator | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubleBatchGenerator:
"""Generates data from two datasets"""
def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, count_cap=20):
"""Initialization Here coocur_df and readm_df need to have integer ind... | stack_v2_sparse_classes_36k_train_013974 | 3,175 | permissive | [
{
"docstring": "Initialization Here coocur_df and readm_df need to have integer index from 0, i.e. they need to reset_index()",
"name": "__init__",
"signature": "def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, coun... | 4 | stack_v2_sparse_classes_30k_train_019184 | Implement the Python class `DoubleBatchGenerator` described below.
Class description:
Generates data from two datasets
Method signatures and docstrings:
- def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, count_cap=20): Initializa... | Implement the Python class `DoubleBatchGenerator` described below.
Class description:
Generates data from two datasets
Method signatures and docstrings:
- def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, count_cap=20): Initializa... | 09e365614b8409e54aaad53d397552bf4227e95f | <|skeleton|>
class DoubleBatchGenerator:
"""Generates data from two datasets"""
def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, count_cap=20):
"""Initialization Here coocur_df and readm_df need to have integer ind... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoubleBatchGenerator:
"""Generates data from two datasets"""
def __init__(self, cooccur_df, readm_df, readm_batchsize=512, batchsize_ratio=16, outcome='MOT_1year', shuffle=True, scaling_factor=0.75, count_cap=20):
"""Initialization Here coocur_df and readm_df need to have integer index from 0, i.... | the_stack_v2_python_sparse | Wenyi/hypertune/doublebatch.py | bnallamo/Readmissions-Deep-Learning-Project-PLOS-One | train | 0 |
1336321b9fc69d414f34bc67a20137133774429b | [
"boot_url = 'http://weixin.sogou.com/weixin'\ntask_id = pop_task(self.name)\nif not task_id:\n print('%s task is empty' % self.name)\n return\nprint('%s task id: %s' % (self.name, task_id))\ntask_item = get_item(FetchTask, task_id)\ncookies_id, cookies = get_cookies(self.name)\nurl_params = {'type': 1, 'query... | <|body_start_0|>
boot_url = 'http://weixin.sogou.com/weixin'
task_id = pop_task(self.name)
if not task_id:
print('%s task is empty' % self.name)
return
print('%s task id: %s' % (self.name, task_id))
task_item = get_item(FetchTask, task_id)
cookies_... | 微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件 | WeixinSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeixinSpider:
"""微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件"""
def start_requests(self):
"""入口准备 :return:"""
<|body_0|>
def parse_article_search_list(self, response):
"""解析微信文章 搜索列表页面 (废弃) :param response: :return:"""
<|body_1|>
def parse_account_s... | stack_v2_sparse_classes_36k_train_013975 | 6,585 | permissive | [
{
"docstring": "入口准备 :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "解析微信文章 搜索列表页面 (废弃) :param response: :return:",
"name": "parse_article_search_list",
"signature": "def parse_article_search_list(self, response)"
},
{
"docstring": ... | 5 | null | Implement the Python class `WeixinSpider` described below.
Class description:
微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件
Method signatures and docstrings:
- def start_requests(self): 入口准备 :return:
- def parse_article_search_list(self, response): 解析微信文章 搜索列表页面 (废弃) :param response: :return:
- def parse_account_searc... | Implement the Python class `WeixinSpider` described below.
Class description:
微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件
Method signatures and docstrings:
- def start_requests(self): 入口准备 :return:
- def parse_article_search_list(self, response): 解析微信文章 搜索列表页面 (废弃) :param response: :return:
- def parse_account_searc... | 9e29525a8bcb2310fca3bb4f9ca4b99b39ecfc9c | <|skeleton|>
class WeixinSpider:
"""微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件"""
def start_requests(self):
"""入口准备 :return:"""
<|body_0|>
def parse_article_search_list(self, response):
"""解析微信文章 搜索列表页面 (废弃) :param response: :return:"""
<|body_1|>
def parse_account_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeixinSpider:
"""微信公众号蜘蛛 因微信公众号详情链接是带有效期签名的动态链接, 故无法使用请求去重中间件"""
def start_requests(self):
"""入口准备 :return:"""
boot_url = 'http://weixin.sogou.com/weixin'
task_id = pop_task(self.name)
if not task_id:
print('%s task is empty' % self.name)
return
... | the_stack_v2_python_sparse | news/spiders/weixin.py | zhanghe06/news_spider | train | 226 |
9eeb378858e67d613479fa41aed968acb7d98a55 | [
"student = g.user\napply = StayApplyModel.objects(student=student).first()\nreturn self.unicode_safe_json_response({'value': apply.value}, 200)",
"student = g.user\nnow = datetime.now()\nif current_app.testing or (now.weekday() == 6 and now.time() > time(20, 30)) or 0 <= now.weekday() < 3 or (now.weekday() == 3 a... | <|body_start_0|>
student = g.user
apply = StayApplyModel.objects(student=student).first()
return self.unicode_safe_json_response({'value': apply.value}, 200)
<|end_body_0|>
<|body_start_1|>
student = g.user
now = datetime.now()
if current_app.testing or (now.weekday() ==... | Stay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stay:
def get(self):
"""잔류신청 정보 조회"""
<|body_0|>
def post(self):
"""잔류신청"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
student = g.user
apply = StayApplyModel.objects(student=student).first()
return self.unicode_safe_json_response(... | stack_v2_sparse_classes_36k_train_013976 | 1,418 | permissive | [
{
"docstring": "잔류신청 정보 조회",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "잔류신청",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002115 | Implement the Python class `Stay` described below.
Class description:
Implement the Stay class.
Method signatures and docstrings:
- def get(self): 잔류신청 정보 조회
- def post(self): 잔류신청 | Implement the Python class `Stay` described below.
Class description:
Implement the Stay class.
Method signatures and docstrings:
- def get(self): 잔류신청 정보 조회
- def post(self): 잔류신청
<|skeleton|>
class Stay:
def get(self):
"""잔류신청 정보 조회"""
<|body_0|>
def post(self):
"""잔류신청"""
... | de585fe904a2bf15f9fc74219eae176151a0f8ca | <|skeleton|>
class Stay:
def get(self):
"""잔류신청 정보 조회"""
<|body_0|>
def post(self):
"""잔류신청"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stay:
def get(self):
"""잔류신청 정보 조회"""
student = g.user
apply = StayApplyModel.objects(student=student).first()
return self.unicode_safe_json_response({'value': apply.value}, 200)
def post(self):
"""잔류신청"""
student = g.user
now = datetime.now()
... | the_stack_v2_python_sparse | Server/app/views/v1/student/apply/stay.py | miraedbswo/DMS-Backend | train | 2 | |
a6cdcafd3e4722178945ed9a3c1107d0397ea8ad | [
"prefix = set(dict)\nwordList = sentence.split()\nfor i in range(len(wordList)):\n word = wordList[i]\n for j in range(len(word)):\n partialWord = word[:j]\n if partialWord in prefix:\n wordList[i] = partialWord\n break\nreturn ' '.join(wordList)",
"def replace(word):\n ... | <|body_start_0|>
prefix = set(dict)
wordList = sentence.split()
for i in range(len(wordList)):
word = wordList[i]
for j in range(len(word)):
partialWord = word[:j]
if partialWord in prefix:
wordList[i] = partialWord
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def replaceWords(self, dict, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_0|>
def replaceWordsCache(self, dict, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_013977 | 2,191 | no_license | [
{
"docstring": ":type dict: List[str] :type sentence: str :rtype: str",
"name": "replaceWords",
"signature": "def replaceWords(self, dict, sentence)"
},
{
"docstring": ":type dict: List[str] :type sentence: str :rtype: str",
"name": "replaceWordsCache",
"signature": "def replaceWordsCach... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def replaceWords(self, dict, sentence): :type dict: List[str] :type sentence: str :rtype: str
- def replaceWordsCache(self, dict, sentence): :type dict: List[str] :type sentence:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def replaceWords(self, dict, sentence): :type dict: List[str] :type sentence: str :rtype: str
- def replaceWordsCache(self, dict, sentence): :type dict: List[str] :type sentence:... | d1666d44226274f13af25cf878cd63a24e1c5528 | <|skeleton|>
class Solution:
def replaceWords(self, dict, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_0|>
def replaceWordsCache(self, dict, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def replaceWords(self, dict, sentence):
""":type dict: List[str] :type sentence: str :rtype: str"""
prefix = set(dict)
wordList = sentence.split()
for i in range(len(wordList)):
word = wordList[i]
for j in range(len(word)):
part... | the_stack_v2_python_sparse | Trie/LeetCode648_ReplaceWords.py | rexhzhang/LeetCodeProbelms | train | 0 | |
ce19eec972183543148b9ab60222eb0a5357d071 | [
"if Answer.objects.filter(pk=kwargs['pk']).exists():\n ans = Answer.objects.get(pk=kwargs['pk'])\n if ans.user != self.request.user:\n return HttpResponseForbidden('Access Denied')\nelse:\n return HttpResponseForbidden('Access Denied')\nreturn super(EditAnswerView, self).get(*args, **kwargs)",
"in... | <|body_start_0|>
if Answer.objects.filter(pk=kwargs['pk']).exists():
ans = Answer.objects.get(pk=kwargs['pk'])
if ans.user != self.request.user:
return HttpResponseForbidden('Access Denied')
else:
return HttpResponseForbidden('Access Denied')
r... | Edit Question View | EditAnswerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditAnswerView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users answer"""
<|body_0|>
def form_valid(self, form):
"""Edit the Updated date of answer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if An... | stack_v2_sparse_classes_36k_train_013978 | 7,882 | no_license | [
{
"docstring": "user can't edit the other users answer",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Edit the Updated date of answer",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003133 | Implement the Python class `EditAnswerView` described below.
Class description:
Edit Question View
Method signatures and docstrings:
- def get(self, *args, **kwargs): user can't edit the other users answer
- def form_valid(self, form): Edit the Updated date of answer | Implement the Python class `EditAnswerView` described below.
Class description:
Edit Question View
Method signatures and docstrings:
- def get(self, *args, **kwargs): user can't edit the other users answer
- def form_valid(self, form): Edit the Updated date of answer
<|skeleton|>
class EditAnswerView:
"""Edit Qu... | d89a811c5c928921a6ffac9120fd1d8d14dd4ac6 | <|skeleton|>
class EditAnswerView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users answer"""
<|body_0|>
def form_valid(self, form):
"""Edit the Updated date of answer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditAnswerView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users answer"""
if Answer.objects.filter(pk=kwargs['pk']).exists():
ans = Answer.objects.get(pk=kwargs['pk'])
if ans.user != self.request.user:
ret... | the_stack_v2_python_sparse | forum/views.py | suman1oct/stack_overflow | train | 0 |
842008ecb8fd17b3f1189ffe2782722c8e3440c2 | [
"self.hass = hass\nself.config_entry: ConfigEntry = config_entry\nself.cam = cam\nsuper().__init__(self.hass, _LOGGER, name=f'{DOMAIN} {config_entry.data[CONF_HOST]}', update_interval=timedelta(seconds=10))",
"try:\n await self.cam.update()\nexcept PyDroidIPCamException as err:\n raise UpdateFailed(err) fro... | <|body_start_0|>
self.hass = hass
self.config_entry: ConfigEntry = config_entry
self.cam = cam
super().__init__(self.hass, _LOGGER, name=f'{DOMAIN} {config_entry.data[CONF_HOST]}', update_interval=timedelta(seconds=10))
<|end_body_0|>
<|body_start_1|>
try:
await self... | Coordinator class for the Android IP Webcam. | AndroidIPCamDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidIPCamDataUpdateCoordinator:
"""Coordinator class for the Android IP Webcam."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None:
"""Initialize the Android IP Webcam."""
<|body_0|>
async def _async_update_data(self) -> N... | stack_v2_sparse_classes_36k_train_013979 | 1,351 | permissive | [
{
"docstring": "Initialize the Android IP Webcam.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None"
},
{
"docstring": "Update Android IP Webcam entities.",
"name": "_async_update_data",
"signature": "async d... | 2 | stack_v2_sparse_classes_30k_test_000312 | Implement the Python class `AndroidIPCamDataUpdateCoordinator` described below.
Class description:
Coordinator class for the Android IP Webcam.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None: Initialize the Android IP Webcam.
- async d... | Implement the Python class `AndroidIPCamDataUpdateCoordinator` described below.
Class description:
Coordinator class for the Android IP Webcam.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None: Initialize the Android IP Webcam.
- async d... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AndroidIPCamDataUpdateCoordinator:
"""Coordinator class for the Android IP Webcam."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None:
"""Initialize the Android IP Webcam."""
<|body_0|>
async def _async_update_data(self) -> N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AndroidIPCamDataUpdateCoordinator:
"""Coordinator class for the Android IP Webcam."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, cam: PyDroidIPCam) -> None:
"""Initialize the Android IP Webcam."""
self.hass = hass
self.config_entry: ConfigEntry = config_ent... | the_stack_v2_python_sparse | homeassistant/components/android_ip_webcam/coordinator.py | home-assistant/core | train | 35,501 |
da0349db85ac46789de3ec695aed3e48b3fed137 | [
"self.central_cube, self.cube = set_up_cubes_for_process_tests()\nself.forecast_period = self.central_cube.coord('forecast_period').points[0]\nself.width = 1.0",
"plugin = TriangularWeightedBlendAcrossAdjacentPoints('forecast_period', self.forecast_period, 'hours', self.width)\ncentral_cube = plugin._find_central... | <|body_start_0|>
self.central_cube, self.cube = set_up_cubes_for_process_tests()
self.forecast_period = self.central_cube.coord('forecast_period').points[0]
self.width = 1.0
<|end_body_0|>
<|body_start_1|>
plugin = TriangularWeightedBlendAcrossAdjacentPoints('forecast_period', self.fore... | Test the _find_central_point. | Test__find_central_point | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__find_central_point:
"""Test the _find_central_point."""
def setUp(self):
"""Set up a test cubes."""
<|body_0|>
def test_central_point_available(self):
"""Test that the central point is available within the input cube."""
<|body_1|>
def test_cen... | stack_v2_sparse_classes_36k_train_013980 | 11,091 | permissive | [
{
"docstring": "Set up a test cubes.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the central point is available within the input cube.",
"name": "test_central_point_available",
"signature": "def test_central_point_available(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_007257 | Implement the Python class `Test__find_central_point` described below.
Class description:
Test the _find_central_point.
Method signatures and docstrings:
- def setUp(self): Set up a test cubes.
- def test_central_point_available(self): Test that the central point is available within the input cube.
- def test_central... | Implement the Python class `Test__find_central_point` described below.
Class description:
Test the _find_central_point.
Method signatures and docstrings:
- def setUp(self): Set up a test cubes.
- def test_central_point_available(self): Test that the central point is available within the input cube.
- def test_central... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__find_central_point:
"""Test the _find_central_point."""
def setUp(self):
"""Set up a test cubes."""
<|body_0|>
def test_central_point_available(self):
"""Test that the central point is available within the input cube."""
<|body_1|>
def test_cen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__find_central_point:
"""Test the _find_central_point."""
def setUp(self):
"""Set up a test cubes."""
self.central_cube, self.cube = set_up_cubes_for_process_tests()
self.forecast_period = self.central_cube.coord('forecast_period').points[0]
self.width = 1.0
def t... | the_stack_v2_python_sparse | improver_tests/blending/blend_across_adjacent_points/test_TriangularWeightedBlendAcrossAdjacentPoints.py | metoppv/improver | train | 101 |
d324e67eaae90d43573dfcbe087f529668e8f132 | [
"seen = set()\nfor i in range(len(arr)):\n sub_array_sum = 0\n sub_array = []\n for j in range(i, len(arr)):\n sub_array_sum += arr[j]\n sub_array.append(arr[j])\n if sub_array_sum == k and tuple(sub_array) not in seen:\n seen.add(tuple(sub_array))\nreturn len(seen)",
"sum... | <|body_start_0|>
seen = set()
for i in range(len(arr)):
sub_array_sum = 0
sub_array = []
for j in range(i, len(arr)):
sub_array_sum += arr[j]
sub_array.append(arr[j])
if sub_array_sum == k and tuple(sub_array) not in see... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def brute_force(self, arr: List[int], k: int) -> int:
"""Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)"""
<|body_0|>
def cumulative_sum(self, arr: List[int], k: int) -> int:
"""We can use the difference of cumulative sums. Cumulative sum... | stack_v2_sparse_classes_36k_train_013981 | 3,284 | no_license | [
{
"docstring": "Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)",
"name": "brute_force",
"signature": "def brute_force(self, arr: List[int], k: int) -> int"
},
{
"docstring": "We can use the difference of cumulative sums. Cumulative sums are often helpful when dealing with suba... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def brute_force(self, arr: List[int], k: int) -> int: Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)
- def cumulative_sum(self, arr: List[int], k: int) -> int:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def brute_force(self, arr: List[int], k: int) -> int: Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)
- def cumulative_sum(self, arr: List[int], k: int) -> int:... | c0d49423885832b616ae3c7cd58e8f24c17cfd4d | <|skeleton|>
class Solution:
def brute_force(self, arr: List[int], k: int) -> int:
"""Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)"""
<|body_0|>
def cumulative_sum(self, arr: List[int], k: int) -> int:
"""We can use the difference of cumulative sums. Cumulative sum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def brute_force(self, arr: List[int], k: int) -> int:
"""Check every subarray Complexity ---- Time : O(N^2) Space : O(N^2)"""
seen = set()
for i in range(len(arr)):
sub_array_sum = 0
sub_array = []
for j in range(i, len(arr)):
... | the_stack_v2_python_sparse | Arrays/sub_array_sum_k.py | miaviles/Data-Structures-Algorithms-Python | train | 0 | |
2c160e3d78b731a3acb332ccdd3af099038d4c85 | [
"if read_first:\n self.policy_1, self.i_epoch = pickle.load(open(path, 'rb'))\n print('Policy read from file. Trained for %i epochs.' % self.i_epoch)\nself.path = path\nself.i_epoch = 0\nself.policy_1 = TabularPolicy()",
"self.policy_2 = TabularPolicy()\nreturns = dict()\nfor num in range(int('1' + '0' * 9,... | <|body_start_0|>
if read_first:
self.policy_1, self.i_epoch = pickle.load(open(path, 'rb'))
print('Policy read from file. Trained for %i epochs.' % self.i_epoch)
self.path = path
self.i_epoch = 0
self.policy_1 = TabularPolicy()
<|end_body_0|>
<|body_start_1|>
... | TrainOneRound | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainOneRound:
def __init__(self, path, read_first=False):
"""Input: path: the path to save the policy read_first: if true, read from the path first"""
<|body_0|>
def MCPrediction(self, n_epoch):
"""MC prediction following Sutton Barto 5.1 Against rush opponent Input... | stack_v2_sparse_classes_36k_train_013982 | 2,243 | no_license | [
{
"docstring": "Input: path: the path to save the policy read_first: if true, read from the path first",
"name": "__init__",
"signature": "def __init__(self, path, read_first=False)"
},
{
"docstring": "MC prediction following Sutton Barto 5.1 Against rush opponent Input: n_epoch: the number of e... | 2 | stack_v2_sparse_classes_30k_train_001636 | Implement the Python class `TrainOneRound` described below.
Class description:
Implement the TrainOneRound class.
Method signatures and docstrings:
- def __init__(self, path, read_first=False): Input: path: the path to save the policy read_first: if true, read from the path first
- def MCPrediction(self, n_epoch): MC... | Implement the Python class `TrainOneRound` described below.
Class description:
Implement the TrainOneRound class.
Method signatures and docstrings:
- def __init__(self, path, read_first=False): Input: path: the path to save the policy read_first: if true, read from the path first
- def MCPrediction(self, n_epoch): MC... | 5831d4c1eaf21d41007eb6988f3c9885b55d13b2 | <|skeleton|>
class TrainOneRound:
def __init__(self, path, read_first=False):
"""Input: path: the path to save the policy read_first: if true, read from the path first"""
<|body_0|>
def MCPrediction(self, n_epoch):
"""MC prediction following Sutton Barto 5.1 Against rush opponent Input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainOneRound:
def __init__(self, path, read_first=False):
"""Input: path: the path to save the policy read_first: if true, read from the path first"""
if read_first:
self.policy_1, self.i_epoch = pickle.load(open(path, 'rb'))
print('Policy read from file. Trained for %... | the_stack_v2_python_sparse | ttt_train_mc_prediction.py | sw2703/rl_tictactoe | train | 0 | |
5f1fbb979033a14e2c58e2833ab1d2a1ccccc4aa | [
"inv = self.browse(cr, uid, id, context=context)\nres = super(account_invoice, self)._get_analytic_lines(cr, uid, id)\nfor r in res:\n r.update({'budget_confirm_id': inv.budget_confirm_id.id})\nreturn res",
"res = super(account_invoice, self).line_get_convert(cr, uid, line, part, date, context)\nres.update({'b... | <|body_start_0|>
inv = self.browse(cr, uid, id, context=context)
res = super(account_invoice, self)._get_analytic_lines(cr, uid, id)
for r in res:
r.update({'budget_confirm_id': inv.budget_confirm_id.id})
return res
<|end_body_0|>
<|body_start_1|>
res = super(account... | account_invoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_invoice:
def _get_analytic_lines(self, cr, uid, id, context=None):
"""Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated"""
<|body_0|>
def line_get_convert(self, cr, uid, line, part, date, context=None):
"""Add budge... | stack_v2_sparse_classes_36k_train_013983 | 6,435 | no_license | [
{
"docstring": "Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated",
"name": "_get_analytic_lines",
"signature": "def _get_analytic_lines(self, cr, uid, id, context=None)"
},
{
"docstring": "Add budget_confirm_id field to result dictionary @param part: ... | 2 | stack_v2_sparse_classes_30k_train_020048 | Implement the Python class `account_invoice` described below.
Class description:
Implement the account_invoice class.
Method signatures and docstrings:
- def _get_analytic_lines(self, cr, uid, id, context=None): Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated
- def line_g... | Implement the Python class `account_invoice` described below.
Class description:
Implement the account_invoice class.
Method signatures and docstrings:
- def _get_analytic_lines(self, cr, uid, id, context=None): Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated
- def line_g... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_invoice:
def _get_analytic_lines(self, cr, uid, id, context=None):
"""Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated"""
<|body_0|>
def line_get_convert(self, cr, uid, line, part, date, context=None):
"""Add budge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_invoice:
def _get_analytic_lines(self, cr, uid, id, context=None):
"""Add budget_confirm_id field to result dictionary. @return: dictionary of values to be updated"""
inv = self.browse(cr, uid, id, context=context)
res = super(account_invoice, self)._get_analytic_lines(cr, uid,... | the_stack_v2_python_sparse | v_7/Dongola/common/account_invoice_confirmation/invoice.py | musabahmed/baba | train | 0 | |
c79a10b3c2132e550167f541a77910564fdd7963 | [
"try:\n access_token = self.find_access_token()\n access_token = AccessToken(id=access_token.id, access_token=access_token, expires_in=expires_in, created_date=access_token.created_date, modified_date=datetime.datetime.utcnow())\n logger.info('Access Token updated : {}'.format(access_token.to_dict()))\nexc... | <|body_start_0|>
try:
access_token = self.find_access_token()
access_token = AccessToken(id=access_token.id, access_token=access_token, expires_in=expires_in, created_date=access_token.created_date, modified_date=datetime.datetime.utcnow())
logger.info('Access Token updated :... | AccessTokenController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessTokenController:
def add_access_token(self, access_token, expires_in):
""":param email: user email id :param access_token: master access token :param expires_in: time expires in :param created_date: token created date time :param modified_date: token modified date time :return: acc... | stack_v2_sparse_classes_36k_train_013984 | 2,143 | no_license | [
{
"docstring": ":param email: user email id :param access_token: master access token :param expires_in: time expires in :param created_date: token created date time :param modified_date: token modified date time :return: access token object",
"name": "add_access_token",
"signature": "def add_access_toke... | 2 | stack_v2_sparse_classes_30k_train_013676 | Implement the Python class `AccessTokenController` described below.
Class description:
Implement the AccessTokenController class.
Method signatures and docstrings:
- def add_access_token(self, access_token, expires_in): :param email: user email id :param access_token: master access token :param expires_in: time expir... | Implement the Python class `AccessTokenController` described below.
Class description:
Implement the AccessTokenController class.
Method signatures and docstrings:
- def add_access_token(self, access_token, expires_in): :param email: user email id :param access_token: master access token :param expires_in: time expir... | df03fc146bf86fd215fd078a5808f26e542f3144 | <|skeleton|>
class AccessTokenController:
def add_access_token(self, access_token, expires_in):
""":param email: user email id :param access_token: master access token :param expires_in: time expires in :param created_date: token created date time :param modified_date: token modified date time :return: acc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessTokenController:
def add_access_token(self, access_token, expires_in):
""":param email: user email id :param access_token: master access token :param expires_in: time expires in :param created_date: token created date time :param modified_date: token modified date time :return: access token obje... | the_stack_v2_python_sparse | database/connectMySQL/sqlAlchemyTest/access_token/controller.py | gol-danRuman/learn_python_basic | train | 0 | |
c336e6fedebb6933da3335d5303ef5256ba154b4 | [
"team = ProjectUsersAssociation.find_all_by_project_id(project_id)\ndata = TeamSchema().dump(team, many=True)\nuser = g.user\nfor team_member in data:\n team_member['isCurrentUser'] = team_member['userId'] == user.id\nreturn (jsonify({'team': data}), HTTPStatus.OK)",
"team_json = request.get_json()\ntry:\n ... | <|body_start_0|>
team = ProjectUsersAssociation.find_all_by_project_id(project_id)
data = TeamSchema().dump(team, many=True)
user = g.user
for team_member in data:
team_member['isCurrentUser'] = team_member['userId'] == user.id
return (jsonify({'team': data}), HTTPSta... | Resource for managing team. | TeamResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
<|body_0|>
def post(project_id):
"""Post a new team using the request body."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
team = ProjectUsersAssociation.find_... | stack_v2_sparse_classes_36k_train_013985 | 6,372 | permissive | [
{
"docstring": "Get team.",
"name": "get",
"signature": "def get(project_id)"
},
{
"docstring": "Post a new team using the request body.",
"name": "post",
"signature": "def post(project_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014244 | Implement the Python class `TeamResource` described below.
Class description:
Resource for managing team.
Method signatures and docstrings:
- def get(project_id): Get team.
- def post(project_id): Post a new team using the request body. | Implement the Python class `TeamResource` described below.
Class description:
Resource for managing team.
Method signatures and docstrings:
- def get(project_id): Get team.
- def post(project_id): Post a new team using the request body.
<|skeleton|>
class TeamResource:
"""Resource for managing team."""
def ... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
<|body_0|>
def post(project_id):
"""Post a new team using the request body."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamResource:
"""Resource for managing team."""
def get(project_id):
"""Get team."""
team = ProjectUsersAssociation.find_all_by_project_id(project_id)
data = TeamSchema().dump(team, many=True)
user = g.user
for team_member in data:
team_member['isCurren... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/resources/team.py | bcgov/BCSC-SS | train | 2 |
f5b9759b2171b993b8644f063ff8b762c92c6927 | [
"self.heap = nums\nself.k = k\nheapq.heapify(self.heap)\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelse:\n heapq.heappushpop(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.heap = nums
self.k = k
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
else:
heapq.heappushpop... | - time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, -val) for i in range(self.k): kLargest.append(heapq.heappop(self.heap)) res =... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
"""- time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, -val) for i in range(self.k): kLargest.... | stack_v2_sparse_classes_36k_train_013986 | 1,373 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
- time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, ... | Implement the Python class `KthLargest` described below.
Class description:
- time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, ... | 085d868ba0458fc8e6b5549aa00fa151c335fa7f | <|skeleton|>
class KthLargest:
"""- time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, -val) for i in range(self.k): kLargest.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
"""- time limit exceeded - Overkill, only need a heap for largest elements, rest not care def __init__(self, k, nums): self.heap = [-n for n in nums] self.k = k heapq.heapify(self.heap) def add(self, val): kLargest = [] heapq.heappush(self.heap, -val) for i in range(self.k): kLargest.append(heapq.... | the_stack_v2_python_sparse | 703-Kth_Largest_Element_in_A_Stream.py | chanyoonzhu/leetcode-python | train | 0 |
57580475ce1d52dc771dc3c9a1dfbf5e8ce72100 | [
"self.max_h = list()\nself.min_h = list()\nheapify(self.max_h)\nheapify(self.min_h)",
"heappush(self.min_h, num)\nheappush(self.max_h, -heappop(self.min_h))\nif len(self.max_h) > len(self.min_h):\n heappush(self.min_h, -heappop(self.max_h))",
"max_len = len(self.max_h)\nmin_len = len(self.min_h)\nif max_len ... | <|body_start_0|>
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
<|end_body_0|>
<|body_start_1|>
heappush(self.min_h, num)
heappush(self.max_h, -heappop(self.min_h))
if len(self.max_h) > len(self.min_h):
heappush(self.m... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_013987 | 2,010 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_007177 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | ce8b12735aa181a223eb3b8d6c6993cbafc2e467 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
def addNum(self, num):
""":type num: int :rtype: None"""
heappush(self.min_h, num)
h... | the_stack_v2_python_sparse | 295. 数据流的中位数.py | hanzhenlei767/leetcode | train | 3 | |
a8e25708c22db770bdc724f4c44a1a4bf29d263f | [
"json_dict = {'status': {'success': True}, 'result': payload}\njson_body = json.dumps(json_dict, cls=CustomJsonEncoder)\nreturn Response(body=json_body, status_code=status_code, headers={'Content-Type': 'application/json'})",
"json_dict = {'status': {'success': False, 'error_message': error_message}, 'result': pa... | <|body_start_0|>
json_dict = {'status': {'success': True}, 'result': payload}
json_body = json.dumps(json_dict, cls=CustomJsonEncoder)
return Response(body=json_body, status_code=status_code, headers={'Content-Type': 'application/json'})
<|end_body_0|>
<|body_start_1|>
json_dict = {'sta... | Responder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Responder:
def success(payload, status_code=200):
"""Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200) :return: Response"""
<|body_0|>
def error(status_code, error_message='', payload=No... | stack_v2_sparse_classes_36k_train_013988 | 1,456 | no_license | [
{
"docstring": "Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200) :return: Response",
"name": "success",
"signature": "def success(payload, status_code=200)"
},
{
"docstring": "Returns a Response denoting fa... | 2 | stack_v2_sparse_classes_30k_train_000524 | Implement the Python class `Responder` described below.
Class description:
Implement the Responder class.
Method signatures and docstrings:
- def success(payload, status_code=200): Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200... | Implement the Python class `Responder` described below.
Class description:
Implement the Responder class.
Method signatures and docstrings:
- def success(payload, status_code=200): Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200... | a3aaf5f23b7c270631f7dddab4ae8889e597e022 | <|skeleton|>
class Responder:
def success(payload, status_code=200):
"""Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200) :return: Response"""
<|body_0|>
def error(status_code, error_message='', payload=No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Responder:
def success(payload, status_code=200):
"""Returns a Response denoting success. :param payload: the response payload :param status_code: the http status code to return (default:200) :return: Response"""
json_dict = {'status': {'success': True}, 'result': payload}
json_body = ... | the_stack_v2_python_sparse | cov api/chalicelib/responses.py | KaisKermani/cov-app-nlp | train | 0 | |
12963e53967c2f14ecac20827a8dfa3bb780ccad | [
"if len(lists) == 0:\n return None\nelse:\n l = len(lists)\n while l - 1:\n cap = (l + 1) // 2\n for i in range(0, l // 2):\n lists[i] = self.mergeSort(lists[i], lists[i + cap])\n l = cap\n return lists[0]",
"if l1 == None and l2 == None:\n return None\nr = result = ... | <|body_start_0|>
if len(lists) == 0:
return None
else:
l = len(lists)
while l - 1:
cap = (l + 1) // 2
for i in range(0, l // 2):
lists[i] = self.mergeSort(lists[i], lists[i + cap])
l = cap
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeSort(self, l1, l2):
""":l1, l2: sorted lists :return: merged sorted listnode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(lists)... | stack_v2_sparse_classes_36k_train_013989 | 1,279 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":l1, l2: sorted lists :return: merged sorted listnode",
"name": "mergeSort",
"signature": "def mergeSort(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019933 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeSort(self, l1, l2): :l1, l2: sorted lists :return: merged sorted listnode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeSort(self, l1, l2): :l1, l2: sorted lists :return: merged sorted listnode
<|skeleton|>
clas... | 61e98983bcb4b4235b8c5863287b8b5f8e687c68 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeSort(self, l1, l2):
""":l1, l2: sorted lists :return: merged sorted listnode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
if len(lists) == 0:
return None
else:
l = len(lists)
while l - 1:
cap = (l + 1) // 2
for i in range(0, l // 2):
... | the_stack_v2_python_sparse | hard/Python/023MergekSortedLists.py | mancunian100/leetcode | train | 0 | |
09e4a149b0d9666a72c8df0d2fb541a6f659eb30 | [
"super(Redirect, self).__init__(trigger, element)\nself._log = logging.getLogger('agentml.parser.tags.redirect')\nwith open(os.path.join(self.trigger.agentml.script_path, 'schemas', 'tags', 'redirect.rng')) as file:\n self.schema = schema(file.read())",
"user = self.trigger.agentml.request_log.most_recent().us... | <|body_start_0|>
super(Redirect, self).__init__(trigger, element)
self._log = logging.getLogger('agentml.parser.tags.redirect')
with open(os.path.join(self.trigger.agentml.script_path, 'schemas', 'tags', 'redirect.rng')) as file:
self.schema = schema(file.read())
<|end_body_0|>
<|bo... | Redirect | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Redirect:
def __init__(self, trigger, element):
"""Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: The XML Element object :type element: etree._Element"""
<|body_0|>
def value(self):
... | stack_v2_sparse_classes_36k_train_013990 | 1,437 | permissive | [
{
"docstring": "Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: The XML Element object :type element: etree._Element",
"name": "__init__",
"signature": "def __init__(self, trigger, element)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_010119 | Implement the Python class `Redirect` described below.
Class description:
Implement the Redirect class.
Method signatures and docstrings:
- def __init__(self, trigger, element): Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: Th... | Implement the Python class `Redirect` described below.
Class description:
Implement the Redirect class.
Method signatures and docstrings:
- def __init__(self, trigger, element): Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: Th... | 209665f27913232433f9b69bdff282ff5e49b7bb | <|skeleton|>
class Redirect:
def __init__(self, trigger, element):
"""Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: The XML Element object :type element: etree._Element"""
<|body_0|>
def value(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Redirect:
def __init__(self, trigger, element):
"""Initialize a new Random Tag instance :param trigger: The executing Trigger instance :type trigger: parser.trigger.Trigger :param element: The XML Element object :type element: etree._Element"""
super(Redirect, self).__init__(trigger, element)
... | the_stack_v2_python_sparse | agentml/parser/tags/redirect.py | Python3pkg/AgentML | train | 0 | |
a141ec628b5b6d9fcd3d9af3bf0f485ea2e7d2d6 | [
"if not nums:\n return nums\nred = 0\nwhite = 0\nblue = 0\nindex = 0\nfor item in nums:\n if item == 0:\n red += 1\n elif item == 1:\n white += 1\n else:\n blue += 1\nwhile red > 0:\n nums[index] = 0\n index += 1\n red -= 1\nwhile white > 0:\n nums[index] = 1\n index ... | <|body_start_0|>
if not nums:
return nums
red = 0
white = 0
blue = 0
index = 0
for item in nums:
if item == 0:
red += 1
elif item == 1:
white += 1
else:
blue += 1
while... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_013991 | 2,355 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | stack_v2_sparse_classes_30k_train_010382 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums): :type nums: List[int] :rtype: ... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
if not nums:
return nums
red = 0
white = 0
blue = 0
index = 0
for item in nums:
if item == 0:
... | the_stack_v2_python_sparse | 中级算法/sortColors.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
b42cd3bb8e5279f575e5be41b39b387ec110fb05 | [
"records = []\nfor _ in range(start_id, start_id + record_count):\n record = self.__create_record()\n records.append(record)\nreturn records",
"instrument = self.get_random_instrument()\nrecord = {'instrument_id': instrument['instrument_id'], 'price': self.create_random_decimal(min=1, max=10, dp=2), 'curren... | <|body_start_0|>
records = []
for _ in range(start_id, start_id + record_count):
record = self.__create_record()
records.append(record)
return records
<|end_body_0|>
<|body_start_1|>
instrument = self.get_random_instrument()
record = {'instrument_id': ins... | Class to create prices. Create method will create a set amount of prices. | PriceFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create... | stack_v2_sparse_classes_36k_train_013992 | 1,577 | no_license | [
{
"docstring": "Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create from lock : Lock Locks critical section of InstrumentFactory class. Defaults to None in all other Factory classes. Returns ------- List Containing 'record_count'... | 2 | stack_v2_sparse_classes_30k_train_007211 | Implement the Python class `PriceFactory` described below.
Class description:
Class to create prices. Create method will create a set amount of prices.
Method signatures and docstrings:
- def create(self, record_count, start_id, lock=None): Create a set number of prices Parameters ---------- record_count : int Number... | Implement the Python class `PriceFactory` described below.
Class description:
Class to create prices. Create method will create a set amount of prices.
Method signatures and docstrings:
- def create(self, record_count, start_id, lock=None): Create a set number of prices Parameters ---------- record_count : int Number... | 1d8257bdd9e4533161f64e114f57312905adad5c | <|skeleton|>
class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create from lock : ... | the_stack_v2_python_sparse | src/domainobjectfactories/price_factory.py | galatea-associates/fuse-test-data-gen | train | 0 |
47bd0ec8d97d3ab85e51ee3413941a99aa37a0f9 | [
"response = json.dumps(instance.accounting_summary, sort_keys=True, indent=2)\nresponse = response\nformatter = HtmlFormatter(style='colorful')\nresponse = highlight(response, JsonLexer(), formatter)\nstyle = '<style>' + formatter.get_style_defs() + '</style><br>'\nreturn mark_safe(style + response)",
"response =... | <|body_start_0|>
response = json.dumps(instance.accounting_summary, sort_keys=True, indent=2)
response = response
formatter = HtmlFormatter(style='colorful')
response = highlight(response, JsonLexer(), formatter)
style = '<style>' + formatter.get_style_defs() + '</style><br>'
... | SmeSummaryAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmeSummaryAdmin:
def accounting_summary_json(self, instance):
"""Function to display pretty version of our data"""
<|body_0|>
def placed_order_accounting_summary_json(self, instance):
"""Function to display pretty version of our data"""
<|body_1|>
def bi... | stack_v2_sparse_classes_36k_train_013993 | 6,252 | permissive | [
{
"docstring": "Function to display pretty version of our data",
"name": "accounting_summary_json",
"signature": "def accounting_summary_json(self, instance)"
},
{
"docstring": "Function to display pretty version of our data",
"name": "placed_order_accounting_summary_json",
"signature": ... | 3 | null | Implement the Python class `SmeSummaryAdmin` described below.
Class description:
Implement the SmeSummaryAdmin class.
Method signatures and docstrings:
- def accounting_summary_json(self, instance): Function to display pretty version of our data
- def placed_order_accounting_summary_json(self, instance): Function to ... | Implement the Python class `SmeSummaryAdmin` described below.
Class description:
Implement the SmeSummaryAdmin class.
Method signatures and docstrings:
- def accounting_summary_json(self, instance): Function to display pretty version of our data
- def placed_order_accounting_summary_json(self, instance): Function to ... | 763fafb271ce07d13ac8ce575f2fee653cf39343 | <|skeleton|>
class SmeSummaryAdmin:
def accounting_summary_json(self, instance):
"""Function to display pretty version of our data"""
<|body_0|>
def placed_order_accounting_summary_json(self, instance):
"""Function to display pretty version of our data"""
<|body_1|>
def bi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmeSummaryAdmin:
def accounting_summary_json(self, instance):
"""Function to display pretty version of our data"""
response = json.dumps(instance.accounting_summary, sort_keys=True, indent=2)
response = response
formatter = HtmlFormatter(style='colorful')
response = hig... | the_stack_v2_python_sparse | web/transiq/sme/admin.py | manibhushan05/tms | train | 0 | |
814cfc5a34effc2a440c60d5aa43db239f6266bb | [
"category = classifier.classify(key)\nif category in container:\n container[category].append(value)\nelse:\n container.update({category: subCollectionFactory(value)})",
"elapsedTscGroup = {}\nfor txn in txnSubCollection:\n if txn.hasProbes([beginProbe, endProbe]):\n beginCounter = txn.getCounterFo... | <|body_start_0|>
category = classifier.classify(key)
if category in container:
container[category].append(value)
else:
container.update({category: subCollectionFactory(value)})
<|end_body_0|>
<|body_start_1|>
elapsedTscGroup = {}
for txn in txnSubCollecti... | Aggregates transaction by categories | TxnAggregator | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_36k_train_013994 | 5,883 | permissive | [
{
"docstring": "Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subCollectionFactory: Callable used to build an instance of subcollection :param classifier: Predicate to classify transactions into different categ... | 4 | stack_v2_sparse_classes_30k_train_009637 | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | Implement the Python class `TxnAggregator` described below.
Class description:
Aggregates transaction by categories
Method signatures and docstrings:
- def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value): Adds transaction to a transaction subcollection with matching category :param cont... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TxnAggregator:
"""Aggregates transaction by categories"""
def _addOrUpdateContainer(container, subCollectionFactory, classifier, key, value):
"""Adds transaction to a transaction subcollection with matching category :param container: Container with all categories of aggreagated values :param subC... | the_stack_v2_python_sparse | scripts/lib/xpedite/analytics/aggregator.py | dendisuhubdy/Xpedite | train | 1 |
db629d32fe46f2590d46c9efe9e20b2423a6e8b1 | [
"room = Classroom(name='Cool new Class')\nroom.save()\nself.assertIsInstance(room, Classroom)",
"class_name = 'Cool new Class'\nroom = Classroom(name=class_name)\nroom.save()\nfull_code = '%s-%s' % (class_name, room.code)\nself.assertEqual(room.get_full_code(), slugify(unicode(full_code)).__str__())",
"instruct... | <|body_start_0|>
room = Classroom(name='Cool new Class')
room.save()
self.assertIsInstance(room, Classroom)
<|end_body_0|>
<|body_start_1|>
class_name = 'Cool new Class'
room = Classroom(name=class_name)
room.save()
full_code = '%s-%s' % (class_name, room.code)
... | ClassesModelTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassesModelTests:
def test_classroom_model_creation(self):
"""Be sure the classroom model is able to be created properly."""
<|body_0|>
def test_classroom_code_output(self):
"""Test code generation."""
<|body_1|>
def test_classroom_association(self):
... | stack_v2_sparse_classes_36k_train_013995 | 1,441 | no_license | [
{
"docstring": "Be sure the classroom model is able to be created properly.",
"name": "test_classroom_model_creation",
"signature": "def test_classroom_model_creation(self)"
},
{
"docstring": "Test code generation.",
"name": "test_classroom_code_output",
"signature": "def test_classroom_... | 3 | stack_v2_sparse_classes_30k_train_016713 | Implement the Python class `ClassesModelTests` described below.
Class description:
Implement the ClassesModelTests class.
Method signatures and docstrings:
- def test_classroom_model_creation(self): Be sure the classroom model is able to be created properly.
- def test_classroom_code_output(self): Test code generatio... | Implement the Python class `ClassesModelTests` described below.
Class description:
Implement the ClassesModelTests class.
Method signatures and docstrings:
- def test_classroom_model_creation(self): Be sure the classroom model is able to be created properly.
- def test_classroom_code_output(self): Test code generatio... | 56621d75204d51816210ffa3a3e336636242b843 | <|skeleton|>
class ClassesModelTests:
def test_classroom_model_creation(self):
"""Be sure the classroom model is able to be created properly."""
<|body_0|>
def test_classroom_code_output(self):
"""Test code generation."""
<|body_1|>
def test_classroom_association(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassesModelTests:
def test_classroom_model_creation(self):
"""Be sure the classroom model is able to be created properly."""
room = Classroom(name='Cool new Class')
room.save()
self.assertIsInstance(room, Classroom)
def test_classroom_code_output(self):
"""Test co... | the_stack_v2_python_sparse | Writerr/classes/tests.py | zetas/django-writer | train | 0 | |
c0d2a57653b1c6d2d04ef968d0bddc3b11c4f714 | [
"_Config.__init__(self)\nconfig_file = agent_config_filename(PATTOO_WEBD_NAME)\nself._daemon_configuration = files.read_yaml_file(config_file)",
"key = PATTOO_WEBD_NAME\nsub_key = 'ip_listen_address'\nresult = search(key, sub_key, self._daemon_configuration, die=False)\nif result is None:\n result = '0.0.0.0'\... | <|body_start_0|>
_Config.__init__(self)
config_file = agent_config_filename(PATTOO_WEBD_NAME)
self._daemon_configuration = files.read_yaml_file(config_file)
<|end_body_0|>
<|body_start_1|>
key = PATTOO_WEBD_NAME
sub_key = 'ip_listen_address'
result = search(key, sub_key,... | Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant | Config | [
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant"""
def __init__(self):
"""Initialize the class. Args: None Returns: None"""
<|body_0|>
def ip_listen_addre... | stack_v2_sparse_classes_36k_train_013996 | 3,449 | permissive | [
{
"docstring": "Initialize the class. Args: None Returns: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get ip_listen_address. Args: None Returns: result: result",
"name": "ip_listen_address",
"signature": "def ip_listen_address(self)"
},
{
"docs... | 6 | stack_v2_sparse_classes_30k_train_011245 | Implement the Python class `Config` described below.
Class description:
Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant
Method signatures and docstrings:
- def __init__(self): Initialize the class. Args: None Ret... | Implement the Python class `Config` described below.
Class description:
Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant
Method signatures and docstrings:
- def __init__(self): Initialize the class. Args: None Ret... | 390c7cb687ba46aee1bbb5764cce01fec0d662fb | <|skeleton|>
class Config:
"""Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant"""
def __init__(self):
"""Initialize the class. Args: None Returns: None"""
<|body_0|>
def ip_listen_addre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Class gathers all configuration information. Only processes the following YAML keys in the configuration file: The value of the PATTOO_WEBD_NAME constant"""
def __init__(self):
"""Initialize the class. Args: None Returns: None"""
_Config.__init__(self)
config_file = age... | the_stack_v2_python_sparse | pattoo_web/configuration.py | palisadoes/pattoo-web | train | 0 |
2a4ce08fa1df750db7bae3280b585a4edea41da7 | [
"_id = request.form.get('id', request.args.get('id', None))\nif _id is None:\n return {'success': False, 'message': 'id must be supplied', 'result': None}\ncontainer = mozart_es.get_by_id(index=CONTAINERS_INDEX, id=_id, ignore=404)\nif container['found'] is False:\n return ({'success': False, 'message': 'cont... | <|body_start_0|>
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return {'success': False, 'message': 'id must be supplied', 'result': None}
container = mozart_es.get_by_id(index=CONTAINERS_INDEX, id=_id, ignore=404)
if container['found'] is False:
... | Container Rest APIs (GET, POST, DELETE) | Containers | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
<|body_0|>
def post(self):
"""Add a container specification to Mozart"""
<|body_1|>
def delete(self):
"""Remove container based ... | stack_v2_sparse_classes_36k_train_013997 | 13,931 | permissive | [
{
"docstring": "Get information on container by ID",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a container specification to Mozart",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Remove container based on ID",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_019374 | Implement the Python class `Containers` described below.
Class description:
Container Rest APIs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Get information on container by ID
- def post(self): Add a container specification to Mozart
- def delete(self): Remove container based on ID | Implement the Python class `Containers` described below.
Class description:
Container Rest APIs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Get information on container by ID
- def post(self): Add a container specification to Mozart
- def delete(self): Remove container based on ID
<|skelet... | c238340fafd96a9b92d92e544d0892a354c1ca32 | <|skeleton|>
class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
<|body_0|>
def post(self):
"""Add a container specification to Mozart"""
<|body_1|>
def delete(self):
"""Remove container based ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Containers:
"""Container Rest APIs (GET, POST, DELETE)"""
def get(self):
"""Get information on container by ID"""
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return {'success': False, 'message': 'id must be supplied', 'result': None}
... | the_stack_v2_python_sparse | mozart/services/api_v02/specs.py | hysds/mozart | train | 1 |
3f4d965b26762662d983689614a1e6fd1904395f | [
"super().__init__()\nself.block_size = [2, 2, 3, 3, 3]\nself.conv_1_1 = nn.Conv2d(3, 64, 3, stride=1, padding=1)\nself.conv_1_2 = nn.Conv2d(64, 64, 3, stride=1, padding=1)\nself.conv_2_1 = nn.Conv2d(64, 128, 3, stride=1, padding=1)\nself.conv_2_2 = nn.Conv2d(128, 128, 3, stride=1, padding=1)\nself.conv_3_1 = nn.Con... | <|body_start_0|>
super().__init__()
self.block_size = [2, 2, 3, 3, 3]
self.conv_1_1 = nn.Conv2d(3, 64, 3, stride=1, padding=1)
self.conv_1_2 = nn.Conv2d(64, 64, 3, stride=1, padding=1)
self.conv_2_1 = nn.Conv2d(64, 128, 3, stride=1, padding=1)
self.conv_2_2 = nn.Conv2d(12... | Main Class | VGG_16 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG_16:
"""Main Class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def load_weights(self, path='/home/SENSETIME/dengyang/PycharmProjects/vgg-face.pytorch/pretrained/VGG_FACE.t7'):
"""Function to load luatorch pretrained Args: path: path for the luatorch pr... | stack_v2_sparse_classes_36k_train_013998 | 7,156 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Function to load luatorch pretrained Args: path: path for the luatorch pretrained",
"name": "load_weights",
"signature": "def load_weights(self, path='/home/SENSETIME/dengyang/PycharmPr... | 3 | stack_v2_sparse_classes_30k_train_013073 | Implement the Python class `VGG_16` described below.
Class description:
Main Class
Method signatures and docstrings:
- def __init__(self): Constructor
- def load_weights(self, path='/home/SENSETIME/dengyang/PycharmProjects/vgg-face.pytorch/pretrained/VGG_FACE.t7'): Function to load luatorch pretrained Args: path: pat... | Implement the Python class `VGG_16` described below.
Class description:
Main Class
Method signatures and docstrings:
- def __init__(self): Constructor
- def load_weights(self, path='/home/SENSETIME/dengyang/PycharmProjects/vgg-face.pytorch/pretrained/VGG_FACE.t7'): Function to load luatorch pretrained Args: path: pat... | f61bbd71694f26a88035819888fb6aaa3dfd6c83 | <|skeleton|>
class VGG_16:
"""Main Class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def load_weights(self, path='/home/SENSETIME/dengyang/PycharmProjects/vgg-face.pytorch/pretrained/VGG_FACE.t7'):
"""Function to load luatorch pretrained Args: path: path for the luatorch pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG_16:
"""Main Class"""
def __init__(self):
"""Constructor"""
super().__init__()
self.block_size = [2, 2, 3, 3, 3]
self.conv_1_1 = nn.Conv2d(3, 64, 3, stride=1, padding=1)
self.conv_1_2 = nn.Conv2d(64, 64, 3, stride=1, padding=1)
self.conv_2_1 = nn.Conv2d(... | the_stack_v2_python_sparse | models/data_filter.py | yddd2333/vgg-face.pytorch | train | 0 |
7c3c5e87f9ada0fb82af9dd988e90bf85eb56c95 | [
"super(FiniteHorizonWrapper, self).__init__(env=env)\nself._max_episode_steps = max_episode_steps\nself._episode_step = 0\nself._pbar = tqdm.tqdm(total=self._max_episode_steps)",
"self._episode_step = 0\nself._pbar.reset()\nreturn self.env.reset(*args, **kwargs)",
"observation, reward, done, info = self.env.ste... | <|body_start_0|>
super(FiniteHorizonWrapper, self).__init__(env=env)
self._max_episode_steps = max_episode_steps
self._episode_step = 0
self._pbar = tqdm.tqdm(total=self._max_episode_steps)
<|end_body_0|>
<|body_start_1|>
self._episode_step = 0
self._pbar.reset()
... | Terminates simulation after specified number of steps. | FiniteHorizonWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FiniteHorizonWrapper:
"""Terminates simulation after specified number of steps."""
def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None:
"""Constructs a gym wrapper to terminate execution after `max_episode_steps` steps."""
<|body_0|>
def reset(self, *args... | stack_v2_sparse_classes_36k_train_013999 | 8,971 | permissive | [
{
"docstring": "Constructs a gym wrapper to terminate execution after `max_episode_steps` steps.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None"
},
{
"docstring": "Resets the wrapped environment and sets the counter to 0.",
"name": "re... | 3 | stack_v2_sparse_classes_30k_test_000563 | Implement the Python class `FiniteHorizonWrapper` described below.
Class description:
Terminates simulation after specified number of steps.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None: Constructs a gym wrapper to terminate execution after `max_episode_steps... | Implement the Python class `FiniteHorizonWrapper` described below.
Class description:
Terminates simulation after specified number of steps.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None: Constructs a gym wrapper to terminate execution after `max_episode_steps... | 1680aee77a53228412f9bab34068f0a9576c58e3 | <|skeleton|>
class FiniteHorizonWrapper:
"""Terminates simulation after specified number of steps."""
def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None:
"""Constructs a gym wrapper to terminate execution after `max_episode_steps` steps."""
<|body_0|>
def reset(self, *args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FiniteHorizonWrapper:
"""Terminates simulation after specified number of steps."""
def __init__(self, env: gym.Env, *, max_episode_steps: int) -> None:
"""Constructs a gym wrapper to terminate execution after `max_episode_steps` steps."""
super(FiniteHorizonWrapper, self).__init__(env=env... | the_stack_v2_python_sparse | oatomobile/core/rl.py | OATML/oatomobile | train | 177 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.