uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
6442682fd75dd5851ab98ee0
train
function
def hints(env: PysmtEnv) -> FrozenSet[Hint]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager delta = mgr.Symbol(delta_name, types.REAL) r2s = mgr.Symbol("r2s", types.INT) s2r = mgr.Symbol("r2s", types.INT) s_l = mgr.Symbol("s_l", types.BOOL) s_evt = mgr.Symbol("s_evt", types.BOOL...
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv) mgr = env.formula_manager delta = mgr.Symbol(delta_name, types.REAL) r2s = mgr.Symbol("r2s", types.INT) s2r = mgr.Symbol("r2s", types.INT) s_l = mgr.Symbol("s_l", types.BOOL) s_evt = mgr.Symbol("s_evt", types.BOOL) s_msg_id = mgr.Symbol("s_msg_id", types...
(wait & wait') -> (out_c' = out_c) lhs = msat_make_and(menv, disc_t, msat_make_and(menv, self.wait, self.x_wait)) rhs = msat_make_equal(menv, x_out_c, out_c) self.trans = msat_make_and(menv, self.trans, msat_make_impl(menv, lhs, rhs...
256
256
1,608
15
241
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
hints
hints
342
497
342
342
a3d46dbdc3d228d1409ddc6de24780b7c1c905c4
bigcode/the-stack
train
41fef05e522e16ec8ae1d95c
train
function
def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term): m_one = msat_make_number(menv, "-1") arg1 = msat_make_times(menv, arg1, m_one) return msat_make_plus(menv, arg0, arg1)
def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
m_one = msat_make_number(menv, "-1") arg1 = msat_make_times(menv, arg1, m_one) return msat_make_plus(menv, arg0, arg1)
(pred) x_vals.append(x_pred) assert len(vals) == enum_size assert len(x_vals) == enum_size return b_vars, vals, x_vals def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
72
26
37
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
msat_make_minus
msat_make_minus
60
63
60
60
c38225f1e9673b3cae169f25af1413608ccd44e7
bigcode/the-stack
train
59b7c141ae9af8efe13e31c3
train
function
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term): geq = msat_make_geq(menv, arg0, arg1) return msat_make_not(menv, geq)
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1) return msat_make_not(menv, geq)
(menv, "-1") arg1 = msat_make_times(menv, arg1, m_one) return msat_make_plus(menv, arg0, arg1) def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
56
26
38
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
msat_make_lt
msat_make_lt
66
68
66
66
f682ff02b643620fb47f1bac9d203fab49c9977a
bigcode/the-stack
train
fdbdcbdc8f2b82662a18580d
train
function
def diverging_symbs(menv: msat_env) -> frozenset: real_type = msat_get_rational_type(menv) delta = msat_declare_function(menv, delta_name, real_type) delta = msat_make_constant(menv, delta) return frozenset([delta])
def diverging_symbs(menv: msat_env) -> frozenset:
real_type = msat_get_rational_type(menv) delta = msat_declare_function(menv, delta_name, real_type) delta = msat_make_constant(menv, delta) return frozenset([delta])
_env, arg0: msat_term, arg1: msat_term): n_arg0 = msat_make_not(menv, arg0) return msat_make_or(menv, n_arg0, arg1) def diverging_symbs(menv: msat_env) -> frozenset:
64
64
67
17
47
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
diverging_symbs
diverging_symbs
85
89
85
85
52aee152609891824a5119dca9434b688ce1f7d3
bigcode/the-stack
train
82b8fdbfbc8700ee49cc2c26
train
function
def test_services_using_correct_values_and_passes_in_creds(monkeypatch): def mybuild(service, version, credentials, **_): return (service, version, credentials) monkeypatch.setattr(googleapiclient.discovery, 'build', mybuild) assert api.gmail('creds') == ('gmail', 'v1', 'creds') assert api.sheets('creds2'...
def test_services_using_correct_values_and_passes_in_creds(monkeypatch):
def mybuild(service, version, credentials, **_): return (service, version, credentials) monkeypatch.setattr(googleapiclient.discovery, 'build', mybuild) assert api.gmail('creds') == ('gmail', 'v1', 'creds') assert api.sheets('creds2') == ('sheets', 'v4', 'creds2')
import googleapiclient.discovery from emailer import api def test_services_using_correct_values_and_passes_in_creds(monkeypatch):
29
64
100
16
12
marcdurham/emailer
tests/test_api.py
Python
test_services_using_correct_values_and_passes_in_creds
test_services_using_correct_values_and_passes_in_creds
6
13
6
7
ab3b2ac1f132ef74ee9cfd34a994d32bf3ec3467
bigcode/the-stack
train
860f38696217f8df56090fad
train
class
class LocationReassignmentRequestForm(BulkUploadForm): VALIDATE = "validate" EMAIL_HOUSEHOLDS = "email_households" UPDATE = "update" REASSIGN_HOUSEHOLDS = "reassign_households" ACTION_TYPE_CHOICES = [(VALIDATE, ugettext("Validate")), (EMAIL_HOUSEHOLDS, ugettext("Email Hous...
class LocationReassignmentRequestForm(BulkUploadForm):
VALIDATE = "validate" EMAIL_HOUSEHOLDS = "email_households" UPDATE = "update" REASSIGN_HOUSEHOLDS = "reassign_households" ACTION_TYPE_CHOICES = [(VALIDATE, ugettext("Validate")), (EMAIL_HOUSEHOLDS, ugettext("Email Households")), (UPDATE, ugettext...
forms from django.utils.translation import ugettext from crispy_forms import layout as crispy from crispy_forms.bootstrap import InlineField from corehq.apps.hqwebapp.forms import BulkUploadForm from corehq.apps.hqwebapp.widgets import SelectToggle class LocationReassignmentRequestForm(BulkUploadForm):
64
64
199
11
52
satyaakam/commcare-hq
custom/icds/location_reassignment/forms.py
Python
LocationReassignmentRequestForm
LocationReassignmentRequestForm
11
29
11
11
4fc19db09dd296bdeda4a560e6ce7ea1204e6873
bigcode/the-stack
train
c7aad26efb2d73103b1526f0
train
function
def check_file( filename: str, binary: str, retries: int, ) -> List[LintMessage]: try: proc = run_command( [binary, filename], extra_env={}, retries=retries, ) except OSError as err: return [ LintMessage( path=fi...
def check_file( filename: str, binary: str, retries: int, ) -> List[LintMessage]:
try: proc = run_command( [binary, filename], extra_env={}, retries=retries, ) except OSError as err: return [ LintMessage( path=filename, line=None, char=None, code="MYPY", ...
(end_time - start_time) * 1000) # Severity is either "error" or "note": https://git.io/JiLOP severities = { "error": LintSeverity.ERROR, "note": LintSeverity.ADVICE, } def check_file( filename: str, binary: str, retries: int, ) -> List[LintMessage]:
83
83
277
26
57
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
check_file
check_file
86
131
86
90
f7098fb51038270996827055e3b5034a545255a6
bigcode/the-stack
train
d5c58f87b78c2fc5741dad2b
train
class
class LintMessage(NamedTuple): path: str line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] bypassChangedLineFiltering: Optional[bool]
class LintMessage(NamedTuple):
path: str line: Optional[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] bypassChangedLineFiltering: Optional[bool]
: Any) -> None: print(*args, file=sys.stderr, flush=True, **kwargs) class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" class LintMessage(NamedTuple):
64
64
70
8
56
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
LintMessage
LintMessage
28
38
28
28
04296f1d1a0304ee8973291e14bc7806dacdb60e
bigcode/the-stack
train
36f235ef19f929cd9aabe9d9
train
function
def main() -> None: parser = argparse.ArgumentParser( description="mypy wrapper linter.", fromfile_prefix_chars="@", ) parser.add_argument( "--binary", required=True, help="mypy binary path", ) parser.add_argument( "--retries", default=3, ...
def main() -> None:
parser = argparse.ArgumentParser( description="mypy wrapper linter.", fromfile_prefix_chars="@", ) parser.add_argument( "--binary", required=True, help="mypy binary path", ) parser.add_argument( "--retries", default=3, type=int, ...
message"], line=int(match["line"]), char=int(match["column"]) if match["column"] is not None and not match["column"].startswith("-") else None, code="MYPY", severity=severities.get(match["severity"], LintSeverity.ERROR), original=None, ...
96
97
326
6
90
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
main
main
134
191
134
134
59f00c6a1d993d1545b9d4e77865d379fe74704a
bigcode/the-stack
train
5082b82d890c8c723da27c96
train
class
class LintSeverity(str, Enum): ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled"
class LintSeverity(str, Enum):
ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled"
import Any, Dict, List, NamedTuple, Optional, Pattern IS_WINDOWS: bool = os.name == "nt" def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, flush=True, **kwargs) class LintSeverity(str, Enum):
64
64
35
8
56
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
LintSeverity
LintSeverity
21
25
21
21
692c180db58e452b88cea19a0f545e105f2d6515
bigcode/the-stack
train
ad143438265ba0eebba5c287
train
function
def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=sys.stderr, flush=True, **kwargs)
def eprint(*args: Any, **kwargs: Any) -> None:
print(*args, file=sys.stderr, flush=True, **kwargs)
import os import re import subprocess import sys import time from enum import Enum from typing import Any, Dict, List, NamedTuple, Optional, Pattern IS_WINDOWS: bool = os.name == "nt" def eprint(*args: Any, **kwargs: Any) -> None:
64
64
31
16
48
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
eprint
eprint
17
18
17
17
fddcdf69e1fde6d6283a77460c296cd68065f62e
bigcode/the-stack
train
ce0c9bd029b7ab73faaaa6ec
train
function
def run_command( args: List[str], *, extra_env: Optional[Dict[str, str]], retries: int, ) -> "subprocess.CompletedProcess[bytes]": logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdout=subprocess.PIPE, ...
def run_command( args: List[str], *, extra_env: Optional[Dict[str, str]], retries: int, ) -> "subprocess.CompletedProcess[bytes]":
logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_ti...
s(?P<message>.*) \s(?P<code>\[.*\]) $ """ ) def run_command( args: List[str], *, extra_env: Optional[Dict[str, str]], retries: int, ) -> "subprocess.CompletedProcess[bytes]":
64
64
117
39
25
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
run_command
run_command
61
77
61
66
0371db4b4eb20b6ff8db14e9c70a523e8e0a1a20
bigcode/the-stack
train
cb53de8be9a3be31888b72fa
train
function
def as_posix(name: str) -> str: return name.replace("\\", "/") if IS_WINDOWS else name
def as_posix(name: str) -> str:
return name.replace("\\", "/") if IS_WINDOWS else name
[int] char: Optional[int] code: str severity: LintSeverity name: str original: Optional[str] replacement: Optional[str] description: Optional[str] bypassChangedLineFiltering: Optional[bool] def as_posix(name: str) -> str:
64
64
25
11
53
hipersys-team/pytorch
tools/linter/adapters/mypy_linter.py
Python
as_posix
as_posix
41
42
41
41
882bdaea3c76dc447a874243b198674747bd2976
bigcode/the-stack
train
f0e8ce018969cc1aaaaa34e9
train
class
class GradientPerturb(abc.ABC): """Base class for all adversarial training perturbations. Parameters ------------ net : a :class: `torch.nn.Module` instance The net should be neural network in torch. criterion: a :class: `torch.nn.Loss` The loss function used in training neural netwo...
class GradientPerturb(abc.ABC):
"""Base class for all adversarial training perturbations. Parameters ------------ net : a :class: `torch.nn.Module` instance The net should be neural network in torch. criterion: a :class: `torch.nn.Loss` The loss function used in training neural networks. eps: a :class: `float` ...
"""Functions to adversarially perturb an input image during net training""" from torch.autograd import grad from math import sqrt, inf import torch import abc from ..operator import forwardOperator, backwardOperator class GradientPerturb(abc.ABC):
53
181
606
9
43
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
GradientPerturb
GradientPerturb
8
84
8
8
a2fd1fd8c224a2ebced64ff18aa5f89155daae1e
bigcode/the-stack
train
83222fb9ecf8721ce4edab92
train
class
class LInfPerturbation(SingleStepGradientPerturb): """ Penalize a loss function by the L-infinity norm of the loss's gradient. """ def _gradient(self, x, y): with torch.enable_grad(): if self._forward_op is not None: xx = self._forward_op(x) else: ...
class LInfPerturbation(SingleStepGradientPerturb):
""" Penalize a loss function by the L-infinity norm of the loss's gradient. """ def _gradient(self, x, y): with torch.enable_grad(): if self._forward_op is not None: xx = self._forward_op(x) else: xx = x logits = self._net(xx) ...
(dim=1, keepdim=True) b = (dxn>0).squeeze() dx[b] = dx[b]/dxn[b] gradient = dx.view(*dxshape) * (self._max_ - self._min_) return self._step_size * gradient class LInfPerturbation(SingleStepGradientPerturb):
75
75
252
13
61
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
LInfPerturbation
LInfPerturbation
186
214
186
186
8fdc8cbbacf5cd82c327a05ed45aa0615bfced20
bigcode/the-stack
train
5ec62c72312c18d55902921d
train
class
class L2Perturbation(SingleStepGradientPerturb): """ Penalize a loss function by the L2 norm of the loss's gradient. """ def _clip_perturbation(self, perturbed, original): norm = perturbed.pow(2).mean().sqrt() norm = max(1e-15, norm) factor = min(1, self._eps * (self._max_ - self...
class L2Perturbation(SingleStepGradientPerturb):
""" Penalize a loss function by the L2 norm of the loss's gradient. """ def _clip_perturbation(self, perturbed, original): norm = perturbed.pow(2).mean().sqrt() norm = max(1e-15, norm) factor = min(1, self._eps * (self._max_ - self._min_) / norm) return perturbed * facto...
) dx = grad(loss, xx, torch.ones_like(loss))[0] if self._backward_op is not None: dx = self._backward_op(dx) else: pass gradient = dx.sign() * (self._max_ - self._min_) return (self._eps - self._step_size) * gradient class L2Perturbation(SingleStepGradien...
89
89
297
13
75
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
L2Perturbation
L2Perturbation
151
183
151
151
7a20efa453ee90c81aced9822258a0a24eaa2c51
bigcode/the-stack
train
ed9a737f06f9861da4d1ba4a
train
class
class SingleStepGradientPerturb(GradientPerturb): """Single step perturbation """ def _initialize(self): self._num_steps = 1 def _clip_perturbation(self, perturbed, original): return perturbed
class SingleStepGradientPerturb(GradientPerturb):
"""Single step perturbation """ def _initialize(self): self._num_steps = 1 def _clip_perturbation(self, perturbed, original): return perturbed
True) gradient = self._gradient(x_hat, y) x_hat = x_hat.detach() + gradient x_hat = self._clip_perturbation(x_hat, x) self._release_net() return x_hat.detach() class SingleStepGradientPerturb(GradientPerturb):
63
64
55
11
52
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
SingleStepGradientPerturb
SingleStepGradientPerturb
86
93
86
86
07aaf9efcc2b9ebf4a8f75d1148a812cc2f7c69f
bigcode/the-stack
train
86b2be4661d8cee974e01de5
train
class
class L1Perturbation(SingleStepGradientPerturb): """ Penalize a loss function by the L1 norm of the loss's gradient. Equivalent to the Fast Gradient Signed Method. """ def _clip_perturbation(self, perturbed, original): perturbed = torch.min(torch.max(perturbed, original-self._eps), ...
class L1Perturbation(SingleStepGradientPerturb):
""" Penalize a loss function by the L1 norm of the loss's gradient. Equivalent to the Fast Gradient Signed Method. """ def _clip_perturbation(self, perturbed, original): perturbed = torch.min(torch.max(perturbed, original-self._eps), original+self._eps) ...
() class SingleStepGradientPerturb(GradientPerturb): """Single step perturbation """ def _initialize(self): self._num_steps = 1 def _clip_perturbation(self, perturbed, original): return perturbed class L1Perturbation(SingleStepGradientPerturb):
70
70
236
13
56
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
L1Perturbation
L1Perturbation
95
122
95
95
2aaf7536cfd8afd7cef944d040442835e7c76386
bigcode/the-stack
train
76c16db01c3523ed92727e0e
train
class
class RFGSM(L1Perturbation): """ R+FGSM: FGSM variant that prepends the gradient computation by a random step Reference: Ensemble adversarial training: attacks and defenses. ICLR 2018, url: https://openreview.net/pdf?id=rkZvSe-RZ """ def _gradient(self, x, y): x_new = x + self._step_siz...
class RFGSM(L1Perturbation):
""" R+FGSM: FGSM variant that prepends the gradient computation by a random step Reference: Ensemble adversarial training: attacks and defenses. ICLR 2018, url: https://openreview.net/pdf?id=rkZvSe-RZ """ def _gradient(self, x, y): x_new = x + self._step_size * torch.zeros_like(x).norma...
backward_op is not None: dx = self._backward_op(dx) else: pass gradient = dx.sign() * (self._max_ - self._min_) return self._step_size * gradient FGSM = L1Perturbation class RFGSM(L1Perturbation):
69
69
230
10
58
AlbertZhangHIT/DL-Templates
dlt/perturbations/gradient.py
Python
RFGSM
RFGSM
126
148
126
126
ee01172005ba244d3f20466aaab4969b3b1c6cd2
bigcode/the-stack
train
bc94d269c6ef7cf78fff5d9d
train
class
class NewOutstandingTokenAdmin(OutstandingTokenAdmin): def has_delete_permission(self, *args, **kwargs): return True
class NewOutstandingTokenAdmin(OutstandingTokenAdmin):
def has_delete_permission(self, *args, **kwargs): return True
from django.contrib import admin from rest_framework_simplejwt import token_blacklist from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin from users.models import User class NewOutstandingTokenAdmin(OutstandingTokenAdmin):
46
64
27
10
35
Dopaman/xcurator_backend
users/admin.py
Python
NewOutstandingTokenAdmin
NewOutstandingTokenAdmin
7
9
7
7
776d6d5d784ab17dfc10a3d047b6161c3a4d09d3
bigcode/the-stack
train
69822020744a8d806fb0ba18
train
class
class UserAdmin(admin.ModelAdmin): fieldsets = [ ( "Credentials", { "fields": [ "email", "username", "first_name", "last_name", "password", ] ...
class UserAdmin(admin.ModelAdmin):
fieldsets = [ ( "Credentials", { "fields": [ "email", "username", "first_name", "last_name", "password", ] }, ), ( ...
import User class NewOutstandingTokenAdmin(OutstandingTokenAdmin): def has_delete_permission(self, *args, **kwargs): return True admin.site.unregister(token_blacklist.models.OutstandingToken) admin.site.register(token_blacklist.models.OutstandingToken, NewOutstandingTokenAdmin) class UserAdmin(admin.Mo...
64
64
161
7
57
Dopaman/xcurator_backend
users/admin.py
Python
UserAdmin
UserAdmin
16
49
16
16
a07a34498a81b1bcdfe1579429f03d305032404f
bigcode/the-stack
train
aa5bc98eea403407358c37b0
train
class
class CheckUserExistenceApiView(APIView): """ Retrieve a "condensed" user instance {"id": ".."} by either "username" or "email" as query params. """ permission_classes = (permissions.AllowAny, ) def get_object(self, login=None, username=None, email=None): try: if login is not N...
class CheckUserExistenceApiView(APIView):
""" Retrieve a "condensed" user instance {"id": ".."} by either "username" or "email" as query params. """ permission_classes = (permissions.AllowAny, ) def get_object(self, login=None, username=None, email=None): try: if login is not None: #! NOQA ...
UserSerializer, NewUserSerializer, UserRevisionSerializer) from ...apps.emails.models import EmailAddress from ...permissions import StaffPermission from ...permissions import is_staff, is_django_staff from ...utils import invalidate_cookie, get_session_key from ...views import DjangoSsoAppB...
104
104
349
10
94
paiuolo/django-sso-app
django_sso_app/core/apps/users/views.py
Python
CheckUserExistenceApiView
CheckUserExistenceApiView
43
92
43
43
f8bd6c8c6bd85c35968fd502fb5c638f61d374a7
bigcode/the-stack
train
3ccad271ea396947609c28f6
train
class
class UserRevisionsApiView(mixins.ListModelMixin, viewsets.GenericViewSet): """ User revisions entrypoint """ queryset = User.objects.filter(is_superuser=False, is_staff=False).order_by('id') serializer_class = UserRevisionSerializer permission_classes = (StaffPermiss...
class UserRevisionsApiView(mixins.ListModelMixin, viewsets.GenericViewSet):
""" User revisions entrypoint """ queryset = User.objects.filter(is_superuser=False, is_staff=False).order_by('id') serializer_class = UserRevisionSerializer permission_classes = (StaffPermission,) def list(self, request, *args, **kwargs): """ List users revisions "...
User {0} updated password and must login again'.format(requesting_user)) invalidate_cookie(response, app_settings.JWT_COOKIE_NAME) else: self.update_response_jwt(user, response) return response class UserRevisionsApiView(mixins.ListModelMixin, ...
64
64
117
20
43
paiuolo/django-sso-app
django_sso_app/core/apps/users/views.py
Python
UserRevisionsApiView
UserRevisionsApiView
193
208
193
194
761fac670c7ff65f52d535026f23766c8ef84f03
bigcode/the-stack
train
8b117eaf781f03eceddd8780
train
class
class UserDetailApiView(generics.RetrieveAPIView): """ User detail entrypoint """ queryset = User.objects.all() serializer_class = UserSerializer def get_object(self, *args, **kwargs): user = getattr(self.request, 'user', None) return user
class UserDetailApiView(generics.RetrieveAPIView):
""" User detail entrypoint """ queryset = User.objects.all() serializer_class = UserSerializer def get_object(self, *args, **kwargs): user = getattr(self.request, 'user', None) return user
,) def list(self, request, *args, **kwargs): """ List users revisions """ logger.info('List users revisions') return super(UserRevisionsApiView, self).list(request, *args, **kwargs) class UserDetailApiView(generics.RetrieveAPIView):
64
64
64
12
52
paiuolo/django-sso-app
django_sso_app/core/apps/users/views.py
Python
UserDetailApiView
UserDetailApiView
211
221
211
211
a8aee60b96953e9b59604d5a57fc49591bb8ac63
bigcode/the-stack
train
1a791860252db18c9b8422ed
train
class
class UserApiViewSet(mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet, DjangoSsoAppBaseViewMi...
class UserApiViewSet(mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet, DjangoSsoAppBaseViewMi...
""" User api viewset """ lookup_field = 'sso_app_profile__sso_id' # serializer_class = UserSerializer permission_classes = (permissions.IsAuthenticated,) filter_backends = (DjangoFilterBackend,) filterset_class = UserFilter def get_serializer_class(self): if self.request.me...
except (User.DoesNotExist, EmailAddress.DoesNotExist): return None def get(self, *args, **kwargs): login = self.request.query_params.get('login', self.request.GET.get('login', None)) username = self.request.query_params.get('username', None) email = self.request.query_pa...
200
200
669
57
143
paiuolo/django-sso-app
django_sso_app/core/apps/users/views.py
Python
UserApiViewSet
UserApiViewSet
95
190
95
101
557b0112ae0c147a5d0e0838d3e98dd6cacdfb99
bigcode/the-stack
train
c33eb77ab402fad65fdb1a74
train
function
def map_icon(key): map_icon_dict = { 'academia': 'book', 'particular': 'home', 'escuela/universidad': 'university', 'remoto': 'laptop', 'otro': 'handshake-o' } return map_icon_dict[key]
def map_icon(key):
map_icon_dict = { 'academia': 'book', 'particular': 'home', 'escuela/universidad': 'university', 'remoto': 'laptop', 'otro': 'handshake-o' } return map_icon_dict[key]
#!/usr/bin/env python # coding: utf-8 # In[116]: import folium import yaml # In[117]: with open(r'data.yaml') as file: data_map = yaml.full_load(file) # In[121]: def map_icon(key):
59
64
66
5
54
brivadeneira/will-jekyll-template
_site/map/mapa-pyar-docentes.py
Python
map_icon
map_icon
21
29
21
21
e9fcc74137f6f206b5ae07a0157a2983b89ff562
bigcode/the-stack
train
85aa03e4664439f1aa17fe18
train
function
def color_icon(key): icon_color_dict = { 'basico': 'lightblue', 'intermedio': 'blue', 'avanzado': 'cadetblue' } return icon_color_dict[key]
def color_icon(key):
icon_color_dict = { 'basico': 'lightblue', 'intermedio': 'blue', 'avanzado': 'cadetblue' } return icon_color_dict[key]
_icon_dict = { 'academia': 'book', 'particular': 'home', 'escuela/universidad': 'university', 'remoto': 'laptop', 'otro': 'handshake-o' } return map_icon_dict[key] def color_icon(key):
64
64
48
5
59
brivadeneira/will-jekyll-template
_site/map/mapa-pyar-docentes.py
Python
color_icon
color_icon
31
37
31
31
832e840bdf1764b68feed0ffa19b29c5c3492a93
bigcode/the-stack
train
8308596f38e2e483b893982a
train
function
def load_content(content): matcher = r'^\w+:' md_content = content.splitlines() attrs = {} if md_content: while re.match(matcher, md_content[0]): line = md_content.pop(0) line_data = line.split(': ', 1) key = line_data[0].lower() value = line_data...
def load_content(content):
matcher = r'^\w+:' md_content = content.splitlines() attrs = {} if md_content: while re.match(matcher, md_content[0]): line = md_content.pop(0) line_data = line.split(': ', 1) key = line_data[0].lower() value = line_data[-1].rstrip() a...
slug or name or id or content_path name if not slug: slug = getattr(self, 'name', None) \ or getattr(self, 'id', None) \ or Path(getattr(self, 'content_path', '/')).stem() self.slug = slug def load_content(content):
64
64
116
5
58
RussTheAerialist/render_engine
render_engine/page.py
Python
load_content
load_content
59
75
59
59
58b032dedd43040879f9a9a99dd058e3abd79194
bigcode/the-stack
train
3c1aa11219f2b2ef1f448911
train
class
class Page(): """Base component used to make web pages""" def __init__( self, *, slug=None, content='', content_path=None, template=None, extension='.html', **kwargs, ): """ initialize a n...
class Page():
"""Base component used to make web pages""" def __init__( self, *, slug=None, content='', content_path=None, template=None, extension='.html', **kwargs, ): """ initialize a new Page object...
from pathlib import Path from markdown import markdown from jinja2 import Markup import maya import re import shlex import subprocess import logging class Page():
37
113
378
3
33
RussTheAerialist/render_engine
render_engine/page.py
Python
Page
Page
11
57
11
11
54b26ff8d98eb913cc55f95e519334e6e1c2bf0c
bigcode/the-stack
train
ad96de1df4a5e069b81487e0
train
function
def test_roc_curve_fpr_tpr_increasing(): # Ensure that fpr and tpr returned by roc_curve are increasing. # Construct an edge case with float y_score and sample_weight # when some adjacent values of fpr and tpr are actually the same. y_true = [0, 0, 1, 1, 1] y_score = [0.1, 0.7, 0.3, 0.4, 0.5] ...
def test_roc_curve_fpr_tpr_increasing(): # Ensure that fpr and tpr returned by roc_curve are increasing. # Construct an edge case with float y_score and sample_weight # when some adjacent values of fpr and tpr are actually the same.
y_true = [0, 0, 1, 1, 1] y_score = [0.1, 0.7, 0.3, 0.4, 0.5] sample_weight = np.repeat(0.2, 5) fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight) assert (np.diff(fpr) < 0).sum() == 0 assert (np.diff(tpr) < 0).sum() == 0
0.]) def test_roc_curve_fpr_tpr_increasing(): # Ensure that fpr and tpr returned by roc_curve are increasing. # Construct an edge case with float y_score and sample_weight # when some adjacent values of fpr and tpr are actually the same.
63
64
180
59
4
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_fpr_tpr_increasing
test_roc_curve_fpr_tpr_increasing
405
414
405
408
797d2d4138ba74ed99c238d167d7f2dd84b8d908
bigcode/the-stack
train
fd7f09e34d1605f796dae43b
train
function
def test_roc_curve_one_label(): y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # assert there are warnings w = UndefinedMetricWarning fpr, tpr, thresholds = assert_warns(w, roc_curve, y_true, y_pred) # all true labels, all fpr should be nan assert_arra...
def test_roc_curve_one_label():
y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # assert there are warnings w = UndefinedMetricWarning fpr, tpr, thresholds = assert_warns(w, roc_curve, y_true, y_pred) # all true labels, all fpr should be nan assert_array_equal(fpr, np.full(len(threshol...
decisions fpr, tpr, thresholds = roc_curve(y_true, pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.78, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape def test_roc_curve_one_label():
75
75
250
8
66
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_one_label
test_roc_curve_one_label
271
289
271
271
e09642e8f879e6ac278fea6b647de509d4617c28
bigcode/the-stack
train
43add4c79193dfe7f1dfc55f
train
function
def test_roc_curve_toydata(): # Binary classification y_true = [0, 1] y_score = [0, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 0, 1]) assert_array_almost_equal(fpr, [0, 1, 1]) assert_almost_equal(roc_auc...
def test_roc_curve_toydata(): # Binary classification
y_true = [0, 1] y_score = [0, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 0, 1]) assert_array_almost_equal(fpr, [0, 1, 1]) assert_almost_equal(roc_auc, 1.) y_true = [0, 1] y_score = [1, 0] tpr,...
y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # assert there are warnings w = UndefinedMetricWarning fpr, tpr, thresholds = assert_warns(w, roc_curve, y_true, y_pred) # all true labels, all fpr should be nan assert_array_equal(fpr, np.full(len(threshol...
256
256
1,268
14
241
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_toydata
test_roc_curve_toydata
292
385
292
293
e341568fce51e1af5e91087d2ddd23b15f1d1143
bigcode/the-stack
train
cab956b5a6f4d7da70a210cd
train
function
@pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 0, 2]), [0, 1, 2]), (np.array([0, 1, 0, 2]), None), (["a", "b", "a", "c"], ["a", "b", "c"]), (["a", "b", "a", "c"], None)] ) def test_multiclass_ovo_roc_auc_toydata(y_true, labels): # Tests the one-vs-one multiclass ROC AUC...
@pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 0, 2]), [0, 1, 2]), (np.array([0, 1, 0, 2]), None), (["a", "b", "a", "c"], ["a", "b", "c"]), (["a", "b", "a", "c"], None)] ) def test_multiclass_ovo_roc_auc_toydata(y_true, labels): # Tests the one-vs-one multiclass ROC AUC...
y_scores = np.array( [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]]) # Used to compute the expected output. # Consider labels 0 and 1: # positive label is 0, negative label is 1 score_01 = roc_auc_score([1, 0, 1], [0.1, 0.3, 0.35]) # positive label is 1, neg...
= [2, 1, 3, 4] y = [5, 6, 7, 8] error_message = ("x is neither increasing nor decreasing : " "{}".format(np.array(x))) with pytest.raises(ValueError, match=re.escape(error_message)): auc(x, y) @pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 0, 2]), ...
211
211
706
143
68
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_multiclass_ovo_roc_auc_toydata
test_multiclass_ovo_roc_auc_toydata
454
503
454
463
4217c8a9d6cf4b42197be169e31c4b690a1eac16
bigcode/the-stack
train
68aadbddba8dfd73bf6c7a46
train
function
@pytest.mark.parametrize( "msg, y_true, labels", [("Parameter 'labels' must be unique", np.array([0, 1, 2, 2]), [0, 2, 0]), ("Parameter 'labels' must be unique", np.array(["a", "b", "c", "c"]), ["a", "a", "b"]), ("Number of classes in y_true not equal to the number of columns " "in '...
@pytest.mark.parametrize( "msg, y_true, labels", [("Parameter 'labels' must be unique", np.array([0, 1, 2, 2]), [0, 2, 0]), ("Parameter 'labels' must be unique", np.array(["a", "b", "c", "c"]), ["a", "a", "b"]), ("Number of classes in y_true not equal to the number of columns " "in '...
y_scores = np.array( [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]]) with pytest.raises(ValueError, match=msg): roc_auc_score(y_true, y_scores, labels=labels, multi_class=multi_class)
@pytest.mark.parametrize( "msg, y_true, labels", [("Parameter 'labels' must be unique", np.array([0, 1, 2, 2]), [0, 2, 0]), ("Parameter 'labels' must be unique", np.array(["a", "b", "c", "c"]), ["a", "a", "b"]), ("Number of classes in y_true not equal to the number of columns " "in '...
525
186
623
525
0
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_auc_score_multiclass_labels_error
test_roc_auc_score_multiclass_labels_error
568
602
568
597
925cf28d33622ef7bcbca2eb960299b04988a543
bigcode/the-stack
train
beb881d9efd1463b5ee7b71c
train
function
def test_dcg_ties(): y_true = np.asarray([np.arange(5)]) y_score = np.zeros(y_true.shape) dcg = _dcg_sample_scores(y_true, y_score) dcg_ignore_ties = _dcg_sample_scores(y_true, y_score, ignore_ties=True) discounts = 1 / np.log2(np.arange(2, 7)) assert dcg == pytest.approx([discounts.sum() ...
def test_dcg_ties():
y_true = np.asarray([np.arange(5)]) y_score = np.zeros(y_true.shape) dcg = _dcg_sample_scores(y_true, y_score) dcg_ignore_ties = _dcg_sample_scores(y_true, y_score, ignore_ties=True) discounts = 1 / np.log2(np.arange(2, 7)) assert dcg == pytest.approx([discounts.sum() * y_true.mean()]) ...
(y_true, y_true, k=5) <= ideal).all() assert ideal.shape == (y_true.shape[0], ) assert score.shape == (y_true.shape[0], ) assert ideal == pytest.approx( (np.sort(y_true)[:, ::-1] / discount).sum(axis=1)) def test_dcg_ties():
76
77
259
7
69
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_dcg_ties
test_dcg_ties
1,350
1,367
1,350
1,350
109e9875d03a5458bbe57ab13180ce66992c4b0a
bigcode/the-stack
train
a4656d1ef2e25476dc065f0b
train
function
def make_prediction(dataset=None, binary=False): """Make some classification predictions on a toy dataset using a SVC If binary is True restrict to a binary classification problem instead of a multiclass classification problem """ if dataset is None: # import some data to play with...
def make_prediction(dataset=None, binary=False):
"""Make some classification predictions on a toy dataset using a SVC If binary is True restrict to a binary classification problem instead of a multiclass classification problem """ if dataset is None: # import some data to play with dataset = datasets.load_iris() X ...
_error from sklearn.metrics import label_ranking_average_precision_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import label_ranking_loss from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve from sklearn.metrics._ranking import _ndcg_sample_scores, _dcg_...
101
101
339
9
91
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
make_prediction
make_prediction
38
79
38
38
bb03a5d17408aad3e40e662481a2aeed82eceb61
bigcode/the-stack
train
4e56b5826c1264271adf97fe
train
function
def test_precision_recall_curve_errors(): # Contains non-binary labels with pytest.raises(ValueError): precision_recall_curve([0, 1, 2], [[0.0], [1.0], [1.0]])
def test_precision_recall_curve_errors(): # Contains non-binary labels
with pytest.raises(ValueError): precision_recall_curve([0, 1, 2], [[0.0], [1.0], [1.0]])
proba having only one value p, r, thresholds = precision_recall_curve(y_true, np.zeros_like(probas_pred)) assert p.size == r.size assert p.size == thresholds.size + 1 def test_precision_recall_curve_errors(): # Contains non-binary labels
64
64
53
16
47
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_precision_recall_curve_errors
test_precision_recall_curve_errors
752
755
752
753
49108f68c6dafa412c5dac48a2a5017946975205
bigcode/the-stack
train
08322bcb29ca3ff75a7c5421
train
function
def test_ndcg_invariant(): y_true = np.arange(70).reshape(7, 10) y_score = y_true + np.random.RandomState(0).uniform( -.2, .2, size=y_true.shape) ndcg = ndcg_score(y_true, y_score) ndcg_no_ties = ndcg_score(y_true, y_score, ignore_ties=True) assert ndcg == pytest.approx(ndcg_no_ties) ...
def test_ndcg_invariant():
y_true = np.arange(70).reshape(7, 10) y_score = y_true + np.random.RandomState(0).uniform( -.2, .2, size=y_true.shape) ndcg = ndcg_score(y_true, y_score) ndcg_no_ties = ndcg_score(y_true, y_score, ignore_ties=True) assert ndcg == pytest.approx(ndcg_no_ties) assert ndcg == pytest.ap...
(): a = np.arange(12).reshape((2, 6)) assert ndcg_score(a, a, k=3, ignore_ties=True) == pytest.approx( ndcg_score(a, a, k=3, ignore_ties=True)) def test_ndcg_invariant():
63
64
138
7
56
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ndcg_invariant
test_ndcg_invariant
1,376
1,385
1,376
1,376
898a252d5abdc4f16a03267ffdb172ed2d9ac4b1
bigcode/the-stack
train
a103cca030307cec5ecda3ad
train
function
@pytest.mark.parametrize('ignore_ties', [True, False]) def test_ndcg_toy_examples(ignore_ties): y_true = 3 * np.eye(7)[:5] y_score = np.tile(np.arange(6, -1, -1), (5, 1)) y_score_noisy = y_score + np.random.RandomState(0).uniform( -.2, .2, size=y_score.shape) assert _dcg_sample_scores( ...
@pytest.mark.parametrize('ignore_ties', [True, False]) def test_ndcg_toy_examples(ignore_ties):
y_true = 3 * np.eye(7)[:5] y_score = np.tile(np.arange(6, -1, -1), (5, 1)) y_score_noisy = y_score + np.random.RandomState(0).uniform( -.2, .2, size=y_score.shape) assert _dcg_sample_scores( y_true, y_score, ignore_ties=ignore_ties) == pytest.approx( 3 / np.log2(np.aran...
variant(): y_true = np.arange(70).reshape(7, 10) y_score = y_true + np.random.RandomState(0).uniform( -.2, .2, size=y_true.shape) ndcg = ndcg_score(y_true, y_score) ndcg_no_ties = ndcg_score(y_true, y_score, ignore_ties=True) assert ndcg == pytest.approx(ndcg_no_ties) assert ndcg ...
156
157
525
24
132
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ndcg_toy_examples
test_ndcg_toy_examples
1,388
1,423
1,388
1,389
77773c19bf218066f3b07899670177a75276eefe
bigcode/the-stack
train
53cd67c974a6899077162402
train
function
def test_ranking_appropriate_input_shape(): # Check that y_true.shape != y_score.shape raise the proper exception with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [0, 1]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0, 1]]) with pytest....
def test_ranking_appropriate_input_shape(): # Check that y_true.shape != y_score.shape raise the proper exception
with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [0, 1]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0], [1]]) with pytest.raises(ValueError): ...
]])), [[0.1, 10, -3], [3, 1, 3]]), (0 + 2 / 2) / 2.) def test_ranking_appropriate_input_shape(): # Check that y_true.shape != y_score.shape raise the proper exception
63
64
210
25
38
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ranking_appropriate_input_shape
test_ranking_appropriate_input_shape
1,300
1,313
1,300
1,301
bba154b851f499f26244495c41967f6f5f83a045
bigcode/the-stack
train
d409c8636d916d3c0f0115e0
train
function
def _test_ndcg_score_for(y_true, y_score): ideal = _ndcg_sample_scores(y_true, y_true) score = _ndcg_sample_scores(y_true, y_score) assert (score <= ideal).all() all_zero = (y_true == 0).all(axis=1) assert ideal[~all_zero] == pytest.approx(np.ones((~all_zero).sum())) assert ideal[all_zero]...
def _test_ndcg_score_for(y_true, y_score):
ideal = _ndcg_sample_scores(y_true, y_true) score = _ndcg_sample_scores(y_true, y_score) assert (score <= ideal).all() all_zero = (y_true == 0).all(axis=1) assert ideal[~all_zero] == pytest.approx(np.ones((~all_zero).sum())) assert ideal[all_zero] == pytest.approx(np.zeros(all_zero.sum())) ...
_test_ndcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_ndcg_score_for(y_true, y_score) def _test_ndcg_score_for(y_true, y_score):
64
64
194
13
51
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_test_ndcg_score_for
_test_ndcg_score_for
1,434
1,446
1,434
1,434
36c906d1590b3b5dd6875a1513e2ea1a603a1304
bigcode/the-stack
train
5393802431113e3132aca020
train
function
def test_binary_clf_curve_multiclass_error(): rng = check_random_state(404) y_true = rng.randint(0, 3, size=10) y_pred = rng.rand(10) msg = "multiclass format is not supported" with pytest.raises(ValueError, match=msg): precision_recall_curve(y_true, y_pred) with pytest.raises...
def test_binary_clf_curve_multiclass_error():
rng = check_random_state(404) y_true = rng.randint(0, 3, size=10) y_pred = rng.rand(10) msg = "multiclass format is not supported" with pytest.raises(ValueError, match=msg): precision_recall_curve(y_true, y_pred) with pytest.raises(ValueError, match=msg): roc_curve(y_t...
match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.full(10, -1, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) def test_binary_clf_curve_multiclass_error():
64
64
99
11
53
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_binary_clf_curve_multiclass_error
test_binary_clf_curve_multiclass_error
665
675
665
665
9bcad1fab0793fe23c1cdfc45ebc0ad582f57e6b
bigcode/the-stack
train
bb857ac5080ef8e4b75ac560
train
function
def test_dcg_score(): _, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = - y_true + 1 _test_dcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_dcg_score_for(y_true, y_score)
def test_dcg_score():
_, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = - y_true + 1 _test_dcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_dcg_score_for(y_true, y_score)
1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 1) def test_dcg_score():
64
64
89
6
58
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_dcg_score
test_dcg_score
1,330
1,335
1,330
1,330
0dde94a231fbd0bf77b2f1953c82ed7c2cf680df
bigcode/the-stack
train
d11cab69de9b19f132c6eaac
train
function
def _test_precision_recall_curve(y_true, probas_pred): # Test Precision-Recall and aread under PR curve p, r, thresholds = precision_recall_curve(y_true, probas_pred) precision_recall_auc = _average_precision_slow(y_true, probas_pred) assert_array_almost_equal(precision_recall_auc, 0.859, 3) as...
def _test_precision_recall_curve(y_true, probas_pred): # Test Precision-Recall and aread under PR curve
p, r, thresholds = precision_recall_curve(y_true, probas_pred) precision_recall_auc = _average_precision_slow(y_true, probas_pred) assert_array_almost_equal(precision_recall_auc, 0.859, 3) assert_array_almost_equal(precision_recall_auc, average_precision_score(y_true, p...
assert_array_almost_equal(t, np.array([1, 2, 3, 4])) assert p.size == r.size assert p.size == t.size + 1 def _test_precision_recall_curve(y_true, probas_pred): # Test Precision-Recall and aread under PR curve
68
68
228
27
40
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_test_precision_recall_curve
_test_precision_recall_curve
733
749
733
734
ef5bd514f769f388a3c74048d4904509d812afd3
bigcode/the-stack
train
9d01412d25ad98cad84e408a
train
function
def test_ndcg_ignore_ties_with_k(): a = np.arange(12).reshape((2, 6)) assert ndcg_score(a, a, k=3, ignore_ties=True) == pytest.approx( ndcg_score(a, a, k=3, ignore_ties=True))
def test_ndcg_ignore_ties_with_k():
a = np.arange(12).reshape((2, 6)) assert ndcg_score(a, a, k=3, ignore_ties=True) == pytest.approx( ndcg_score(a, a, k=3, ignore_ties=True))
]).sum()]) assert dcg == pytest.approx([ discounts[:2].sum() * y_true[0, 3:].mean() + discounts[2:].sum() * y_true[0, :3].mean() ]) def test_ndcg_ignore_ties_with_k():
63
64
65
10
53
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ndcg_ignore_ties_with_k
test_ndcg_ignore_ties_with_k
1,370
1,373
1,370
1,370
4ae0aae8c8dff7189c0ac337074d00ce5de81875
bigcode/the-stack
train
3aa4cc34a4d9f3b25cde6460
train
function
def _my_lrap(y_true, y_score): """Simple implementation of label ranking average precision""" check_consistent_length(y_true, y_score) y_true = check_array(y_true) y_score = check_array(y_score) n_samples, n_labels = y_true.shape score = np.empty((n_samples, )) for i in range(n_sample...
def _my_lrap(y_true, y_score):
"""Simple implementation of label ranking average precision""" check_consistent_length(y_true, y_score) y_true = check_array(y_true) y_score = check_array(y_score) n_samples, n_labels = y_true.shape score = np.empty((n_samples, )) for i in range(n_samples): # The best rank cor...
for pos in range(n_labels - n_relevant): y_true = np.zeros((1, n_labels)) y_true[0, pos:pos + n_relevant] = 1 assert_almost_equal(lrap_score(y_true, y_score), sum((r + 1) / ((pos + r + 1) * n_relevant) ...
99
100
335
11
88
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_my_lrap
_my_lrap
1,072
1,107
1,072
1,072
3b5a88a36d8541ac8349f161193193d86afcda29
bigcode/the-stack
train
406f153b0424dff6e94bb48c
train
function
def test_roc_curve_drop_intermediate(): # Test that drop_intermediate drops the correct thresholds y_true = [0, 0, 0, 0, 1, 1] y_score = [0., 0.2, 0.5, 0.6, 0.7, 1.0] tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) assert_array_almost_equal(thresholds, [2., 1., 0.7, 0....
def test_roc_curve_drop_intermediate(): # Test that drop_intermediate drops the correct thresholds
y_true = [0, 0, 0, 0, 1, 1] y_score = [0., 0.2, 0.5, 0.6, 0.7, 1.0] tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) assert_array_almost_equal(thresholds, [2., 1., 0.7, 0.]) # Test dropping thresholds with repeating scores y_true = [0, 0, 0, 0, 0, 0, 0, ...
"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), .5) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), .5) def test_roc_curve_drop_intermediate(): # Test that drop_intermediat...
91
91
305
21
70
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_drop_intermediate
test_roc_curve_drop_intermediate
388
402
388
389
116660709adbd4aea8b9a92bae4c575750cabdc8
bigcode/the-stack
train
5f4d846f68276e2e0d355b8b
train
function
def test_ndcg_score(): _, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = - y_true + 1 _test_ndcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_ndcg_score_for(y_true, y_score)
def test_ndcg_score():
_, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = - y_true + 1 _test_ndcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_ndcg_score_for(y_true, y_score)
g_score( y_true, y_score, ignore_ties=ignore_ties) == pytest.approx( expected_dcg_score) assert ndcg_score( y_true, y_score, ignore_ties=ignore_ties) == pytest.approx(1.) def test_ndcg_score():
63
64
89
6
57
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ndcg_score
test_ndcg_score
1,426
1,431
1,426
1,426
600dd2c05677eea60ae7a04a2c2fa5eb80a6c292
bigcode/the-stack
train
6e928dfd9fb781325808afaa
train
function
def test_roc_curve_confidence(): # roc_curve for confidence scores y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred - 0.5) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.90, decimal=2) assert fpr.shape == tpr.shape ...
def test_roc_curve_confidence(): # roc_curve for confidence scores
y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred - 0.5) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.90, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
test_roc_curve_multi(): # roc_curve not applicable for multi-class problems y_true, _, probas_pred = make_prediction(binary=False) with pytest.raises(ValueError): roc_curve(y_true, probas_pred) def test_roc_curve_confidence(): # roc_curve for confidence scores
64
64
102
16
48
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_confidence
test_roc_curve_confidence
232
240
232
233
5522a96a67c6ee067be46bbdc442813649183a39
bigcode/the-stack
train
f3b516e3d7ebef2348c0281b
train
function
def check_zero_or_all_relevant_labels(lrap_score): random_state = check_random_state(0) for n_labels in range(2, 5): y_score = random_state.uniform(size=(1, n_labels)) y_score_ties = np.zeros_like(y_score) # No relevant labels y_true = np.zeros((1, n_labels)) a...
def check_zero_or_all_relevant_labels(lrap_score):
random_state = check_random_state(0) for n_labels in range(2, 5): y_score = random_state.uniform(size=(1, n_labels)) y_score_ties = np.zeros_like(y_score) # No relevant labels y_true = np.zeros((1, n_labels)) assert lrap_score(y_true, y_score) == 1. ass...
2 / 3) assert_almost_equal(lrap_score([[1, 1, 1, 0]], [[0.5, 0.5, 0.5, 0.5]]), 3 / 4) def check_zero_or_all_relevant_labels(lrap_score):
65
65
217
12
53
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_zero_or_all_relevant_labels
check_zero_or_all_relevant_labels
984
1,003
984
984
5cf300a0492cb200ccc45e8db891ded87478c7b2
bigcode/the-stack
train
98f1b978e61077b4ff5f5854
train
function
def test_ranking_loss_ties_handling(): # Tie handling assert_almost_equal(label_ranking_loss([[1, 0]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 1 / 2) as...
def test_ranking_loss_ties_handling(): # Tie handling
assert_almost_equal(label_ranking_loss([[1, 0]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25, 0....
[[0, 1], [0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0], [1]], [[0, 1], [0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0], [1]]) def test_ranking_loss_ties_handling(): # Tie handling
89
90
303
15
74
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_ranking_loss_ties_handling
test_ranking_loss_ties_handling
1,316
1,327
1,316
1,317
7155204a7f3b76b0171239e710b11e361a2e598b
bigcode/the-stack
train
0dfa108215c76ec3ec504e11
train
function
def test_roc_returns_consistency(): # Test whether the returned threshold matches up with tpr # make small toy dataset y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred) # use the given thresholds to determine the tpr tpr_correct =...
def test_roc_returns_consistency(): # Test whether the returned threshold matches up with tpr # make small toy dataset
y_true, _, probas_pred = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, probas_pred) # use the given thresholds to determine the tpr tpr_correct = [] for t in thresholds: tp = np.sum((probas_pred >= t) & y_true) p = np.sum(y_true) tpr_correct.a...
0] == 0 assert fpr[-1] == 1 assert fpr.shape == tpr.shape assert fpr.shape == thr.shape def test_roc_returns_consistency(): # Test whether the returned threshold matches up with tpr # make small toy dataset
64
64
177
28
35
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_returns_consistency
test_roc_returns_consistency
205
221
205
207
3fce10fb69e39e03cadc3c3b99f7e55255783c2a
bigcode/the-stack
train
28a61e9d58598fac1c037b62
train
function
def test_coverage_error(): # Toy case assert_almost_equal(coverage_error([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 0]], [[0.75, 0.25]]), ...
def test_coverage_error(): # Toy case
assert_almost_equal(coverage_error([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 0]], [[0.75, 0.25]]), 0) assert_almost_equal(coverage_error...
in test_common. # For these test samples, the APs are 0.5, 0.75, and 1.0 (default for zero # labels). y_true = np.array([[1, 0, 0, 0], [1, 0, 0, 1], [0, 0, 0, 0]], dtype=np.bool) y_score = np.array([[0.3, 0.4, 0.2, 0.1], [0.1, 0.2, 0.3, 0.4], [0.4, 0....
255
256
1,219
11
244
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_coverage_error
test_coverage_error
1,183
1,228
1,183
1,184
9a8b5262a723bbff3fcefa31ed725504ab25fd65
bigcode/the-stack
train
bfc96e781a52a94510580365
train
function
def check_lrap_error_raised(lrap_score): # Raise value error if not appropriate format with pytest.raises(ValueError): lrap_score([0, 1, 0], [0.25, 0.3, 0.2]) with pytest.raises(ValueError): lrap_score([0, 1, 2], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]])...
def check_lrap_error_raised(lrap_score): # Raise value error if not appropriate format
with pytest.raises(ValueError): lrap_score([0, 1, 0], [0.25, 0.3, 0.2]) with pytest.raises(ValueError): lrap_score([0, 1, 2], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) with pytest.raises(ValueError): lrap_score([(0), (1), (2)], ...
1, n_labels)) assert lrap_score(y_true, y_score) == 1. assert lrap_score(y_true, y_score_ties) == 1. # Degenerate case: only one label assert_almost_equal(lrap_score([[1], [0], [1], [0]], [[0.5], [0.5], [0.5], [0.5]]), 1.) def check_lrap_error_raised(lra...
114
115
386
21
93
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_lrap_error_raised
check_lrap_error_raised
1,006
1,029
1,006
1,007
062157a8ffec39b66adf9c2cd1fc9f6475312233
bigcode/the-stack
train
57c419ec0bcf718f9673a386
train
function
@pytest.mark.parametrize("msg, kwargs", [ ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "samples", "multi_class": "ovo"}), ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "micro", "multi_class": "ovr"})...
@pytest.mark.parametrize("msg, kwargs", [ ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "samples", "multi_class": "ovo"}), ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "micro", "multi_class": "ovr"})...
rng = check_random_state(404) y_score = rng.rand(20, 3) y_prob = softmax(y_score) y_true = rng.randint(0, 3, size=20) with pytest.raises(ValueError, match=msg): roc_auc_score(y_true, y_prob, **kwargs)
@pytest.mark.parametrize("msg, kwargs", [ ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "samples", "multi_class": "ovo"}), ((r"average must be one of \('macro', 'weighted'\) for " r"multiclass problems"), {"average": "micro", "multi_class": "ovr"})...
324
118
394
324
0
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_auc_score_multiclass_error
test_roc_auc_score_multiclass_error
605
630
605
624
657f8bbc0a29dea8232e6a0c98cd1f9700616a82
bigcode/the-stack
train
a06cf82d1301450810935154
train
function
def check_alternative_lrap_implementation(lrap_score, n_classes=5, n_samples=20, random_state=0): _, y_true = make_multilabel_classification(n_features=1, allow_unlabeled=False, ...
def check_alternative_lrap_implementation(lrap_score, n_classes=5, n_samples=20, random_state=0):
_, y_true = make_multilabel_classification(n_features=1, allow_unlabeled=False, random_state=random_state, n_classes=n_classes, ...
<= rank[label] for r in relevant) # Weight by the rank of the actual label score[i] += n_ranked_above / rank[label] score[i] /= relevant.size return score.mean() def check_alternative_lrap_implementation(lrap_score, n_classes=5, n...
75
75
250
28
47
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_alternative_lrap_implementation
check_alternative_lrap_implementation
1,110
1,134
1,110
1,111
0b3a4cf9c7597cab06ad0fd55e072aa19ddba261
bigcode/the-stack
train
b1005bf6329ba0593bb2629f
train
function
def test_roc_curve_end_points(): # Make sure that roc_curve returns a curve start at 0 and ending and # 1 even in corner cases rng = np.random.RandomState(0) y_true = np.array([0] * 50 + [1] * 50) y_pred = rng.randint(3, size=100) fpr, tpr, thr = roc_curve(y_true, y_pred, drop_intermediate...
def test_roc_curve_end_points(): # Make sure that roc_curve returns a curve start at 0 and ending and # 1 even in corner cases
rng = np.random.RandomState(0) y_true = np.array([0] * 50 + [1] * 50) y_pred = rng.randint(3, size=100) fpr, tpr, thr = roc_curve(y_true, y_pred, drop_intermediate=True) assert fpr[0] == 0 assert fpr[-1] == 1 assert fpr.shape == tpr.shape assert fpr.shape == thr.shape
roc_auc_score(y_true, probas_pred)) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape def test_roc_curve_end_points(): # Make sure that roc_curve returns a curve start at 0 and ending and # 1 even in corner cases
64
64
141
35
28
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_end_points
test_roc_curve_end_points
192
202
192
194
8ffd5967625054155b7bb225787dabe711f1fd38
bigcode/the-stack
train
f4af287e43317787942cd59f
train
function
def test_lrap_sample_weighting_zero_labels(): # Degenerate sample labeling (e.g., zero labels for a sample) is a valid # special case for lrap (the sample is considered to achieve perfect # precision), but this case is not tested in test_common. # For these test samples, the APs are 0.5, 0.75, and 1...
def test_lrap_sample_weighting_zero_labels(): # Degenerate sample labeling (e.g., zero labels for a sample) is a valid # special case for lrap (the sample is considered to achieve perfect # precision), but this case is not tested in test_common. # For these test samples, the APs are 0.5, 0.75, and 1...
y_true = np.array([[1, 0, 0, 0], [1, 0, 0, 1], [0, 0, 0, 0]], dtype=np.bool) y_score = np.array([[0.3, 0.4, 0.2, 0.1], [0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1]]) samplewise_lraps = np.array([0.5, 0.75, 1.0]) sample_weight = np.array([1.0, 1.0, 0.0]) ...
def test_lrap_sample_weighting_zero_labels(): # Degenerate sample labeling (e.g., zero labels for a sample) is a valid # special case for lrap (the sample is considered to achieve perfect # precision), but this case is not tested in test_common. # For these test samples, the APs are 0.5, 0.75, and 1...
95
90
300
95
0
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_lrap_sample_weighting_zero_labels
test_lrap_sample_weighting_zero_labels
1,164
1,180
1,164
1,169
a8b0a0af4aef32fb58840ac005376be480c453b2
bigcode/the-stack
train
ebdc6455209439672401a4a0
train
function
@pytest.mark.parametrize("y_true, labels", [(np.array([0, 2, 0, 2]), [0, 1, 2]), (np.array(['a', 'd', 'a', 'd']), ['a', 'b', 'd'])]) def test_multiclass_ovo_roc_auc_toydata_binary(y_true, labels): # Tests the one-vs-one multiclass ROC AUC algorithm for binary y...
@pytest.mark.parametrize("y_true, labels", [(np.array([0, 2, 0, 2]), [0, 1, 2]), (np.array(['a', 'd', 'a', 'd']), ['a', 'b', 'd'])]) def test_multiclass_ovo_roc_auc_toydata_binary(y_true, labels): # Tests the one-vs-one multiclass ROC AUC algorithm for binary y...
y_scores = np.array( [[0.2, 0.0, 0.8], [0.6, 0.0, 0.4], [0.55, 0.0, 0.45], [0.4, 0.0, 0.6]]) # Used to compute the expected output. # Consider labels 0 and 1: # positive label is 0, negative label is 1 score_01 = roc_auc_score([1, 0, 1, 0], [0.2, 0.6, 0.55, 0.4]) # positive label...
"), ovo_weighted_score) @pytest.mark.parametrize("y_true, labels", [(np.array([0, 2, 0, 2]), [0, 1, 2]), (np.array(['a', 'd', 'a', 'd']), ['a', 'b', 'd'])]) def test_multiclass_ovo_roc_auc_toydata_binary(y_true, labels): # Tests the one-vs-one multiclass ROC AU...
121
121
405
115
6
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_multiclass_ovo_roc_auc_toydata_binary
test_multiclass_ovo_roc_auc_toydata_binary
506
531
506
512
238f9505d8c54488d5ccb3b6cdf5620d11b7ab7c
bigcode/the-stack
train
d7715dfbf068e2d8a966fe89
train
function
def _auc(y_true, y_score): """Alternative implementation to check for correctness of `roc_auc_score`.""" pos_label = np.unique(y_true)[1] # Count the number of times positive samples are correctly ranked above # negative samples. pos = y_score[y_true == pos_label] neg = y_score[y_tr...
def _auc(y_true, y_score):
"""Alternative implementation to check for correctness of `roc_auc_score`.""" pos_label = np.unique(y_true)[1] # Count the number of times positive samples are correctly ranked above # negative samples. pos = y_score[y_true == pos_label] neg = y_score[y_true != pos_label] diff_m...
for the binary case? probas_pred = probas_pred[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] return y_true, y_pred, probas_pred ############################################################################### # Tests def _auc(y_true, y_score):
64
64
126
9
54
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_auc
_auc
85
97
85
85
a58b4427b1a09b9bb4fc86e87843f326c7420e1f
bigcode/the-stack
train
bba39d0fdf73ad7c42303953
train
function
def test_auc_errors(): # Incompatible shapes with pytest.raises(ValueError): auc([0.0, 0.5, 1.0], [0.1, 0.2]) # Too few x values with pytest.raises(ValueError): auc([0.0], [0.1]) # x is not in order x = [2, 1, 3, 4] y = [5, 6, 7, 8] error_message = ("x is ne...
def test_auc_errors(): # Incompatible shapes
with pytest.raises(ValueError): auc([0.0, 0.5, 1.0], [0.1, 0.2]) # Too few x values with pytest.raises(ValueError): auc([0.0], [0.1]) # x is not in order x = [2, 1, 3, 4] y = [5, 6, 7, 8] error_message = ("x is neither increasing nor decreasing : " ...
auc(x, y), 1) x = [0, 0.5, 1] y = [0, 0.5, 1] assert_array_almost_equal(auc(x, y), 0.5) def test_auc_errors(): # Incompatible shapes
64
64
149
11
53
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_auc_errors
test_auc_errors
436
451
436
437
1215edb108f0e4208384db8354722aba79554962
bigcode/the-stack
train
9cc6a0acbc166181b6dafc53
train
function
def test_score_scale_invariance(): # Test that average_precision_score and roc_auc_score are invariant by # the scaling or shifting of probabilities # This test was expanded (added scaled_down) in response to github # issue #3864 (and others), where overly aggressive rounding was causing # prob...
def test_score_scale_invariance(): # Test that average_precision_score and roc_auc_score are invariant by # the scaling or shifting of probabilities # This test was expanded (added scaled_down) in response to github # issue #3864 (and others), where overly aggressive rounding was causing # prob...
y_true, _, probas_pred = make_prediction(binary=True) roc_auc = roc_auc_score(y_true, probas_pred) roc_auc_scaled_up = roc_auc_score(y_true, 100 * probas_pred) roc_auc_scaled_down = roc_auc_score(y_true, 1e-6 * probas_pred) roc_auc_shifted = roc_auc_score(y_true, probas_pred - 10) assert ...
_precision_score(y_true, y_pred, pos_label=0) def test_score_scale_invariance(): # Test that average_precision_score and roc_auc_score are invariant by # the scaling or shifting of probabilities # This test was expanded (added scaled_down) in response to github # issue #3864 (and others), where over...
89
89
298
76
13
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_score_scale_invariance
test_score_scale_invariance
903
925
903
908
b0518872dd2c266e0b54dc465c37eba159a7b90e
bigcode/the-stack
train
21e533e92d0139d421d0713c
train
function
@pytest.mark.parametrize('n_samples', (1, 2, 8, 20)) @pytest.mark.parametrize('n_classes', (2, 5, 10)) @pytest.mark.parametrize('random_state', range(1)) def test_alternative_lrap_implementation(n_samples, n_classes, random_state): check_alternative_lrap_implementation( label_ranking_average_p...
@pytest.mark.parametrize('n_samples', (1, 2, 8, 20)) @pytest.mark.parametrize('n_classes', (2, 5, 10)) @pytest.mark.parametrize('random_state', range(1)) def test_alternative_lrap_implementation(n_samples, n_classes, random_state):
check_alternative_lrap_implementation( label_ranking_average_precision_score, n_classes, n_samples, random_state)
) @pytest.mark.parametrize('n_samples', (1, 2, 8, 20)) @pytest.mark.parametrize('n_classes', (2, 5, 10)) @pytest.mark.parametrize('random_state', range(1)) def test_alternative_lrap_implementation(n_samples, n_classes, random_state):
64
64
90
63
1
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_alternative_lrap_implementation
test_alternative_lrap_implementation
1,154
1,161
1,154
1,158
186962c2231642ab9ddc6d043c98dbf9b8f84e60
bigcode/the-stack
train
8d34dd6c5d24343038137735
train
function
@pytest.mark.parametrize('drop', [True, False]) def test_roc_curve(drop): # Test Area under Receiver Operating Characteristic (ROC) curve y_true, _, probas_pred = make_prediction(binary=True) expected_auc = _auc(y_true, probas_pred) fpr, tpr, thresholds = roc_curve(y_true, probas_pred, ...
@pytest.mark.parametrize('drop', [True, False]) def test_roc_curve(drop): # Test Area under Receiver Operating Characteristic (ROC) curve
y_true, _, probas_pred = make_prediction(binary=True) expected_auc = _auc(y_true, probas_pred) fpr, tpr, thresholds = roc_curve(y_true, probas_pred, drop_intermediate=drop) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, expected_auc, decimal=2)...
2 - fpr1 return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area)) @pytest.mark.parametrize('drop', [True, False]) def test_roc_curve(drop): # Test Area under Receiver Operating Characteristic (ROC) curve
63
64
150
32
31
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve
test_roc_curve
177
189
177
179
089c5f46140e74df6f26fb6cd989ebbbbe58c08d
bigcode/the-stack
train
106d5a4a29fb68b6d5a38d78
train
function
@pytest.mark.parametrize("curve_func", [ precision_recall_curve, roc_curve, ]) def test_binary_clf_curve_implicit_pos_label(curve_func): # Check that using string class labels raises an informative # error for any supported string dtype: msg = ("y_true takes value in {'a', 'b'} and pos_label ...
@pytest.mark.parametrize("curve_func", [ precision_recall_curve, roc_curve, ]) def test_binary_clf_curve_implicit_pos_label(curve_func): # Check that using string class labels raises an informative # error for any supported string dtype:
msg = ("y_true takes value in {'a', 'b'} and pos_label is " "not specified: either make y_true take " "value in {0, 1} or {-1, 1} or pass pos_label " "explicitly.") with pytest.raises(ValueError, match=msg): roc_curve(np.array(["a", "b"], dtype='<U1'), [0., 1.]) ...
, 3, size=10) y_pred = rng.rand(10) msg = "multiclass format is not supported" with pytest.raises(ValueError, match=msg): precision_recall_curve(y_true, y_pred) with pytest.raises(ValueError, match=msg): roc_curve(y_true, y_pred) @pytest.mark.parametrize("curve_func", [ pr...
125
125
419
54
71
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_binary_clf_curve_implicit_pos_label
test_binary_clf_curve_implicit_pos_label
678
710
678
684
70d8f3b37c39e7632d89d8ad374ea15ce7d08c3c
bigcode/the-stack
train
91828fe2c24d24f091a1bede
train
function
def test_average_precision_constant_values(): # Check the average_precision_score of a constant predictor is # the TPR # Generate a dataset with 25% of positives y_true = np.zeros(100, dtype=int) y_true[::4] = 1 # And a constant score y_score = np.ones(100) # The precision is t...
def test_average_precision_constant_values(): # Check the average_precision_score of a constant predictor is # the TPR # Generate a dataset with 25% of positives
y_true = np.zeros(100, dtype=int) y_true[::4] = 1 # And a constant score y_score = np.ones(100) # The precision is then the fraction of positive whatever the recall # is, as there is only one threshold: assert average_precision_score(y_true, y_score) == .25
1]]) assert_almost_equal(average_precision_score(y_true, y_score, average="weighted"), 1) def test_average_precision_constant_values(): # Check the average_precision_score of a constant predictor is # the TPR # Generate a dataset with 25% of positives
64
64
117
38
26
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_average_precision_constant_values
test_average_precision_constant_values
871
882
871
875
b7f4eecbc3065970b38b4cc0b800b4d74c9ae8be
bigcode/the-stack
train
32668e40dd12d7d418420ac1
train
function
def test_average_precision_score_pos_label_errors(): # Raise an error when pos_label is not in binary y_true y_true = np.array([0, 1]) y_pred = np.array([0, 1]) error_message = ("pos_label=2 is invalid. Set it to a label in y_true.") with pytest.raises(ValueError, match=error_message): ...
def test_average_precision_score_pos_label_errors(): # Raise an error when pos_label is not in binary y_true
y_true = np.array([0, 1]) y_pred = np.array([0, 1]) error_message = ("pos_label=2 is invalid. Set it to a label in y_true.") with pytest.raises(ValueError, match=error_message): average_precision_score(y_true, y_pred, pos_label=2) # Raise an error for multilabel-indicator y_true with ...
And a constant score y_score = np.ones(100) # The precision is then the fraction of positive whatever the recall # is, as there is only one threshold: assert average_precision_score(y_true, y_score) == .25 def test_average_precision_score_pos_label_errors(): # Raise an error when pos_label is ...
78
78
263
24
53
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_average_precision_score_pos_label_errors
test_average_precision_score_pos_label_errors
885
900
885
886
ba6c04a92b25d44d9761b236b70bbdab34d4d049
bigcode/the-stack
train
e94d367af5b5368285a97470
train
function
@pytest.mark.parametrize( 'check', (check_lrap_toy, check_lrap_without_tie_and_increasing_score, check_lrap_only_ties, check_zero_or_all_relevant_labels)) @pytest.mark.parametrize( 'func', (label_ranking_average_precision_score, _my_lrap)) def test_lab...
@pytest.mark.parametrize( 'check', (check_lrap_toy, check_lrap_without_tie_and_increasing_score, check_lrap_only_ties, check_zero_or_all_relevant_labels)) @pytest.mark.parametrize( 'func', (label_ranking_average_precision_score, _my_lrap)) def test_lab...
check(func)
@pytest.mark.parametrize( 'check', (check_lrap_toy, check_lrap_without_tie_and_increasing_score, check_lrap_only_ties, check_zero_or_all_relevant_labels)) @pytest.mark.parametrize( 'func', (label_ranking_average_precision_score, _my_lrap)) def test_lab...
78
64
82
78
0
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_label_ranking_avp
test_label_ranking_avp
1,137
1,147
1,137
1,146
dfdf1b7115bf31c3903437b6606ef85e591064d0
bigcode/the-stack
train
8c5f9b95d2d67e6c5b2119e0
train
function
def test_label_ranking_loss(): assert_almost_equal(label_ranking_loss([[0, 1]], [[0.25, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_r...
def test_label_ranking_loss():
assert_almost_equal(label_ranking_loss([[0, 1]], [[0.25, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25,...
most_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(c...
256
256
914
7
249
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_label_ranking_loss
test_label_ranking_loss
1,247
1,297
1,247
1,247
1a6ba9b996b73e5a5025036e6b2b4599679a5923
bigcode/the-stack
train
958cd44ce9849bf96e820bdd
train
function
def check_lrap_without_tie_and_increasing_score(lrap_score): # Check that Label ranking average precision works for various # Basic check with increasing label space size and decreasing score for n_labels in range(2, 10): y_score = n_labels - (np.arange(n_labels).reshape((1, n_labels)) + 1) ...
def check_lrap_without_tie_and_increasing_score(lrap_score): # Check that Label ranking average precision works for various # Basic check with increasing label space size and decreasing score
for n_labels in range(2, 10): y_score = n_labels - (np.arange(n_labels).reshape((1, n_labels)) + 1) # First and last y_true = np.zeros((1, n_labels)) y_true[0, 0] = 1 y_true[0, -1] = 1 assert_almost_equal(lrap_score(y_true, y_score), ...
y_true[0, pos:pos + n_relevant] = 1 assert_almost_equal(lrap_score(y_true, y_score), n_relevant / n_labels) def check_lrap_without_tie_and_increasing_score(lrap_score): # Check that Label ranking average precision works for various # Basic ...
80
80
268
40
40
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_lrap_without_tie_and_increasing_score
check_lrap_without_tie_and_increasing_score
1,048
1,069
1,048
1,050
b528c907aaf8e37b48be6783c6d4e9e4dcc0d384
bigcode/the-stack
train
de3e58907297854ffe577d2f
train
function
def check_lrap_only_ties(lrap_score): # Check tie handling in score # Basic check with only ties and increasing label space for n_labels in range(2, 10): y_score = np.ones((1, n_labels)) # Check for growing number of consecutive relevant for n_relevant in range(1, n_labels): ...
def check_lrap_only_ties(lrap_score): # Check tie handling in score # Basic check with only ties and increasing label space
for n_labels in range(2, 10): y_score = np.ones((1, n_labels)) # Check for growing number of consecutive relevant for n_relevant in range(1, n_labels): # Check for a bunch of positions for pos in range(n_labels - n_relevant): y_true = np.zeros(...
1]]) with pytest.raises(ValueError): lrap_score([[0, 1], [0, 1]], [[0], [1]]) def check_lrap_only_ties(lrap_score): # Check tie handling in score # Basic check with only ties and increasing label space
63
64
151
31
32
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_lrap_only_ties
check_lrap_only_ties
1,032
1,045
1,032
1,034
1838adc63b27d8adfea05918025909698db20b62
bigcode/the-stack
train
aca7c0cbe97290a30b8a07d0
train
function
def test_auc(): # Test Area Under Curve (AUC) computation x = [0, 1] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0, 0] y = [0, 1, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [0, 1...
def test_auc(): # Test Area Under Curve (AUC) computation
x = [0, 1] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0, 0] y = [0, 1, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [0, 1] y = [1, 1] assert_array_almost_equal(auc(x, y), 1) ...
(y_true, y_score, sample_weight=sample_weight) assert (np.diff(fpr) < 0).sum() == 0 assert (np.diff(tpr) < 0).sum() == 0 def test_auc(): # Test Area Under Curve (AUC) computation
64
64
205
16
47
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_auc
test_auc
417
433
417
418
49328e5d2281134093d7fc765ec99833f2129e38
bigcode/the-stack
train
f3db3fb07be401452322df1e
train
function
def _partial_roc_auc_score(y_true, y_predict, max_fpr): """Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """ def _partial_roc(y_true, y_predict, max_fpr): fpr, tpr, _ = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] ...
def _partial_roc_auc_score(y_true, y_predict, max_fpr):
"""Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """ def _partial_roc(y_true, y_predict, max_fpr): fpr, tpr, _ = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr ...
_precision>`_ """ precision, recall, threshold = precision_recall_curve(y_true, y_score) precision = list(reversed(precision)) recall = list(reversed(recall)) average_precision = 0 for i in range(1, len(precision)): average_precision += precision[i] * (recall[i] - recall[i - 1]) ...
101
101
339
17
83
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_partial_roc_auc_score
_partial_roc_auc_score
149
174
149
149
47a4b8065849e97c2c46597b00c8b95e3ba5b885
bigcode/the-stack
train
7dddc241b89d07951a91b60a
train
function
def test_precision_recall_curve(): y_true, _, probas_pred = make_prediction(binary=True) _test_precision_recall_curve(y_true, probas_pred) # Use {-1, 1} for labels; make sure original labels aren't modified y_true[np.where(y_true == 0)] = -1 y_true_copy = y_true.copy() _test_precision_re...
def test_precision_recall_curve():
y_true, _, probas_pred = make_prediction(binary=True) _test_precision_recall_curve(y_true, probas_pred) # Use {-1, 1} for labels; make sure original labels aren't modified y_true[np.where(y_true == 0)] = -1 y_true_copy = y_true.copy() _test_precision_recall_curve(y_true, probas_pred) ...
roc_curve([0, 1, 1, 0], y_pred) float_curve = roc_curve([0., 1., 1., 0.], y_pred) for int_curve_part, float_curve_part in zip(int_curve, float_curve): np.testing.assert_allclose(int_curve_part, float_curve_part) def test_precision_recall_curve():
77
77
259
7
70
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_precision_recall_curve
test_precision_recall_curve
713
730
713
713
795cbaaa126052f1c6ae27d7da928e21a575953d
bigcode/the-stack
train
5ef9a7b327489d1173337f5e
train
function
def _average_precision_slow(y_true, y_score): """A second alternative implementation of average precision that closely follows the Wikipedia article's definition (see References). This should give identical results as `average_precision_score` for all inputs. References ---------- .. [1]...
def _average_precision_slow(y_true, y_score):
"""A second alternative implementation of average precision that closely follows the Wikipedia article's definition (see References). This should give identical results as `average_precision_score` for all inputs. References ---------- .. [1] `Wikipedia entry for the Average precision ...
j in range(0, i + 1): if y_true[j] == pos_label: prec += 1.0 prec /= (i + 1.0) score += prec return score / n_pos def _average_precision_slow(y_true, y_score):
64
64
165
12
51
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_average_precision_slow
_average_precision_slow
130
146
130
130
6444378f9ff76e8db6109ace76b5cda2fa5fb5a4
bigcode/the-stack
train
512c2fcc9e3da5abc395d17b
train
function
def test_lrap_error_raised(): check_lrap_error_raised(label_ranking_average_precision_score)
def test_lrap_error_raised():
check_lrap_error_raised(label_ranking_average_precision_score)
_score, check_lrap_only_ties, check_zero_or_all_relevant_labels)) @pytest.mark.parametrize( 'func', (label_ranking_average_precision_score, _my_lrap)) def test_label_ranking_avp(check, func): check(func) def test_lrap_error_raised():
64
64
22
8
56
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_lrap_error_raised
test_lrap_error_raised
1,150
1,151
1,150
1,150
7cf98cb87dc6e0e7b664ce05abba95f94749420e
bigcode/the-stack
train
535bc0acae9bde597f5971c1
train
function
def _average_precision(y_true, y_score): """Alternative implementation to check for correctness of `average_precision_score`. Note that this implementation fails on some edge cases. For example, for constant predictions e.g. [0.5, 0.5, 0.5], y_true = [1, 0, 0] returns an average precision of ...
def _average_precision(y_true, y_score):
"""Alternative implementation to check for correctness of `average_precision_score`. Note that this implementation fails on some edge cases. For example, for constant predictions e.g. [0.5, 0.5, 0.5], y_true = [1, 0, 0] returns an average precision of 0.33... but y_true = [0, 0, 1] return...
pos = y_score[y_true == pos_label] neg = y_score[y_true != pos_label] diff_matrix = pos.reshape(1, -1) - neg.reshape(-1, 1) n_correct = np.sum(diff_matrix > 0) return n_correct / float(len(pos) * len(neg)) def _average_precision(y_true, y_score):
79
80
269
10
69
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_average_precision
_average_precision
100
127
100
100
70a81b144861cb889fd05544e5d3ff3a3e56cc54
bigcode/the-stack
train
0d38ef1f1b285c5223b21640
train
function
def check_lrap_toy(lrap_score): # Check on several small example that it works assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1]], [[0.75, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[1, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(lrap_sc...
def check_lrap_toy(lrap_score): # Check on several small example that it works
assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1]], [[0.75, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[1, 1]], [[0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1,...
# problems for users with very small y_score values y_true, _, probas_pred = make_prediction(binary=True) roc_auc = roc_auc_score(y_true, probas_pred) roc_auc_scaled_up = roc_auc_score(y_true, 100 * probas_pred) roc_auc_scaled_down = roc_auc_score(y_true, 1e-6 * probas_pred) roc_auc_shi...
256
256
1,391
21
234
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
check_lrap_toy
check_lrap_toy
928
981
928
929
25f574015eda69289cb17c2b75ff490742fa6594
bigcode/the-stack
train
6ea295b881ad459dfee97378
train
function
def test_auc_score_non_binary_class(): # Test that roc_auc_score function returns an error when trying # to compute AUC for non-binary class values. rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") err_msg = ...
def test_auc_score_non_binary_class(): # Test that roc_auc_score function returns an error when trying # to compute AUC for non-binary class values.
rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") err_msg = "ROC AUC score is not defined" with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.ones(10, dtype="int")...
404) y_score = rng.rand(20, 3) y_prob = softmax(y_score) y_true = rng.randint(0, 3, size=20) with pytest.raises(ValueError, match=msg): roc_auc_score(y_true, y_prob, **kwargs) def test_auc_score_non_binary_class(): # Test that roc_auc_score function returns an error when trying # ...
98
98
329
35
63
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_auc_score_non_binary_class
test_auc_score_non_binary_class
633
662
633
635
a350f3ccc2dc17055cb2e697709c1803fe236fed
bigcode/the-stack
train
645ea2e1217ee338536f87e2
train
function
def test_partial_roc_auc_score(): # Check `roc_auc_score` for max_fpr != `None` y_true = np.array([0, 0, 1, 1]) assert roc_auc_score(y_true, y_true, max_fpr=1) == 1 assert roc_auc_score(y_true, y_true, max_fpr=0.001) == 1 with pytest.raises(ValueError): assert roc_auc_score(y_true, y_t...
def test_partial_roc_auc_score(): # Check `roc_auc_score` for max_fpr != `None`
y_true = np.array([0, 0, 1, 1]) assert roc_auc_score(y_true, y_true, max_fpr=1) == 1 assert roc_auc_score(y_true, y_true, max_fpr=0.001) == 1 with pytest.raises(ValueError): assert roc_auc_score(y_true, y_true, max_fpr=-0.1) with pytest.raises(ValueError): assert roc_auc_score(...
_dcg_sample_scores(y_true, y_score)[~all_zero] / _dcg_sample_scores(y_true, y_true)[~all_zero]) assert score[all_zero] == pytest.approx(np.zeros(all_zero.sum())) assert ideal.shape == (y_true.shape[0], ) assert score.shape == (y_true.shape[0], ) def test_partial_roc_auc_score(): # C...
101
102
343
24
77
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_partial_roc_auc_score
test_partial_roc_auc_score
1,449
1,471
1,449
1,450
ba1932087b378a5e26f0ece44985a30546452a95
bigcode/the-stack
train
d5735697726259a0fc01e626
train
function
def test_coverage_tie_handling(): assert_almost_equal(coverage_error([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[1, 0]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.5, 0.5]]), 2) assert_...
def test_coverage_tie_handling():
assert_almost_equal(coverage_error([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[1, 0]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 0,...
1, 3], [0, 2, 0]]), (1 + 3 + 3) / 3.) assert_almost_equal(coverage_error([[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]]), (1 + 3 + 3) / 3.) def test_coverage_tie_handling():
121
122
409
9
112
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_coverage_tie_handling
test_coverage_tie_handling
1,231
1,244
1,231
1,231
acd9ffbb66f9aa297bb8848c6bc13aafe26bd695
bigcode/the-stack
train
eedba843c6cc4708a28ac118
train
function
def test_roc_curve_hard(): # roc_curve for hard decisions y_true, pred, probas_pred = make_prediction(binary=True) # always predict one trivial_pred = np.ones(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_a...
def test_roc_curve_hard(): # roc_curve for hard decisions
y_true, pred, probas_pred = make_prediction(binary=True) # always predict one trivial_pred = np.ones(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.50, decimal=2) assert fpr.shape == tpr.shape ass...
roc_curve(y_true, probas_pred - 0.5) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.90, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape def test_roc_curve_hard(): # roc_curve for hard decisions
79
79
265
16
62
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_hard
test_roc_curve_hard
243
268
243
244
82f910605af9f57e9c474cbf0b30137507bfa3a5
bigcode/the-stack
train
b4915a77e13b0ba12704bb0a
train
function
def test_precision_recall_curve_toydata(): with np.errstate(all="raise"): # Binary classification y_true = [0, 1] y_score = [0, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, ...
def test_precision_recall_curve_toydata():
with np.errstate(all="raise"): # Binary classification y_true = [0, 1] y_score = [0, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [1, 1]) assert_array_almost_equal(r...
_recall_curve(y_true, probas_pred) precision_recall_auc = _average_precision_slow(y_true, probas_pred) assert_array_almost_equal(precision_recall_auc, 0.859, 3) assert_array_almost_equal(precision_recall_auc, average_precision_score(y_true, probas_pred)) # `_average_pr...
255
256
1,330
10
245
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_precision_recall_curve_toydata
test_precision_recall_curve_toydata
758
868
758
758
b5c80ee7c3b3ae4bc5ab48d8ec3231a43a68855b
bigcode/the-stack
train
1064d8a52238de79766757bf
train
function
def _test_dcg_score_for(y_true, y_score): discount = np.log2(np.arange(y_true.shape[1]) + 2) ideal = _dcg_sample_scores(y_true, y_true) score = _dcg_sample_scores(y_true, y_score) assert (score <= ideal).all() assert (_dcg_sample_scores(y_true, y_true, k=5) <= ideal).all() assert ideal.sha...
def _test_dcg_score_for(y_true, y_score):
discount = np.log2(np.arange(y_true.shape[1]) + 2) ideal = _dcg_sample_scores(y_true, y_true) score = _dcg_sample_scores(y_true, y_score) assert (score <= ideal).all() assert (_dcg_sample_scores(y_true, y_true, k=5) <= ideal).all() assert ideal.shape == (y_true.shape[0], ) assert score...
_test_dcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_dcg_score_for(y_true, y_score) def _test_dcg_score_for(y_true, y_score):
64
64
144
13
51
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
_test_dcg_score_for
_test_dcg_score_for
1,338
1,347
1,338
1,338
4d374395fb91a5201aee591f857462f097998352
bigcode/the-stack
train
863f372c32daa6f32b57911e
train
function
def test_roc_curve_multi(): # roc_curve not applicable for multi-class problems y_true, _, probas_pred = make_prediction(binary=False) with pytest.raises(ValueError): roc_curve(y_true, probas_pred)
def test_roc_curve_multi(): # roc_curve not applicable for multi-class problems
y_true, _, probas_pred = make_prediction(binary=False) with pytest.raises(ValueError): roc_curve(y_true, probas_pred)
to see if the thresholds' order was correct assert_array_almost_equal(tpr, tpr_correct, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape def test_roc_curve_multi(): # roc_curve not applicable for multi-class problems
64
64
49
18
45
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_roc_curve_multi
test_roc_curve_multi
224
229
224
225
3a737e2a547f09cbc38f50ce827b032267695196
bigcode/the-stack
train
fc4012e10495823ddff07682
train
function
@pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 2, 2]), None), (["a", "b", "c", "c"], None), ([0, 1, 2, 2], [0, 1, 2]), (["a", "b", "c", "c"], ["a", "b", "c"])]) def test_multiclass_ovr_roc_auc_toydata(y_true, labels): # Tests the unweighted, one-vs-rest multiclass ROC AU...
@pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 2, 2]), None), (["a", "b", "c", "c"], None), ([0, 1, 2, 2], [0, 1, 2]), (["a", "b", "c", "c"], ["a", "b", "c"])]) def test_multiclass_ovr_roc_auc_toydata(y_true, labels): # Tests the unweighted, one-vs-rest multiclass ROC AU...
y_scores = np.array( [[1.0, 0.0, 0.0], [0.1, 0.5, 0.4], [0.1, 0.1, 0.8], [0.3, 0.3, 0.4]]) # Compute the expected result by individually computing the 'one-vs-rest' # ROC AUC scores for classes 0, 1, and 2. out_0 = roc_auc_score([1, 0, 0, 0], y_scores[:, 0]) out_1 = roc_auc_score([0, 1,...
) @pytest.mark.parametrize( "y_true, labels", [(np.array([0, 1, 2, 2]), None), (["a", "b", "c", "c"], None), ([0, 1, 2, 2], [0, 1, 2]), (["a", "b", "c", "c"], ["a", "b", "c"])]) def test_multiclass_ovr_roc_auc_toydata(y_true, labels): # Tests the unweighted, one-vs-rest multiclass ROC ...
145
145
484
144
1
obulrdy6881/Drowsinss
my_env/Lib/site-packages/sklearn/metrics/tests/test_ranking.py
Python
test_multiclass_ovr_roc_auc_toydata
test_multiclass_ovr_roc_auc_toydata
534
565
534
542
dfe7f00cb37f141c717f93e75c0d692df097b160
bigcode/the-stack
train
28e03eec39f7b327a2634bed
train
class
class TripleSquare(unittest.TestCase): def content_helper(self, countlist): main() result=get_out().split('\n') l=len(result) self.assertIn(l, countlist, msg="Wrong number of printed lines: %i!" % l) for i, line in zip(range(l), result): j = i + 1 ...
class TripleSquare(unittest.TestCase):
def content_helper(self, countlist): main() result=get_out().split('\n') l=len(result) self.assertIn(l, countlist, msg="Wrong number of printed lines: %i!" % l) for i, line in zip(range(l), result): j = i + 1 pattern = r"triple\((\d+)\)==(\d+) square\(...
#!/usr/bin/env python3 import re import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name="src.triple_square" main = load(module_name, "main") triple = load(module_name, "triple") square = load(module_name, "square") class TripleSquare(unittest.TestCase)...
80
183
611
8
72
Melimet/DAP2020
hy-data-analysis-with-python-spring-2020/part01-e06_triple_square/test/test_triple_square.py
Python
TripleSquare
TripleSquare
16
68
16
18
2172e4f466e2c48809793d5951c4238eed7c2b91
bigcode/the-stack
train
050c5d94b819b8f43c9228a0
train
function
def extract_version(txt): """This function tries to extract the version from the help text of any program.""" words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x an...
def extract_version(txt):
"""This function tries to extract the version from the help text of any program.""" words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x and x[0].isdigit(): ...
return wrapped def __enter__(self): """used by the :keyword:`with` statement""" self.start() return self def __exit__(self, *exc_info): """used by the :keyword:`with` statement""" self.stop() def extract_version(txt):
64
64
98
5
59
zahed3795/Super-Automation
automation/virtual_display/easyprocess.py
Python
extract_version
extract_version
416
428
416
416
454fc3e6ea67d5fe46602b5d3b1b8f57aeb484cc
bigcode/the-stack
train
5b7f1adb2285da359a1dc6ff
train
class
class EasyProcessError(Exception): def __init__(self, easy_process, msg=''): self.easy_process = easy_process self.msg = msg def __str__(self): return self.msg + ' ' + repr(self.easy_process)
class EasyProcessError(Exception):
def __init__(self, easy_process, msg=''): self.easy_process = easy_process self.msg = msg def __str__(self): return self.msg + ' ' + repr(self.easy_process)
import os.path import platform import signal import subprocess import tempfile import threading import time log = logging.getLogger(__name__) log.setLevel(logging.ERROR) SECTION_LINK = 'link' POLL_TIME = 0.1 USE_POLL = 0 class EasyProcessError(Exception):
64
64
53
6
57
zahed3795/Super-Automation
automation/virtual_display/easyprocess.py
Python
EasyProcessError
EasyProcessError
22
29
22
23
395cc67f54696a2e4e822a07a34b687cc1adfd58
bigcode/the-stack
train
8d2a5d4d2b79e5b8b03ee2f6
train
class
class EasyProcessCheckInstalledError(Exception): """This exception is raised when a process run by check() returns a non-zero exit status or OSError is raised. """ def __init__(self, easy_process): self.easy_process = easy_process def __str__(self): msg = template % (self.easy_pro...
class EasyProcessCheckInstalledError(Exception):
"""This exception is raised when a process run by check() returns a non-zero exit status or OSError is raised. """ def __init__(self, easy_process): self.easy_process = easy_process def __str__(self): msg = template % (self.easy_process.cmd, self.easy_proc...
, msg=''): self.easy_process = easy_process self.msg = msg def __str__(self): return self.msg + ' ' + repr(self.easy_process) template = '''cmd=%s OSError=%s Program install error! ''' class EasyProcessCheckInstalledError(Exception):
63
64
165
8
55
zahed3795/Super-Automation
automation/virtual_display/easyprocess.py
Python
EasyProcessCheckInstalledError
EasyProcessCheckInstalledError
37
57
37
38
b6371c33e358f1dc636b04ca149ea66ba9e22b2f
bigcode/the-stack
train
6414bff8002148c6038fc94a
train
class
class EasyProcess(object): """ .. module:: easyprocess simple interface for :mod:`subprocess` shell is not supported (shell=False) .. warning:: unicode is supported only for string list command (Python2.x) (check :mod:`shlex` for more information) :param cmd: string ('ls -l') o...
class EasyProcess(object):
""" .. module:: easyprocess simple interface for :mod:`subprocess` shell is not supported (shell=False) .. warning:: unicode is supported only for string list command (Python2.x) (check :mod:`shlex` for more information) :param cmd: string ('ls -l') or list of strings (['ls','-l...
OLL_TIME = 0.1 USE_POLL = 0 class EasyProcessError(Exception): def __init__(self, easy_process, msg=''): self.easy_process = easy_process self.msg = msg def __str__(self): return self.msg + ' ' + repr(self.easy_process) template = '''cmd=%s OSError=%s Program install error! ''' c...
256
256
2,236
5
250
zahed3795/Super-Automation
automation/virtual_display/easyprocess.py
Python
EasyProcess
EasyProcess
60
413
60
61
096896a122fe2998191a58b2c2fd9810060330c6
bigcode/the-stack
train
a09699c48c83e9ee7844a64a
train
class
class Update(Create): def transform(self, json: dict): # variables countries = json.keys() update_data = [] # we only want to update everything from yesterday onwards.. update_day = datetime.now().date() + timedelta(days=-7) # loop and build array of Stat fo...
class Update(Create):
def transform(self, json: dict): # variables countries = json.keys() update_data = [] # we only want to update everything from yesterday onwards.. update_day = datetime.now().date() + timedelta(days=-7) # loop and build array of Stat for country in countries...
#!/usr/bin/env python3 """ Implementation of updating sqlite db """ from datetime import datetime, timedelta from create import Create, db, Stat class Update(Create):
35
77
258
4
30
Dangandy/covid
backend/db/update.py
Python
Update
Update
10
54
10
10
e5036e1b7a9b9928825e7dced70435f5b9144eba
bigcode/the-stack
train
da2fcd9836a818e2bcb2e11d
train
function
def main(): """ 1. Extract new data from url 2. get last 2 days data ( data here is updated hourly ) 3. insert / update into db """ update = Update() json = update.extract() last_days = update.transform(json) update.load(last_days)
def main():
""" 1. Extract new data from url 2. get last 2 days data ( data here is updated hourly ) 3. insert / update into db """ update = Update() json = update.extract() last_days = update.transform(json) update.load(last_days)
query = Stat.query.get({"id": stat.id}) if query: query.confirmed = stat.confirmed query.deaths = stat.deaths query.recovered = stat.recovered else: db.session.add(stat) # commit db.session.commit() def ...
64
64
69
3
61
Dangandy/covid
backend/db/update.py
Python
main
main
57
66
57
57
82a9d1dbc7dea3366c7273c085adf1990863be00
bigcode/the-stack
train
557ee4ae59a99924163945b1
train
function
def _decode(line, encoding): if isinstance(line, six.text_type): return line try: return line.decode(encoding) except UnicodeDecodeError: return line.decode(encoding, 'replace')
def _decode(line, encoding):
if isinstance(line, six.text_type): return line try: return line.decode(encoding) except UnicodeDecodeError: return line.decode(encoding, 'replace')
return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(tb): length = 0 while tb and not _is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def _decode(line, encoding):
64
64
46
7
56
pzahemszky/haas
haas/result.py
Python
_decode
_decode
67
73
67
67
5b5b5cfcd0c23852afb16695a19b5a1f330eafd2
bigcode/the-stack
train
f4b9745d2ee1513814b58579
train
class
class ResultCollecter(ResultCollector): def __init__(self, *args, **kwargs): super(ResultCollecter, self).__init__(*args, **kwargs) warnings.warn( 'ResultCollecter is deprecated in favour of ResultCollector and ' 'will be removed in the next release.', Deprecation...
class ResultCollecter(ResultCollector):
def __init__(self, *args, **kwargs): super(ResultCollecter, self).__init__(*args, **kwargs) warnings.warn( 'ResultCollecter is deprecated in favour of ResultCollector and ' 'will be removed in the next release.', DeprecationWarning, )
Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True class ResultCollecter(ResultCollector):
64
64
71
7
56
pzahemszky/haas
haas/result.py
Python
ResultCollecter
ResultCollecter
623
630
623
623
b57e17b538df3718e10b1e4d3f04d74a89f54393
bigcode/the-stack
train
d6b4c5bd9d6edd582abd0fc1
train
function
def _is_relevant_tb_level(tb): return '__unittest' in tb.tb_frame.f_globals
def _is_relevant_tb_level(tb):
return '__unittest' in tb.tb_frame.f_globals
skipped = 6 _successful_results = set([TestCompletionStatus.success, TestCompletionStatus.expected_failure, TestCompletionStatus.skipped]) STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' def _is_relevant_tb_level(tb):
64
64
22
9
55
pzahemszky/haas
haas/result.py
Python
_is_relevant_tb_level
_is_relevant_tb_level
55
56
55
55
3c965c0ba9fd2b0f858a43d6b361f7627c7516b1
bigcode/the-stack
train
184416958c38cd9b77255087
train
class
class TestResult(object): """Container object for all information related to the run of a single test. This contains the test itself, the actual status including the reason or error associated with status, along with timing information. """ def __init__(self, test_class, test_method_name, sta...
class TestResult(object):
"""Container object for all information related to the run of a single test. This contains the test itself, the actual status including the reason or error associated with status, along with timing information. """ def __init__(self, test_class, test_method_name, status, duration, ...
, 'duration'): return NotImplemented return self.duration < other.duration def __le__(self, other): return not (self > other) def __gt__(self, other): if not hasattr(other, 'duration'): return NotImplemented return self.duration > other.duration def...
210
210
703
5
205
pzahemszky/haas
haas/result.py
Python
TestResult
TestResult
208
307
208
208
ca0cb0716ec43f87bce0bf989dd8e4d5bc096b0e
bigcode/the-stack
train
efc2c6297431f34748ed2f8b
train
function
def _count_relevant_tb_levels(tb): length = 0 while tb and not _is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length
def _count_relevant_tb_levels(tb):
length = 0 while tb and not _is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length
_failure, TestCompletionStatus.skipped]) STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' def _is_relevant_tb_level(tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(tb):
64
64
45
9
54
pzahemszky/haas
haas/result.py
Python
_count_relevant_tb_levels
_count_relevant_tb_levels
59
64
59
59
4cb10e294b177be3cc50130f263f3f409d60641d
bigcode/the-stack
train
d5fc0afe01d95aef8659d877
train
function
def failfast(method): @wraps(method) def inner(self, *args, **kw): if self.failfast: self.stop() return method(self, *args, **kw) return inner
def failfast(method): @wraps(method)
def inner(self, *args, **kw): if self.failfast: self.stop() return method(self, *args, **kw) return inner
a ``TestResult`` from a dictionary created by :meth:`~.TestResult.to_dict` """ return cls(**data) # Temporary compatibility with unittest's runner separator2 = '-' * 70 # Copied from unittest.result def failfast(method): @wraps(method)
64
64
47
11
52
pzahemszky/haas
haas/result.py
Python
failfast
failfast
315
321
315
316
b608fca1a4181258e532373aac9989f109aba5ad
bigcode/the-stack
train
6149b2ca961852ab9962aabb
train
class
class TestDuration(object): """An orderable representation of the duration of an individual test. """ def __init__(self, start_time, stop_time=None): if stop_time is not None: self._start_time = start_time self._stop_time = stop_time self._duration = stop_time -...
class TestDuration(object):
"""An orderable representation of the duration of an individual test. """ def __init__(self, start_time, stop_time=None): if stop_time is not None: self._start_time = start_time self._stop_time = stop_time self._duration = stop_time - start_time else: ...
, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: # Skip assert*() traceback levels length = _count_relevant...
210
210
701
5
205
pzahemszky/haas
haas/result.py
Python
TestDuration
TestDuration
104
205
104
104
b77035c35864f8a79b2daa4ce38952521f6cb729
bigcode/the-stack
train