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
e376f41090540d4355c15cea
train
class
class BaseTestUserManager( Generic[models.UC, models.UD], BaseUserManager[models.UC, models.UD] ): reset_password_token_secret = "SECRET" verification_token_secret = "SECRET" async def validate_password( self, password: str, user: Union[models.UC, models.UD] ) -> None: if len(passwo...
class BaseTestUserManager( Generic[models.UC, models.UD], BaseUserManager[models.UC, models.UD] ):
reset_password_token_secret = "SECRET" verification_token_secret = "SECRET" async def validate_password( self, password: str, user: Union[models.UC, models.UD] ) -> None: if len(password) < 3: raise InvalidPasswordException( reason="Password should be at leas...
models.BaseUserDB): pass class UserOAuth(User, BaseOAuthAccountMixin): pass class UserDBOAuth(UserOAuth, UserDB): pass class BaseTestUserManager( Generic[models.UC, models.UD], BaseUserManager[models.UC, models.UD] ):
64
64
106
30
33
chatalyan/fastapi-users
tests/conftest.py
Python
BaseTestUserManager
BaseTestUserManager
60
72
60
62
c56cfad1f38c0c3c7ca04fc012ffbb596b47e0e6
bigcode/the-stack
train
9d24a4a00068753f1fe661b1
train
function
@pytest.fixture def async_method_mocker(mocker: MockerFixture) -> AsyncMethodMocker: def _async_method_mocker( object: Any, method: str, return_value: Any = None, ) -> MagicMock: mock: MagicMock = mocker.MagicMock() future: asyncio.Future = asyncio.Future() futur...
@pytest.fixture def async_method_mocker(mocker: MockerFixture) -> AsyncMethodMocker:
def _async_method_mocker( object: Any, method: str, return_value: Any = None, ) -> MagicMock: mock: MagicMock = mocker.MagicMock() future: asyncio.Future = asyncio.Future() future.set_result(return_value) mock.return_value = future mock.side_effec...
session") def event_loop(): """Force the pytest-asyncio loop to be the main one.""" loop = asyncio.get_event_loop() yield loop AsyncMethodMocker = Callable[..., MagicMock] @pytest.fixture def async_method_mocker(mocker: MockerFixture) -> AsyncMethodMocker:
64
64
115
21
43
chatalyan/fastapi-users
tests/conftest.py
Python
async_method_mocker
async_method_mocker
108
126
108
109
bcd9edc5cbdf4fb2526c8b3078bbc24f926482f9
bigcode/the-stack
train
1cd7afb2e3f3723b9e417149
train
function
@pytest.fixture def user_manager(make_user_manager, mock_user_db): return make_user_manager(UserManager, mock_user_db)
@pytest.fixture def user_manager(make_user_manager, mock_user_db):
return make_user_manager(UserManager, mock_user_db)
orgot_password") mocker.spy(user_manager, "on_after_reset_password") mocker.spy(user_manager, "on_after_update") mocker.spy(user_manager, "_update") return user_manager return _make_user_manager @pytest.fixture def user_manager(make_user_manager, mock_user_db):
64
64
26
14
49
chatalyan/fastapi-users
tests/conftest.py
Python
user_manager
user_manager
418
420
418
419
ff368d9fc3db7aedfad29e2a94863e3aa698f862
bigcode/the-stack
train
8acfdd0fa200b5b89df31026
train
function
@pytest.fixture def verified_superuser_oauth() -> UserDBOAuth: return UserDBOAuth( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, oauth_accounts=[], )
@pytest.fixture def verified_superuser_oauth() -> UserDBOAuth:
return UserDBOAuth( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, oauth_accounts=[], )
def verified_superuser() -> UserDB: return UserDB( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, ) @pytest.fixture def verified_superuser_oauth() -> UserDBOAuth:
64
64
61
15
49
chatalyan/fastapi-users
tests/conftest.py
Python
verified_superuser_oauth
verified_superuser_oauth
219
227
219
220
4f3f92cb737cd50b4914f5d06b8fbe5142e4aa0f
bigcode/the-stack
train
889bcbc4e981af8d01a2d29e
train
class
class MockTransport(BearerTransport): def __init__(self, tokenUrl: str): super().__init__(tokenUrl) async def get_logout_response(self, response: Response) -> Any: return None @staticmethod def get_openapi_logout_responses_success() -> OpenAPIResponseType: return {}
class MockTransport(BearerTransport):
def __init__(self, tokenUrl: str): super().__init__(tokenUrl) async def get_logout_response(self, response: Response) -> Any: return None @staticmethod def get_openapi_logout_responses_success() -> OpenAPIResponseType: return {}
_get_user_manager(): return user_manager return _get_user_manager @pytest.fixture def get_user_manager_oauth(user_manager_oauth): def _get_user_manager_oauth(): return user_manager_oauth return _get_user_manager_oauth class MockTransport(BearerTransport):
64
64
70
8
55
chatalyan/fastapi-users
tests/conftest.py
Python
MockTransport
MockTransport
444
453
444
444
4862b259e34932fcb399bd4b3d9dd2938368c730
bigcode/the-stack
train
c00ed7cf35f0a05d2e0486fc
train
function
@pytest.fixture def mock_user_db( user, user_oauth, verified_user, inactive_user, superuser, verified_superuser ) -> BaseUserDatabase: class MockUserDatabase(BaseUserDatabase[UserDB]): async def get(self, id: UUID4) -> Optional[UserDB]: if id == user.id: return user ...
@pytest.fixture def mock_user_db( user, user_oauth, verified_user, inactive_user, superuser, verified_superuser ) -> BaseUserDatabase:
class MockUserDatabase(BaseUserDatabase[UserDB]): async def get(self, id: UUID4) -> Optional[UserDB]: if id == user.id: return user if id == user_oauth.id: return user_oauth if id == verified_user.id: return verified_user ...
-> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service5", access_token="TOKEN", expires_at=1579000751, account_id="verified_superuser_oauth1", account_email="the.real.merlin@camelot.bt", ) @pytest.fixture def mock_user_db( user, user_oauth, verified_user, ...
94
94
314
34
60
chatalyan/fastapi-users
tests/conftest.py
Python
mock_user_db
mock_user_db
285
328
285
288
533655fad92378bc4469ebe7f5573adebd520e7a
bigcode/the-stack
train
eaac074db632959022ae4c2d
train
function
@pytest.fixture def verified_user_oauth(oauth_account4) -> UserDBOAuth: return UserDBOAuth( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=False, oauth_accounts=[oauth_account4], )
@pytest.fixture def verified_user_oauth(oauth_account4) -> UserDBOAuth:
return UserDBOAuth( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=False, oauth_accounts=[oauth_account4], )
def verified_user() -> UserDB: return UserDB( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=True, is_verified=True, ) @pytest.fixture def verified_user_oauth(oauth_account4) -> UserDBOAuth:
64
64
60
18
46
chatalyan/fastapi-users
tests/conftest.py
Python
verified_user_oauth
verified_user_oauth
180
187
180
181
c65892fb5aaec2ca27dcc4450ac40467d90233b3
bigcode/the-stack
train
1059d9bff8cedb51c2fe5ff7
train
function
@pytest.fixture def get_test_client(): async def _get_test_client(app: FastAPI) -> AsyncGenerator[httpx.AsyncClient, None]: async with LifespanManager(app): async with httpx.AsyncClient( app=app, base_url="http://app.io" ) as test_client: yield test_cl...
@pytest.fixture def get_test_client():
async def _get_test_client(app: FastAPI) -> AsyncGenerator[httpx.AsyncClient, None]: async with LifespanManager(app): async with httpx.AsyncClient( app=app, base_url="http://app.io" ) as test_client: yield test_client return _get_test_client
def get_mock_authentication(name: str): return AuthenticationBackend( name=name, transport=MockTransport(tokenUrl="/login"), get_strategy=lambda: MockStrategy(), ) @pytest.fixture def mock_authentication(): return get_mock_authentication(name="mock") @pytest.fixture def get_test_cl...
64
64
79
8
56
chatalyan/fastapi-users
tests/conftest.py
Python
get_test_client
get_test_client
490
499
490
491
c83fb3b05239b2213c1bbafa0e069973f2354f6d
bigcode/the-stack
train
a198b8cd1647ad35a6a594a0
train
class
class UserDBOAuth(UserOAuth, UserDB): pass
class UserDBOAuth(UserOAuth, UserDB):
pass
Create(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate): first_name: Optional[str] class UserDB(User, models.BaseUserDB): pass class UserOAuth(User, BaseOAuthAccountMixin): pass class UserDBOAuth(UserOAuth, UserDB):
64
64
13
10
53
chatalyan/fastapi-users
tests/conftest.py
Python
UserDBOAuth
UserDBOAuth
56
57
56
56
409384dd88c99fb34fe206783a3d2d51c7ce446d
bigcode/the-stack
train
de1160ce90baa214221b44d3
train
function
@pytest.fixture def inactive_user_oauth(oauth_account3) -> UserDBOAuth: return UserDBOAuth( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, oauth_accounts=[oauth_account3], )
@pytest.fixture def inactive_user_oauth(oauth_account3) -> UserDBOAuth:
return UserDBOAuth( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, oauth_accounts=[oauth_account3], )
], ) @pytest.fixture def inactive_user() -> UserDB: return UserDB( email="percival@camelot.bt", hashed_password=angharad_password_hash, is_active=False, ) @pytest.fixture def inactive_user_oauth(oauth_account3) -> UserDBOAuth:
64
64
59
18
46
chatalyan/fastapi-users
tests/conftest.py
Python
inactive_user_oauth
inactive_user_oauth
160
167
160
161
089177932c93928ae8813db03241388c464f0b80
bigcode/the-stack
train
f9d13cac8784fa126010b99f
train
function
@pytest.fixture def user() -> UserDB: return UserDB( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, )
@pytest.fixture def user() -> UserDB:
return UserDB( email="king.arthur@camelot.bt", hashed_password=guinevere_password_hash, )
future mock.side_effect = None setattr(object, method, mock) return mock return _async_method_mocker @pytest.fixture(params=["SECRET", SecretStr("SECRET")]) def secret(request) -> SecretType: return request.param @pytest.fixture def user() -> UserDB:
64
64
39
10
53
chatalyan/fastapi-users
tests/conftest.py
Python
user
user
134
139
134
135
4ec9512fa2ea264bbed0d3ce91f8751e257a108e
bigcode/the-stack
train
ef55c11c7b525211edf680e9
train
class
class UserManagerOAuth(BaseTestUserManager[UserCreate, UserDBOAuth]): user_db_model = UserDBOAuth
class UserManagerOAuth(BaseTestUserManager[UserCreate, UserDBOAuth]):
user_db_model = UserDBOAuth
(password) < 3: raise InvalidPasswordException( reason="Password should be at least 3 characters" ) class UserManager(BaseTestUserManager[UserCreate, UserDB]): user_db_model = UserDB class UserManagerOAuth(BaseTestUserManager[UserCreate, UserDBOAuth]):
64
64
25
16
47
chatalyan/fastapi-users
tests/conftest.py
Python
UserManagerOAuth
UserManagerOAuth
79
80
79
79
af5ea5caba379d1bea044b656cc381f7dc27f310
bigcode/the-stack
train
e5525a893f7a7e2c04afa98c
train
class
class UserManager(BaseTestUserManager[UserCreate, UserDB]): user_db_model = UserDB
class UserManager(BaseTestUserManager[UserCreate, UserDB]):
user_db_model = UserDB
password: str, user: Union[models.UC, models.UD] ) -> None: if len(password) < 3: raise InvalidPasswordException( reason="Password should be at least 3 characters" ) class UserManager(BaseTestUserManager[UserCreate, UserDB]):
64
64
22
14
50
chatalyan/fastapi-users
tests/conftest.py
Python
UserManager
UserManager
75
76
75
75
d1f00086b043f3c7aa25193402c4f1c76388b206
bigcode/the-stack
train
778575856c83e782f71463bf
train
class
class UserCreate(models.BaseUserCreate): first_name: Optional[str]
class UserCreate(models.BaseUserCreate):
first_name: Optional[str]
iane") lancelot_password_hash = get_password_hash("lancelot") excalibur_password_hash = get_password_hash("excalibur") class User(models.BaseUser): first_name: Optional[str] last_name: Optional[str] picture: Optional[str] class UserCreate(models.BaseUserCreate):
64
64
15
8
56
chatalyan/fastapi-users
tests/conftest.py
Python
UserCreate
UserCreate
40
41
40
40
4e54a8c9a096d97f536435edb7b3cc5c88f8bd45
bigcode/the-stack
train
11cb8ab021867d5bcf5d8d7e
train
function
@pytest.fixture def mock_user_db_oauth( user_oauth, verified_user_oauth, inactive_user_oauth, superuser_oauth, verified_superuser_oauth, ) -> BaseUserDatabase: class MockUserDatabase(BaseUserDatabase[UserDBOAuth]): async def get(self, id: UUID4) -> Optional[UserDBOAuth]: if i...
@pytest.fixture def mock_user_db_oauth( user_oauth, verified_user_oauth, inactive_user_oauth, superuser_oauth, verified_superuser_oauth, ) -> BaseUserDatabase:
class MockUserDatabase(BaseUserDatabase[UserDBOAuth]): async def get(self, id: UUID4) -> Optional[UserDBOAuth]: if id == user_oauth.id: return user_oauth if id == verified_user_oauth.id: return verified_user_oauth if id == inactive_user_oau...
return inactive_user if lower_email == superuser.email.lower(): return superuser if lower_email == verified_superuser.email.lower(): return verified_superuser return None async def create(self, user: UserDB) -> UserDB: return user...
149
149
497
46
103
chatalyan/fastapi-users
tests/conftest.py
Python
mock_user_db_oauth
mock_user_db_oauth
331
394
331
338
15cf4ada850f528d5c1959c55033cf72ffc8991b
bigcode/the-stack
train
9cecab2a9d3f7b6ab6beb70e
train
class
class UserManagerMock(UserManager): get_by_email: MagicMock request_verify: MagicMock verify: MagicMock forgot_password: MagicMock reset_password: MagicMock on_after_register: MagicMock on_after_request_verify: MagicMock on_after_verify: MagicMock on_after_forgot_password: MagicMock ...
class UserManagerMock(UserManager):
get_by_email: MagicMock request_verify: MagicMock verify: MagicMock forgot_password: MagicMock reset_password: MagicMock on_after_register: MagicMock on_after_request_verify: MagicMock on_after_verify: MagicMock on_after_forgot_password: MagicMock on_after_reset_password: MagicMo...
should be at least 3 characters" ) class UserManager(BaseTestUserManager[UserCreate, UserDB]): user_db_model = UserDB class UserManagerOAuth(BaseTestUserManager[UserCreate, UserDBOAuth]): user_db_model = UserDBOAuth class UserManagerMock(UserManager):
64
64
101
7
56
chatalyan/fastapi-users
tests/conftest.py
Python
UserManagerMock
UserManagerMock
83
95
83
83
0877b5e78e6f02abec66b16dcd1768718e9d34ea
bigcode/the-stack
train
0a0843421ed2b62867221a37
train
function
@pytest.fixture def verified_superuser() -> UserDB: return UserDB( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, )
@pytest.fixture def verified_superuser() -> UserDB:
return UserDB( email="the.real.merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, is_verified=True, )
@pytest.fixture def superuser_oauth() -> UserDBOAuth: return UserDBOAuth( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, oauth_accounts=[], ) @pytest.fixture def verified_superuser() -> UserDB:
64
64
52
12
52
chatalyan/fastapi-users
tests/conftest.py
Python
verified_superuser
verified_superuser
209
216
209
210
75d6f233ab3fdaca06338600805a3040981be825
bigcode/the-stack
train
3e79a305b3278a249f51d203
train
function
@pytest.fixture def superuser() -> UserDB: return UserDB( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, )
@pytest.fixture def superuser() -> UserDB:
return UserDB( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, )
auth(oauth_account4) -> UserDBOAuth: return UserDBOAuth( email="lake.lady@camelot.bt", hashed_password=excalibur_password_hash, is_active=False, oauth_accounts=[oauth_account4], ) @pytest.fixture def superuser() -> UserDB:
64
64
43
11
53
chatalyan/fastapi-users
tests/conftest.py
Python
superuser
superuser
190
196
190
191
45b6dca489f5304b3cf92bdd43f56e0e491dacf8
bigcode/the-stack
train
1f6f4489da2fc6a7e733996d
train
function
@pytest.fixture(scope="session") def event_loop(): """Force the pytest-asyncio loop to be the main one.""" loop = asyncio.get_event_loop() yield loop
@pytest.fixture(scope="session") def event_loop():
"""Force the pytest-asyncio loop to be the main one.""" loop = asyncio.get_event_loop() yield loop
MagicMock on_after_request_verify: MagicMock on_after_verify: MagicMock on_after_forgot_password: MagicMock on_after_reset_password: MagicMock on_after_update: MagicMock _update: MagicMock @pytest.fixture(scope="session") def event_loop():
64
64
37
10
53
chatalyan/fastapi-users
tests/conftest.py
Python
event_loop
event_loop
98
102
98
99
bc34a25b20aedc24180ca70d105467a16f55a095
bigcode/the-stack
train
5d4384c8facd05fbabe4793d
train
function
@pytest.fixture def oauth_account5() -> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service5", access_token="TOKEN", expires_at=1579000751, account_id="verified_superuser_oauth1", account_email="the.real.merlin@camelot.bt", )
@pytest.fixture def oauth_account5() -> BaseOAuthAccount:
return BaseOAuthAccount( oauth_name="service5", access_token="TOKEN", expires_at=1579000751, account_id="verified_superuser_oauth1", account_email="the.real.merlin@camelot.bt", )
return BaseOAuthAccount( oauth_name="service4", access_token="TOKEN", expires_at=1579000751, account_id="verified_user_oauth1", account_email="lake.lady@camelot.bt", ) @pytest.fixture def oauth_account5() -> BaseOAuthAccount:
64
64
68
13
51
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_account5
oauth_account5
274
282
274
275
9d12067db57410a023c2495705cff437209e3c0b
bigcode/the-stack
train
8e682b7a9ac6a533ad158909
train
class
class UserOAuth(User, BaseOAuthAccountMixin): pass
class UserOAuth(User, BaseOAuthAccountMixin):
pass
_name: Optional[str] picture: Optional[str] class UserCreate(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate): first_name: Optional[str] class UserDB(User, models.BaseUserDB): pass class UserOAuth(User, BaseOAuthAccountMixin):
64
64
13
10
53
chatalyan/fastapi-users
tests/conftest.py
Python
UserOAuth
UserOAuth
52
53
52
52
305e335ec67ff9089ed9dff79496dd8959781b55
bigcode/the-stack
train
3774269794e63a29eee8863e
train
function
@pytest.fixture def mock_authentication(): return get_mock_authentication(name="mock")
@pytest.fixture def mock_authentication():
return get_mock_authentication(name="mock")
, token: str, user: models.UD) -> None: return None def get_mock_authentication(name: str): return AuthenticationBackend( name=name, transport=MockTransport(tokenUrl="/login"), get_strategy=lambda: MockStrategy(), ) @pytest.fixture def mock_authentication():
64
64
18
8
56
chatalyan/fastapi-users
tests/conftest.py
Python
mock_authentication
mock_authentication
485
487
485
486
889c9262c0982ebf61d7b189b31e2d1474a29658
bigcode/the-stack
train
932f7f58e05a720f4d4bd200
train
function
@pytest.fixture def user_manager_oauth(make_user_manager, mock_user_db_oauth): return make_user_manager(UserManagerOAuth, mock_user_db_oauth)
@pytest.fixture def user_manager_oauth(make_user_manager, mock_user_db_oauth):
return make_user_manager(UserManagerOAuth, mock_user_db_oauth)
er.spy(user_manager, "_update") return user_manager return _make_user_manager @pytest.fixture def user_manager(make_user_manager, mock_user_db): return make_user_manager(UserManager, mock_user_db) @pytest.fixture def user_manager_oauth(make_user_manager, mock_user_db_oauth):
64
64
33
18
46
chatalyan/fastapi-users
tests/conftest.py
Python
user_manager_oauth
user_manager_oauth
423
425
423
424
ace44ff8dc86eaa8f588e33d68644443e1037881
bigcode/the-stack
train
e5f04504ad9810e383090500
train
class
class MockStrategy(Strategy[UserCreate, UserDB]): async def read_token( self, token: Optional[str], user_manager: BaseUserManager[UserCreate, UserDB] ) -> Optional[UserDB]: if token is not None: try: token_uuid = UUID4(token) return await user_manager....
class MockStrategy(Strategy[UserCreate, UserDB]):
async def read_token( self, token: Optional[str], user_manager: BaseUserManager[UserCreate, UserDB] ) -> Optional[UserDB]: if token is not None: try: token_uuid = UUID4(token) return await user_manager.get(token_uuid) except ValueError: ...
): super().__init__(tokenUrl) async def get_logout_response(self, response: Response) -> Any: return None @staticmethod def get_openapi_logout_responses_success() -> OpenAPIResponseType: return {} class MockStrategy(Strategy[UserCreate, UserDB]):
63
64
143
12
51
chatalyan/fastapi-users
tests/conftest.py
Python
MockStrategy
MockStrategy
456
474
456
456
9006fe480f6b954d48c479d66458ff666399f7df
bigcode/the-stack
train
9e7e750e170594556694081d
train
function
@pytest.fixture def oauth_account2() -> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service2", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth2", account_email="king.arthur@camelot.bt", )
@pytest.fixture def oauth_account2() -> BaseOAuthAccount:
return BaseOAuthAccount( oauth_name="service2", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth2", account_email="king.arthur@camelot.bt", )
return BaseOAuthAccount( oauth_name="service1", access_token="TOKEN", expires_at=1579000751, account_id="user_oauth1", account_email="king.arthur@camelot.bt", ) @pytest.fixture def oauth_account2() -> BaseOAuthAccount:
64
64
65
13
51
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_account2
oauth_account2
241
249
241
242
9c4715fe2064c9bb4a7bf9936fd4dd1e89f3f195
bigcode/the-stack
train
79db3796551330b77db40cfd
train
function
@pytest.fixture def superuser_oauth() -> UserDBOAuth: return UserDBOAuth( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, oauth_accounts=[], )
@pytest.fixture def superuser_oauth() -> UserDBOAuth:
return UserDBOAuth( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, oauth_accounts=[], )
=[oauth_account4], ) @pytest.fixture def superuser() -> UserDB: return UserDB( email="merlin@camelot.bt", hashed_password=viviane_password_hash, is_superuser=True, ) @pytest.fixture def superuser_oauth() -> UserDBOAuth:
64
64
52
14
50
chatalyan/fastapi-users
tests/conftest.py
Python
superuser_oauth
superuser_oauth
199
206
199
200
3d83cef17873caec793013241d4bddb8780cf539
bigcode/the-stack
train
a43e909ea482dce6ef5038b9
train
function
@pytest.fixture def oauth_account4() -> BaseOAuthAccount: return BaseOAuthAccount( oauth_name="service4", access_token="TOKEN", expires_at=1579000751, account_id="verified_user_oauth1", account_email="lake.lady@camelot.bt", )
@pytest.fixture def oauth_account4() -> BaseOAuthAccount:
return BaseOAuthAccount( oauth_name="service4", access_token="TOKEN", expires_at=1579000751, account_id="verified_user_oauth1", account_email="lake.lady@camelot.bt", )
return BaseOAuthAccount( oauth_name="service3", access_token="TOKEN", expires_at=1579000751, account_id="inactive_user_oauth1", account_email="percival@camelot.bt", ) @pytest.fixture def oauth_account4() -> BaseOAuthAccount:
64
64
65
13
51
chatalyan/fastapi-users
tests/conftest.py
Python
oauth_account4
oauth_account4
263
271
263
264
237a1b1363583c6169a32fff0f838af60c77378f
bigcode/the-stack
train
4aa210c0f2649d67ea4e5d66
train
class
@ddt.ddt class BackupsAPITestCase(test.TestCase): """Test Case for backups API.""" def setUp(self): super(BackupsAPITestCase, self).setUp() self.volume_api = cinder.volume.API() self.backup_api = cinder.backup.API() self.context = context.get_admin_context() self.context...
@ddt.ddt class BackupsAPITestCase(test.TestCase):
"""Test Case for backups API.""" def setUp(self): super(BackupsAPITestCase, self).setUp() self.volume_api = cinder.volume.API() self.backup_api = cinder.backup.API() self.context = context.get_admin_context() self.context.project_id = fake.PROJECT_ID self.context...
an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Tests for Backup code. """ import ddt import mock from oslo_serialization import jsonutils from oslo_utils i...
256
256
22,654
16
239
inspur-storage/cinder
cinder/tests/unit/api/contrib/test_backups.py
Python
BackupsAPITestCase
BackupsAPITestCase
50
2,370
50
51
526dc1ac4db49728e0bdc8bf9097317057fa2223
bigcode/the-stack
train
bcb103abc2334c251c77ea6e
train
function
def point_to_pixelf(x, y, w, h): xp = (min(w-1, (x*(w/2) + w/2))) # Avoid going out of bounds - a little less accurate but hey yp = (min(h-1, (-y*(h/2) + h/2))) return xp, yp
def point_to_pixelf(x, y, w, h):
xp = (min(w-1, (x*(w/2) + w/2))) # Avoid going out of bounds - a little less accurate but hey yp = (min(h-1, (-y*(h/2) + h/2))) return xp, yp
2) + w/2))) # Avoid going out of bounds yp = int(min(h-1, (-y*(h/2) + h/2))) return xp, yp # Floating point version (for interpolation methods later) def point_to_pixelf(x, y, w, h):
64
64
75
13
51
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
point_to_pixelf
point_to_pixelf
28
31
28
28
2e31ae8777d3176b9dd836235d6fd4028a59af3a
bigcode/the-stack
train
dcec6e766d0e6f49ca26b160
train
function
def reconstruct(sin, nviews, ndetectors, IMSIZE, dist_e, dist_d): # Sinogram, nv, nd, w and h, dist to e (1 = imsize/2), dist to d vol_geom = astra.create_vol_geom(IMSIZE, IMSIZE) angles = np.linspace(0,2*math.pi,nviews); proj_geom= astra.create_proj_geom('fanflat', 640/IMSIZE, ndetectors, angles, IMSIZ...
def reconstruct(sin, nviews, ndetectors, IMSIZE, dist_e, dist_d): # Sinogram, nv, nd, w and h, dist to e (1 = imsize/2), dist to d
vol_geom = astra.create_vol_geom(IMSIZE, IMSIZE) angles = np.linspace(0,2*math.pi,nviews); proj_geom= astra.create_proj_geom('fanflat', 640/IMSIZE, ndetectors, angles, IMSIZE*dist_e/2, IMSIZE*dist_d/2); proj_id = astra.create_projector('line_fanflat', proj_geom, vol_geom) sinogram_id = astra.data2d....
8) img = buf.reshape(w, h, 4)[:,:,0] return surface, img, x, y def rotate_des(ds, es, angle): for d in ds: d['a'] += angle for e in es: e['a'] += angle return ds, es def reconstruct(sin, nviews, ndetectors, IMSIZE, dist_e, dist_d): # Sinogram, nv, nd, w and h, dist to e (1 = ims...
119
119
399
49
69
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
reconstruct
reconstruct
186
221
186
187
5319de690a327c1bd5290f5709df6f63be55f9f2
bigcode/the-stack
train
a0843dc4edaf89c573c779e3
train
function
def draw_des(ds, es, width, height): ## Cairo STUFF surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context (surface) ctx.set_source_rgb(1,1,1) ctx.rectangle(0,0,width,height) ctx.fill() def circle(ctx, x, y, size): ctx.arc(x, y, size, 0, 2 * math.pi...
def draw_des(ds, es, width, height): ## Cairo STUFF
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context (surface) ctx.set_source_rgb(1,1,1) ctx.rectangle(0,0,width,height) ctx.fill() def circle(ctx, x, y, size): ctx.arc(x, y, size, 0, 2 * math.pi) ## Back to the good stuff # Connect detectors ...
, (-y*(h/2) + h/2))) return xp, yp # Floating point version (for interpolation methods later) def point_to_pixelf(x, y, w, h): xp = (min(w-1, (x*(w/2) + w/2))) # Avoid going out of bounds - a little less accurate but hey yp = (min(h-1, (-y*(h/2) + h/2))) return xp, yp def draw_des(ds, es, width, height...
121
121
406
17
103
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
draw_des
draw_des
33
76
33
36
9f36a6973a3f573782a9429c86c2d062340da6f3
bigcode/the-stack
train
a65d90005e933fd2a6ec2037
train
function
def p2(w, h): surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() x, y = 0, 0 xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1)...
def p2(w, h):
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() x, y = 0, 0 xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1) ctx.recta...
, w/4, h/4) ctx.fill() ctx.stroke() buf = np.frombuffer(surface.get_data(), np.uint8) img = buf.reshape(w, h, 4)[:,:,0] return surface, img, x, y def p2(w, h):
64
64
207
7
56
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
p2
p2
160
177
160
160
5c5fa443d0977a26dea6de0ba6c06b6d29484df1
bigcode/the-stack
train
1f80bceb0d480a8c5f71f2b9
train
function
def rotate_des(ds, es, angle): for d in ds: d['a'] += angle for e in es: e['a'] += angle return ds, es
def rotate_des(ds, es, angle):
for d in ds: d['a'] += angle for e in es: e['a'] += angle return ds, es
/5, h/5) ctx.fill() ctx.stroke() buf = np.frombuffer(surface.get_data(), np.uint8) img = buf.reshape(w, h, 4)[:,:,0] return surface, img, x, y def rotate_des(ds, es, angle):
64
64
43
9
54
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
rotate_des
rotate_des
179
184
179
179
778ddf141629306a2834bfd83a72cb22d37a39d8
bigcode/the-stack
train
d394f288d4f3d14920909601
train
function
def get_paths(img, ds, es, width, height): # Does interpolation along all paths from emitters to detectors, given an image, detectors and emitters lines = [] for e in es: for d in ds: y0, x0 = point_to_pixel(e['r']*math.cos(e['a']), e['r']*math.sin(e['a']), width, height) # E loc ...
def get_paths(img, ds, es, width, height): # Does interpolation along all paths from emitters to detectors, given an image, detectors and emitters
lines = [] for e in es: for d in ds: y0, x0 = point_to_pixel(e['r']*math.cos(e['a']), e['r']*math.sin(e['a']), width, height) # E loc y1, x1 = point_to_pixel(d['r']*math.cos(d['a']), d['r']*math.sin(d['a']), width, height) # d loc # Make samplng points le...
a']), width, height) circle(ctx, cx, cy, 10) ctx.fill() ctx.stroke() return surface def get_paths(img, ds, es, width, height): # Does interpolation along all paths from emitters to detectors, given an image, detectors and emitters
64
64
216
35
28
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
get_paths
get_paths
107
122
107
108
ce62b0686ce0e7b377aede9d2d13b296129de002
bigcode/the-stack
train
a0e40df1b9477beae23c8094
train
function
def p1(w, h): surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() x, y = 0, 0 xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1)...
def p1(w, h):
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() x, y = 0, 0 xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1) ctx.recta...
0, 2 * math.pi) ctx.fill() ctx.stroke() buf = np.frombuffer(surface.get_data(), np.uint8) img = buf.reshape(w, h, 4)[:,:,0] return surface, img, x, y def p1(w, h):
64
64
207
7
56
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
p1
p1
141
158
141
141
b771254879f12be3507dbebb3b08cfe6f4f3bf85
bigcode/the-stack
train
d9b346ed42fb1c43f64d9ab6
train
function
def test_image(w, h, r, x, y): surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1...
def test_image(w, h, r, x, y):
surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1) ctx.arc(xp, yp, r, 0, 2 *...
0, x1, length), np.linspace(y0, y1, length) # Extract the values along the line zi = img[x.astype(np.int), y.astype(np.int)] lines.append(sum(zi)) return lines def test_image(w, h, r, x, y):
64
64
183
13
50
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
test_image
test_image
124
139
124
124
0319d524ad403d36606665228048ca799281f8f8
bigcode/the-stack
train
4bce7a481dc11e9419302737
train
function
def draw_des_surf(surface, ds, es, width, height): ctx = cairo.Context (surface) def circle(ctx, x, y, size): ctx.arc(x, y, size, 0, 2 * math.pi) # Connect detectors to emitters ctx.set_line_width(2) ctx.set_source_rgb(0, 0.5, 0) for e in es: for d in ds: ctx.move_to(...
def draw_des_surf(surface, ds, es, width, height):
ctx = cairo.Context (surface) def circle(ctx, x, y, size): ctx.arc(x, y, size, 0, 2 * math.pi) # Connect detectors to emitters ctx.set_line_width(2) ctx.set_source_rgb(0, 0.5, 0) for e in es: for d in ds: ctx.move_to(*point_to_pixel(e['r']*math.cos(e['a']), e['r']*mat...
ctx.set_source_rgb(1, 0, 1) for e in es: cx, cy = point_to_pixel(e['r']*math.cos(e['a']), e['r']*math.sin(e['a']), width, height) circle(ctx, cx, cy, 10) ctx.fill() ctx.stroke() # print(cx, cy) return surface def draw_des_surf(surface, ds, es, width, height):
100
100
336
15
84
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
draw_des_surf
draw_des_surf
78
105
78
78
37b11381e27c8f29d233e58098c8520c7947308b
bigcode/the-stack
train
ad16bac47125b01764913118
train
function
def point_to_pixel(x, y, w, h): xp = int(min(w-1, (x*(w/2) + w/2))) # Avoid going out of bounds yp = int(min(h-1, (-y*(h/2) + h/2))) return xp, yp
def point_to_pixel(x, y, w, h):
xp = int(min(w-1, (x*(w/2) + w/2))) # Avoid going out of bounds yp = int(min(h-1, (-y*(h/2) + h/2))) return xp, yp
from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPRegressor from skimage.transform import iradon import seaborn as sns # Drae a set of emitters and detectors # Get a point as a pixel location def point_to_pixel(x, y, w, h):
64
64
67
12
51
johnowhitaker/CIRTS
Misc Notebooks/image_util.py
Python
point_to_pixel
point_to_pixel
22
25
22
22
b4112a76d000c193feaabe4c6d7bdd3c8ae78968
bigcode/the-stack
train
c04cc1d9de7766df10e88686
train
function
def test_unalias_nick(db): conn = sqlite3.connect(db_filename) nick = 'Embolalia' nick_id = 42 conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(nick).lower(), nick]) aliases = ['EmbölaliÅ', 'Embo`work', 'Embo'] for alias in aliases: conn.execut...
def test_unalias_nick(db):
conn = sqlite3.connect(db_filename) nick = 'Embolalia' nick_id = 42 conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(nick).lower(), nick]) aliases = ['EmbölaliÅ', 'Embo`work', 'Embo'] for alias in aliases: conn.execute('INSERT INTO nicknames VA...
nick_values VALUES (?, ?, ?)', [nick_id, key, json.dumps(value, ensure_ascii=False)]) conn.commit() for key, value in data.iteritems(): found_value = db.get_nick_value(nick, key) assert found_value == value def test_unalias_nick(db):
64
64
168
8
55
Nikola-K/lpbot
test/test_db.py
Python
test_unalias_nick
test_unalias_nick
151
170
151
151
0fe05c60a93c03c4f25f1e203f0ded8b8196bd1e
bigcode/the-stack
train
af8674a354e06cb87cb8f01b
train
function
def test_get_nick_or_channel_value(db): db.set_nick_value('asdf', 'qwer', 'poiu') db.set_channel_value('#asdf', 'qwer', '/.,m') assert db.get_nick_or_channel_value('asdf', 'qwer', 'poiu') assert db.get_nick_or_channel_value('#asdf', 'qwer', '/.,m')
def test_get_nick_or_channel_value(db):
db.set_nick_value('asdf', 'qwer', 'poiu') db.set_channel_value('#asdf', 'qwer', '/.,m') assert db.get_nick_or_channel_value('asdf', 'qwer', 'poiu') assert db.get_nick_or_channel_value('#asdf', 'qwer', '/.,m')
(db_filename) conn.execute("INSERT INTO channel_values VALUES ('#asdf', 'qwer', '\"zxcv\"')") conn.commit() result = db.get_channel_value('#asdf', 'qwer') assert result == 'zxcv' def test_get_nick_or_channel_value(db):
64
64
83
10
54
Nikola-K/lpbot
test/test_db.py
Python
test_get_nick_or_channel_value
test_get_nick_or_channel_value
239
243
239
239
ffe5bd437d1ad7644bc40d37d3d58c2fcc8a089d
bigcode/the-stack
train
ecdd7ebfe608f787dc49d466
train
function
def test_get_nick_or_channel_value(db): db.set_nick_value('asdf', 'qwer', 'poiu') db.set_channel_value('#asdf', 'qwer', '/.,m') db.set_channel_value('#asdf', 'lkjh', '1234') names = ['asdf', '#asdf'] assert db.get_preferred_value(names, 'qwer') == 'poiu' assert db.get_preferred_value(names, 'lkj...
def test_get_nick_or_channel_value(db):
db.set_nick_value('asdf', 'qwer', 'poiu') db.set_channel_value('#asdf', 'qwer', '/.,m') db.set_channel_value('#asdf', 'lkjh', '1234') names = ['asdf', '#asdf'] assert db.get_preferred_value(names, 'qwer') == 'poiu' assert db.get_preferred_value(names, 'lkjh') == '1234'
.set_channel_value('#asdf', 'qwer', '/.,m') assert db.get_nick_or_channel_value('asdf', 'qwer', 'poiu') assert db.get_nick_or_channel_value('#asdf', 'qwer', '/.,m') def test_get_nick_or_channel_value(db):
64
64
104
10
54
Nikola-K/lpbot
test/test_db.py
Python
test_get_nick_or_channel_value
test_get_nick_or_channel_value
246
252
246
246
8adeb3f7ce2c582e290112fcbf405960f7ff433a
bigcode/the-stack
train
faa7d70b0e1c49a152cd4138
train
function
def test_set_channel_value(db): conn = sqlite3.connect(db_filename) db.set_channel_value('#asdf', 'qwer', 'zxcv') result = conn.execute( 'SELECT value FROM channel_values WHERE channel = ? and key = ?', ['#asdf', 'qwer']).fetchone()[0] assert result == '"zxcv"'
def test_set_channel_value(db):
conn = sqlite3.connect(db_filename) db.set_channel_value('#asdf', 'qwer', 'zxcv') result = conn.execute( 'SELECT value FROM channel_values WHERE channel = ? and key = ?', ['#asdf', 'qwer']).fetchone()[0] assert result == '"zxcv"'
alias_id for key, value in finals: found = conn.execute( 'SELECT value FROM nick_values WHERE nick_id = ? AND key = ?', [nick_id, key]).fetchone()[0] assert json.loads(unicode(found)) == value def test_set_channel_value(db):
64
64
79
7
56
Nikola-K/lpbot
test/test_db.py
Python
test_set_channel_value
test_set_channel_value
222
228
222
222
c22e350cd997a34d18fc10f5deb71c5d68b35247
bigcode/the-stack
train
20d58f39fe34b607878b1197
train
function
def test_merge_nick_groups(db): conn = sqlite3.connect(db_filename) aliases = ['Embolalia', 'Embo'] for nick_id, alias in enumerate(aliases): conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(alias).lower(), alias]) conn.commit() finals = (('fo...
def test_merge_nick_groups(db):
conn = sqlite3.connect(db_filename) aliases = ['Embolalia', 'Embo'] for nick_id, alias in enumerate(aliases): conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(alias).lower(), alias]) conn.commit() finals = (('foo', 'bar'), ('bar', 'blue'), ('s...
', 'eggs') db.delete_nick_group(aliases[0]) # Nothing else has created values, so we know the tables are empty nicks = conn.execute('SELECT * FROM nicknames').fetchall() assert len(nicks) == 0 data = conn.execute('SELECT * FROM nick_values').fetchone() assert data is None def test_merge_nick_g...
87
87
293
8
78
Nikola-K/lpbot
test/test_db.py
Python
test_merge_nick_groups
test_merge_nick_groups
194
219
194
194
db79bc49371d6b6dfe3dd116ca7c98ce03a123c6
bigcode/the-stack
train
207feb680c6ac752e4717c9d
train
function
def test_set_nick_value(db): conn = sqlite3.connect(db_filename) cursor = conn.cursor() nick = 'Embolalia' nick_id = db.get_nick_id(nick) data = { 'key': 'value', 'number_key': 1234, 'bytes': b'value', 'unicode': 'EmbölaliÅ', } def check(): for key, v...
def test_set_nick_value(db):
conn = sqlite3.connect(db_filename) cursor = conn.cursor() nick = 'Embolalia' nick_id = db.get_nick_id(nick) data = { 'key': 'value', 'number_key': 1234, 'bytes': b'value', 'unicode': 'EmbölaliÅ', } def check(): for key, value in data.iteritems(): ...
nick_id db.alias_nick('both', 'arenew') # Shouldn't fail. with pytest.raises(ValueError): db.alias_nick('Eve', nick) with pytest.raises(ValueError): db.alias_nick(nick, nick) def test_set_nick_value(db):
64
64
204
8
56
Nikola-K/lpbot
test/test_db.py
Python
test_set_nick_value
test_set_nick_value
98
126
98
98
fd151670d997f9fc49cbbd429f17a522359d0f13
bigcode/the-stack
train
f3cab3d7c9ecb6f4d1d70af5
train
function
@pytest.fixture def db(): config = Config('', False) config.core.db_filename = db_filename db = WillieDB(config) # TODO add tests to ensure db creation works properly, too. return db
@pytest.fixture def db():
config = Config('', False) config.core.db_filename = db_filename db = WillieDB(config) # TODO add tests to ensure db creation works properly, too. return db
import tempfile import pytest from lpbot.config import Config from lpbot.db import WillieDB from lpbot.tools import Identifier db_filename = tempfile.mkstemp()[1] if sys.version_info.major >= 3: unicode = str basestring = str @pytest.fixture def db():
64
64
47
6
57
Nikola-K/lpbot
test/test_db.py
Python
db
db
27
33
27
28
7ee81a5ec01aefa05d6f5ea1b93c07296dc05d6c
bigcode/the-stack
train
b2e3360b1ffafb25d92273ec
train
function
def test_delete_nick_group(db): conn = sqlite3.connect(db_filename) aliases = ['Embolalia', 'Embo'] nick_id = 42 for alias in aliases: conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(alias).lower(), alias]) conn.commit() db.set_nick_value...
def test_delete_nick_group(db):
conn = sqlite3.connect(db_filename) aliases = ['Embolalia', 'Embo'] nick_id = 42 for alias in aliases: conn.execute('INSERT INTO nicknames VALUES (?, ?, ?)', [nick_id, Identifier(alias).lower(), alias]) conn.commit() db.set_nick_value(aliases[0], 'foo', 'bar') d...
for alias in aliases: db.unalias_nick(alias) for alias in aliases: found = conn.execute( 'SELECT * FROM nicknames WHERE nick_id = ?', [nick_id]).fetchall() assert len(found) == 1 def test_delete_nick_group(db):
64
64
180
8
55
Nikola-K/lpbot
test/test_db.py
Python
test_delete_nick_group
test_delete_nick_group
173
191
173
173
daea87178c43feb5e24b764fd4147a64930e3dbe
bigcode/the-stack
train
300e2265099b3d0fd6bf2133
train
function
def test_alias_nick(db): conn = sqlite3.connect(db_filename) nick = 'Embolalia' aliases = ['EmbölaliÅ', 'Embo`work', 'Embo'] nick_id = db.get_nick_id(nick) for alias in aliases: db.alias_nick(nick, alias) for alias in aliases: assert db.get_nick_id(alias) == nick_id db.ali...
def test_alias_nick(db):
conn = sqlite3.connect(db_filename) nick = 'Embolalia' aliases = ['EmbölaliÅ', 'Embo`work', 'Embo'] nick_id = db.get_nick_id(nick) for alias in aliases: db.alias_nick(nick, alias) for alias in aliases: assert db.get_nick_id(alias) == nick_id db.alias_nick('both', 'arenew')...
]) assert nick_id == new_id # Even if the case is different for test in tests: nick_id = test[0] new_id = db.get_nick_id(Identifier(test[2].upper())) assert nick_id == new_id def test_alias_nick(db):
64
64
143
7
56
Nikola-K/lpbot
test/test_db.py
Python
test_alias_nick
test_alias_nick
77
95
77
77
d18da6b06681934f416bd9601ce5acdcbeb62177
bigcode/the-stack
train
e965890785df29471d7810a8
train
function
def test_get_nick_value(db): conn = sqlite3.connect(db_filename) cursor = conn.cursor() nick = 'Embolalia' nick_id = db.get_nick_id(nick) data = { 'key': 'value', 'number_key': 1234, 'bytes': b'value', 'unicode': 'EmbölaliÅ', } for key, value in data.iteritem...
def test_get_nick_value(db):
conn = sqlite3.connect(db_filename) cursor = conn.cursor() nick = 'Embolalia' nick_id = db.get_nick_id(nick) data = { 'key': 'value', 'number_key': 1234, 'bytes': b'value', 'unicode': 'EmbölaliÅ', } for key, value in data.iteritems(): cursor.execute('...
).fetchone()[0] assert json.loads(unicode(found_value)) == value check() # Test updates data['number_key'] = 'not a number anymore!' data['unicode'] = 'This is different toö!' check() def test_get_nick_value(db):
64
64
153
8
56
Nikola-K/lpbot
test/test_db.py
Python
test_get_nick_value
test_get_nick_value
129
148
129
129
51ea393eece594fdc41ac3383f846d59de9e8a3a
bigcode/the-stack
train
b7c4de92efed5ed70a8e24a1
train
function
def test_get_nick_id(db): conn = sqlite3.connect(db_filename) tests = [ [None, 'embolalia', Identifier('Embolalia')], # Ensures case conversion is handled properly [None, '[][]', Identifier('[]{}')], # Unicode, just in case [None, 'embölaliå', Identifier('EmbölaliÅ')], ...
def test_get_nick_id(db):
conn = sqlite3.connect(db_filename) tests = [ [None, 'embolalia', Identifier('Embolalia')], # Ensures case conversion is handled properly [None, '[][]', Identifier('[]{}')], # Unicode, just in case [None, 'embölaliå', Identifier('EmbölaliÅ')], ] for test in tests...
tempfile.mkstemp()[1] if sys.version_info.major >= 3: unicode = str basestring = str @pytest.fixture def db(): config = Config('', False) config.core.db_filename = db_filename db = WillieDB(config) # TODO add tests to ensure db creation works properly, too. return db def teardown_functi...
93
93
311
8
85
Nikola-K/lpbot
test/test_db.py
Python
test_get_nick_id
test_get_nick_id
40
74
40
40
f129c569a3604ce4f79cc8f6c04e8f822cc382d1
bigcode/the-stack
train
a9bf3d324d5ba790fd2ccdc5
train
function
def teardown_function(function): os.remove(db_filename)
def teardown_function(function):
os.remove(db_filename)
: unicode = str basestring = str @pytest.fixture def db(): config = Config('', False) config.core.db_filename = db_filename db = WillieDB(config) # TODO add tests to ensure db creation works properly, too. return db def teardown_function(function):
64
64
11
5
58
Nikola-K/lpbot
test/test_db.py
Python
teardown_function
teardown_function
36
37
36
36
060bd2b689d67fa36b87261957fb93ae6dfa371e
bigcode/the-stack
train
530c9c56f4fd5926eaa4cd72
train
function
def test_get_channel_value(db): conn = sqlite3.connect(db_filename) conn.execute("INSERT INTO channel_values VALUES ('#asdf', 'qwer', '\"zxcv\"')") conn.commit() result = db.get_channel_value('#asdf', 'qwer') assert result == 'zxcv'
def test_get_channel_value(db):
conn = sqlite3.connect(db_filename) conn.execute("INSERT INTO channel_values VALUES ('#asdf', 'qwer', '\"zxcv\"')") conn.commit() result = db.get_channel_value('#asdf', 'qwer') assert result == 'zxcv'
asdf', 'qwer', 'zxcv') result = conn.execute( 'SELECT value FROM channel_values WHERE channel = ? and key = ?', ['#asdf', 'qwer']).fetchone()[0] assert result == '"zxcv"' def test_get_channel_value(db):
64
64
67
7
56
Nikola-K/lpbot
test/test_db.py
Python
test_get_channel_value
test_get_channel_value
231
236
231
231
2cb0824513831afc40e9059318b66e0dc6b34747
bigcode/the-stack
train
1753dcb994dec4c519da0603
train
class
class SuggestionContext: def __init__(self, parent, start_pos): self.parent = parent self.start_pos = start_pos
class SuggestionContext:
def __init__(self, parent, start_pos): self.parent = parent self.start_pos = start_pos
class SuggestionContext:
5
64
30
5
0
NickNackGus/brigadier.py
brigadier/context/suggestion_context.py
Python
SuggestionContext
SuggestionContext
1
4
1
1
3bc11adf4edb56b85452b65bb32e1abe81860744
bigcode/the-stack
train
acf42117ea7b605d1a9a58cb
train
class
class Granularities(enum.Enum): """The attributes of this class like granularity.DAILY , .ANNUALY , etc. are enum members The granularities are listed in an arbitrary order. And currently annually, monthly, daily, hourly are used. """ ANNUALLY = 1 MONTHLY = 2 DAILY = 3 HOURLY = 4
class Granularities(enum.Enum):
"""The attributes of this class like granularity.DAILY , .ANNUALY , etc. are enum members The granularities are listed in an arbitrary order. And currently annually, monthly, daily, hourly are used. """ ANNUALLY = 1 MONTHLY = 2 DAILY = 3 HOURLY = 4
STD = 6 VAR = 7 FIRST = 8 LAST = 9 DISTINCT = 10 MEDIAN = 11 PROPORTION_OF_SUM = 12 PROPORTION_OF_COUNT = 13 class Granularities(enum.Enum):
64
64
88
7
56
anmoliiitd823/debaised-analysis
intents/util/enums.py
Python
Granularities
Granularities
43
53
43
43
b84063777c313f491e2e63a58dc823ea8e044325
bigcode/the-stack
train
996accddbd7337d3265d5978
train
class
class Filters(enum.Enum): """The attributes of this class like Filters.EQUALTO , .NOTEQUALTO , etc. are enum members The Filters are listed in an arbitrary order. And currently =, !=, <, <=, >, >=, in, not in are used """ EQUAL_TO = 1 NOT_EQUAL_TO = 2 LESS_THAN = 3 LESS_THAN_EQUAL_T...
class Filters(enum.Enum):
"""The attributes of this class like Filters.EQUALTO , .NOTEQUALTO , etc. are enum members The Filters are listed in an arbitrary order. And currently =, !=, <, <=, >, >=, in, not in are used """ EQUAL_TO = 1 NOT_EQUAL_TO = 2 LESS_THAN = 3 LESS_THAN_EQUAL_TO = 4 GREATER_THAN = 5...
are enum members The granularities are listed in an arbitrary order. And currently annually, monthly, daily, hourly are used. """ ANNUALLY = 1 MONTHLY = 2 DAILY = 3 HOURLY = 4 class Filters(enum.Enum):
64
64
127
5
58
anmoliiitd823/debaised-analysis
intents/util/enums.py
Python
Filters
Filters
55
69
55
55
16cad47f59c9269e829a4870a493d878f66d8666
bigcode/the-stack
train
33d5ef1b380610efa47e90cf
train
class
class SummaryOperators(enum.Enum): """The attributes of this class like summary_operators.SUM , .MEAN , etc. are enum members The operators are listed in an arbitrary order. And currently sum, mean, count, max, min, standard deviation, variance, first, last, count unique are used. sum, max, min...
class SummaryOperators(enum.Enum):
"""The attributes of this class like summary_operators.SUM , .MEAN , etc. are enum members The operators are listed in an arbitrary order. And currently sum, mean, count, max, min, standard deviation, variance, first, last, count unique are used. sum, max, min are replaced by summation, maximum...
, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ """This module contains the enumerations""" import enum class Summ...
64
64
185
6
57
anmoliiitd823/debaised-analysis
intents/util/enums.py
Python
SummaryOperators
SummaryOperators
19
41
19
19
3e8ba8e20361f116272cccc57807a49cead123ca
bigcode/the-stack
train
010cd82009e602b9b0d81255
train
class
class RC3XGate(cirq.Gate): def __init__(self): super(RC3XGate, self).__init__() def _num_qubits_(self): return 4 def _unitary_(self, dtype=None): return numpy.array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
class RC3XGate(cirq.Gate):
def __init__(self): super(RC3XGate, self).__init__() def _num_qubits_(self): return 4 def _unitary_(self, dtype=None): return numpy.array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ...
# (C) Copyright Artificial Brain 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
156
256
889
10
145
Artificial-Brain/quantumcat
quantumcat/gates/custom_gates/cirq/rc3x_gate.py
Python
RC3XGate
RC3XGate
18
45
18
18
871b027e51e08d3d483937457618e7ac826e4260
bigcode/the-stack
train
89d8942598d0e045ea7f1f77
train
class
class GitHubSource: def __init__(self, project_config, spec: GitHubSourceModel): self.project_config = project_config self.spec = spec self.url = spec.github if self.url.endswith(".git"): self.url = self.url[:-4] self.repo_owner, self.repo_name = split_repo_url(s...
class GitHubSource:
def __init__(self, project_config, spec: GitHubSourceModel): self.project_config = project_config self.spec = spec self.url = spec.github if self.url.endswith(".git"): self.url = self.url[:-4] self.repo_owner, self.repo_name = split_repo_url(self.url) tr...
import os import shutil import fs from github3.exceptions import NotFoundError from cumulusci.core.exceptions import DependencyResolutionError from cumulusci.core.github import ( catch_common_github_auth_errors, find_latest_release, find_previous_release, get_github_api_for_repo, ) from cumulusci.util...
114
256
1,233
5
108
SalesforceFoundation/CumulusCI
cumulusci/core/source/github.py
Python
GitHubSource
GitHubSource
19
170
19
19
fd421528ad77a447064acde5443485dbc403a59d
bigcode/the-stack
train
8d3917d4b7f2fecba9e50d43
train
class
class car: maker = 'toyota' def __init__(self,input_model): self.model=input_model
class car:
maker = 'toyota' def __init__(self,input_model): self.model=input_model
''' lec9 class ''' class car:
9
64
26
3
6
JoshuaJurack/IA241-github
lec9.py
Python
car
car
5
9
5
5
9c1e95cea65d7e267a0775df0ed1ae61dc15374a
bigcode/the-stack
train
1ed3bc237385fd424747aac1
train
class
class Elu(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Elu', inputs=['x'], outputs=['y'], alpha=2.0 ) x = np.array([-1, 0, 1]).astype(np.float32) # expected output [-1.2642411, 0., 1.] ...
class Elu(Base): @staticmethod
def export(): # type: () -> None node = onnx.helper.make_node( 'Elu', inputs=['x'], outputs=['y'], alpha=2.0 ) x = np.array([-1, 0, 1]).astype(np.float32) # expected output [-1.2642411, 0., 1.] y = np.clip(x, 0, np.inf) + (np....
# SPDX-License-Identifier: Apache-2.0 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Elu(Base): @staticmethod
76
106
355
9
66
pchandrasekaran1595/onnx
onnx/backend/test/case/node/elu.py
Python
Elu
Elu
15
48
15
17
465869f61344d352c3ec353712a36a213f2316cd
bigcode/the-stack
train
35b2653e9d3541878d70bab8
train
function
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_ddp_all_dataloaders_passed_to_fit(tmpdir): """Make sure DDP works with dataloaders passed to fit()""" tutils.set_random_master_port() model = EvalModelTemplate() fit_options = dict(train_dataloader=mod...
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_ddp_all_dataloaders_passed_to_fit(tmpdir):
"""Make sure DDP works with dataloaders passed to fit()""" tutils.set_random_master_port() model = EvalModelTemplate() fit_options = dict(train_dataloader=model.train_dataloader(), val_dataloaders=model.val_dataloader()) trainer = Trainer( default_root_dir=tmpdir, ...
ipes.run_model_test(trainer_options, model) # test memory helper functions memory.get_memory_profile('min_max') @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_ddp_all_dataloaders_passed_to_fit(tmpdir):
64
64
188
38
26
nightlessbaron/pytorch-lightning
tests/backends/test_ddp_spawn.py
Python
test_ddp_all_dataloaders_passed_to_fit
test_ddp_all_dataloaders_passed_to_fit
66
85
66
67
e58e5b75de0a8cd717ec089f385fd30cd8ef9c18
bigcode/the-stack
train
f3a6ed139f1f7f515f29009c
train
function
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_model_ddp_spawn(tmpdir): tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=10, limit_val_batches=10, ...
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_model_ddp_spawn(tmpdir):
tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=10, limit_val_batches=10, gpus=[0, 1], accelerator='ddp_spawn', progress_bar_refresh_rate=0, ) model = EvalModelTemplate() tpi...
1], accelerator='ddp_spawn', ) model = EvalModelTemplate() tpipes.run_model_test(trainer_options, model) @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_model_ddp_spawn(tmpdir):
64
64
136
33
31
nightlessbaron/pytorch-lightning
tests/backends/test_ddp_spawn.py
Python
test_multi_gpu_model_ddp_spawn
test_multi_gpu_model_ddp_spawn
44
63
44
45
5514ecd8655a6a60dbffe79e509171f236ca931b
bigcode/the-stack
train
a6637133712e0bc2429bd868
train
function
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_early_stop_ddp_spawn(tmpdir): """Make sure DDP works. with early stopping""" tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, callbacks=[EarlyStopp...
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_early_stop_ddp_spawn(tmpdir):
"""Make sure DDP works. with early stopping""" tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, callbacks=[EarlyStopping()], max_epochs=50, limit_train_batches=10, limit_val_batches=10, gpus=[0, 1], accelerator='ddp_spa...
Stopping from tests.base import EvalModelTemplate from pytorch_lightning.core import memory from pytorch_lightning.trainer import Trainer @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_multi_gpu_early_stop_ddp_spawn(tmpdir):
64
64
132
35
28
nightlessbaron/pytorch-lightning
tests/backends/test_ddp_spawn.py
Python
test_multi_gpu_early_stop_ddp_spawn
test_multi_gpu_early_stop_ddp_spawn
25
41
25
26
8cf585c007a15bbac56cacfa696808648f778768
bigcode/the-stack
train
ce2468d2335fe0fb741c7a21
train
class
class AssetCode4: """ XDR Source Code ---------------------------------------------------------------- typedef opaque AssetCode4[4]; ---------------------------------------------------------------- """ def __init__(self, asset_code4: bytes) -> None: self.asset_code4 = asset_code4 ...
class AssetCode4:
""" XDR Source Code ---------------------------------------------------------------- typedef opaque AssetCode4[4]; ---------------------------------------------------------------- """ def __init__(self, asset_code4: bytes) -> None: self.asset_code4 = asset_code4 def pack(self, ...
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from .base import Opaque __all__ = ["AssetCode4"] class AssetCode4:
55
103
346
5
50
kaotisk-hund/py-stellar-base
stellar_sdk/xdr/asset_code4.py
Python
AssetCode4
AssetCode4
11
55
11
11
265e4a6591b19e4f221b0ab3faa13077004341dc
bigcode/the-stack
train
c86c2d090b3911462da5e41e
train
function
def test_cape3d_1d(wrfnc): def func(self): varnames = ("T", "P", "PB", "QVAPOR", "PH", "PHB", "HGT", "PSFC") ncvars = extract_vars(wrfnc, 0, varnames, method="cat", squeeze=True, cache=None, meta=True) t = ncvars["T"] p = ncvars["P"] ...
def test_cape3d_1d(wrfnc):
def func(self): varnames = ("T", "P", "PB", "QVAPOR", "PH", "PHB", "HGT", "PSFC") ncvars = extract_vars(wrfnc, 0, varnames, method="cat", squeeze=True, cache=None, meta=True) t = ncvars["T"] p = ncvars["P"] pb = ncvars["PB"] qv ...
name, wrfnc, timeidx, method, squeeze) except ProjectionError: # Don't fail for this return routine = ROUTINE_MAP[varname] kwargs = {"meta" : meta} result = routine(*args, **kwargs) ref = getvar(wrfnc, varname, timeidx, method, squeeze, cach...
137
137
459
15
121
khallock/wrf-python
test/comp_utest.py
Python
test_cape3d_1d
test_cape3d_1d
549
599
549
550
36066953956e2951b8723c57fafd8f4ffc92621b
bigcode/the-stack
train
e23d05cd3af88dfb4d6bd1a5
train
function
def get_args(varname, wrfnc, timeidx, method, squeeze): if varname == "avo": ncvars = extract_vars(wrfnc, timeidx, ("U", "V", "MAPFAC_U", "MAPFAC_V", "MAPFAC_M", "F"), method, squeeze, cache=None,...
def get_args(varname, wrfnc, timeidx, method, squeeze):
if varname == "avo": ncvars = extract_vars(wrfnc, timeidx, ("U", "V", "MAPFAC_U", "MAPFAC_V", "MAPFAC_M", "F"), method, squeeze, cache=None, meta=True) attrs = extract_global_attrs(wr...
" NCFILE = nc(TEST_FILE) NCGROUP = [NCFILE, NCFILE, NCFILE] # Python 3 if sys.version_info > (3,): xrange = range ROUTINE_MAP = {"avo" : avo, "eth" : eth, "cape_2d" : cape_2d, "cape_3d" : cape_3d, "ctt" : ctt, "dbz" : dbz, "helicity" : srhel, ...
256
256
4,446
17
238
khallock/wrf-python
test/comp_utest.py
Python
get_args
get_args
48
519
48
48
fcf710c62e53d75bcae9d1cfd34bd977014961e6
bigcode/the-stack
train
cd18405e4581aef072d0763a
train
function
def make_func(varname, wrfnc, timeidx, method, squeeze, meta): def func(self): try: args = get_args(varname, wrfnc, timeidx, method, squeeze) except ProjectionError: # Don't fail for this return routine = ROUTINE_MAP[varname] kwargs ...
def make_func(varname, wrfnc, timeidx, method, squeeze, meta):
def func(self): try: args = get_args(varname, wrfnc, timeidx, method, squeeze) except ProjectionError: # Don't fail for this return routine = ROUTINE_MAP[varname] kwargs = {"meta" : meta} result = routine(*args, **kwargs) ...
kel) return (geoht_agl, relh, 1, 300., 2000., 6000.) class WRFVarsTest(ut.TestCase): longMessage = True def make_func(varname, wrfnc, timeidx, method, squeeze, meta):
64
64
156
19
44
khallock/wrf-python
test/comp_utest.py
Python
make_func
make_func
525
546
525
525
9f149dd284944c36f1cbacfd8c55a688da33c271
bigcode/the-stack
train
91aef4598df1b21f765a058f
train
class
class ProjectionError(RuntimeError): pass
class ProjectionError(RuntimeError):
pass
"tk" : tk, "tv" : tvirtual, "twb" : wetbulb, "updraft_helicity" : udhel, "uvmet" : uvmet, "cloudfrac" : cloudfrac} class ProjectionError(RuntimeError):
64
64
9
6
58
khallock/wrf-python
test/comp_utest.py
Python
ProjectionError
ProjectionError
45
46
45
45
e6a51fc3fa2b4a43137c5c14b9a9d8b704bcac41
bigcode/the-stack
train
da17c0b60e30cc0d7011b9fc
train
function
def test_cape2d_1d(wrfnc): def func(self): varnames = ("T", "P", "PB", "QVAPOR", "PH", "PHB", "HGT", "PSFC") ncvars = extract_vars(wrfnc, 0, varnames, method="cat", squeeze=True, cache=None, meta=True) t = ncvars["T"] p = ncvars["P"] ...
def test_cape2d_1d(wrfnc):
def func(self): varnames = ("T", "P", "PB", "QVAPOR", "PH", "PHB", "HGT", "PSFC") ncvars = extract_vars(wrfnc, 0, varnames, method="cat", squeeze=True, cache=None, meta=True) t = ncvars["T"] p = ncvars["P"] pb = ncvars["PB"] qv ...
= ConversionFactors.PA_TO_HPA * full_p psfc_hpa = ConversionFactors.PA_TO_HPA * psfc i3dflag = 1 ter_follow = 1 result = cape_3d(p_hpa, tkel, qv, z, ter, psfc_hpa, ter_follow) ref = getvar(wrfnc, "cape_3d") ref = ref[(slice(None),) + col_idxs] ...
138
138
462
15
122
khallock/wrf-python
test/comp_utest.py
Python
test_cape2d_1d
test_cape2d_1d
602
652
602
603
6363c4c005362579a4550232ddf22d0ca1f9aba4
bigcode/the-stack
train
6d2281dc53ff2c5b8fc4e772
train
class
class WRFVarsTest(ut.TestCase): longMessage = True
class WRFVarsTest(ut.TestCase):
longMessage = True
_BASE tkel = tk(full_p, full_t) relh = rh(qv, full_p, tkel) return (geoht_agl, relh, 1, 300., 2000., 6000.) class WRFVarsTest(ut.TestCase):
63
64
16
10
53
khallock/wrf-python
test/comp_utest.py
Python
WRFVarsTest
WRFVarsTest
522
523
522
522
d442b76b951b83c8fe245964a5368e704ed6230e
bigcode/the-stack
train
cc4b5336687eb3018a081294
train
function
@contextmanager def provide_gcp_credentials(key_file_path: Optional[str] = None, key_file_dict: Optional[Dict] = None): """ Context manager that provides a Google Cloud credentials for application supporting `Application Default Credentials (ADC) strategy <https://cloud.google.com/docs/authentication/produc...
@contextmanager def provide_gcp_credentials(key_file_path: Optional[str] = None, key_file_dict: Optional[Dict] = None):
""" Context manager that provides a Google Cloud credentials for application supporting `Application Default Credentials (ADC) strategy <https://cloud.google.com/docs/authentication/production>`__. It can be used to provide credentials for external programs (e.g. gcloud) that expect authorization f...
if scopes: scopes_string = ",".join(scopes) query_params["{}__scope".format(extras)] = scopes_string if project_id: query_params["{}__projects".format(extras)] = project_id query = urlencode(query_params) return conn.format(query) @contextmanager def provide_gcp_credentials(key_fil...
93
93
311
30
63
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
provide_gcp_credentials
provide_gcp_credentials
78
108
78
79
d8224649e57c154c564956dae5fa48f3c9d9ed1f
bigcode/the-stack
train
9e988ceaddf2afc6af713227
train
function
@contextmanager def provide_gcp_connection( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Optional[str] = None, ): """ Context manager that provides a temporary value of :envvar:`AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT` connection. It build a new connection that includes ...
@contextmanager def provide_gcp_connection( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Optional[str] = None, ):
""" Context manager that provides a temporary value of :envvar:`AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT` connection. It build a new connection that includes path to provided service json, required scopes and project id. :param key_file_path: Path to file with Gooogle Cloud Service Account .json file. ...
_environ({CREDENTIALS: key_file_path}): yield else: # We will use the default service account credentials. yield @contextmanager def provide_gcp_connection( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Optional[str] = None, ):
72
72
242
40
31
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
provide_gcp_connection
provide_gcp_connection
111
133
111
114
086f4b48fc1f719ceedaf04fbe52c9897ab2cfb4
bigcode/the-stack
train
d03ea5a90671db7cc868d2ea
train
function
def _get_target_principal_and_delegates( impersonation_chain: Optional[Union[str, Sequence[str]]] = None ) -> Tuple[Optional[str], Optional[Sequence[str]]]: """ Analyze contents of impersonation_chain and return target_principal (the service account to directly impersonate using short-term credentials, ...
def _get_target_principal_and_delegates( impersonation_chain: Optional[Union[str, Sequence[str]]] = None ) -> Tuple[Optional[str], Optional[Sequence[str]]]:
""" Analyze contents of impersonation_chain and return target_principal (the service account to directly impersonate using short-term credentials, if any) and optional list of delegates required to get the access_token of target_principal. :param impersonation_chain: the service account to imperson...
""" return [s.strip() for s in scopes.split(',')] if scopes else _DEFAULT_SCOPES def _get_target_principal_and_delegates( impersonation_chain: Optional[Union[str, Sequence[str]]] = None ) -> Tuple[Optional[str], Optional[Sequence[str]]]:
64
64
207
40
23
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
_get_target_principal_and_delegates
_get_target_principal_and_delegates
323
344
323
325
6c7081baa0c3b974eabb01f76cfd8913b2ae0224
bigcode/the-stack
train
61f0f2669422810fc9942d3f
train
function
def _get_scopes(scopes: Optional[str] = None) -> Sequence[str]: """ Parse a comma-separated string containing OAuth2 scopes if `scopes` is provided. Otherwise, default scope will be returned. :param scopes: A comma-separated string containing OAuth2 scopes :type scopes: Optional[str] :return: R...
def _get_scopes(scopes: Optional[str] = None) -> Sequence[str]:
""" Parse a comma-separated string containing OAuth2 scopes if `scopes` is provided. Otherwise, default scope will be returned. :param scopes: A comma-separated string containing OAuth2 scopes :type scopes: Optional[str] :return: Returns the scope defined in the connection configuration, or the...
) -> Tuple[google.auth.credentials.Credentials, str]: """ Returns the Credentials object for Google API and the associated project_id. """ return _CredentialProvider(*args, **kwargs).get_credentials_and_project() def _get_scopes(scopes: Optional[str] = None) -> Sequence[str]:
64
64
118
18
46
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
_get_scopes
_get_scopes
310
320
310
310
e5ce098eec5cc88a2a9d5fae55bd63fecacef320
bigcode/the-stack
train
471f4d4631f7252771214773
train
function
def _get_project_id_from_service_account_email(service_account_email: str) -> str: """ Extracts project_id from service account's email address. :param service_account_email: email of the service account. :type service_account_email: str :return: Returns the project_id of the provided service acco...
def _get_project_id_from_service_account_email(service_account_email: str) -> str:
""" Extracts project_id from service account's email address. :param service_account_email: email of the service account. :type service_account_email: str :return: Returns the project_id of the provided service account. :rtype: str """ try: return service_account_email.split('@...
if not impersonation_chain: return None, None if isinstance(impersonation_chain, str): return impersonation_chain, None return impersonation_chain[-1], impersonation_chain[:-1] def _get_project_id_from_service_account_email(service_account_email: str) -> str:
64
64
128
18
46
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
_get_project_id_from_service_account_email
_get_project_id_from_service_account_email
347
362
347
347
e2c56da5aeaf03956a0f1e67fce4ff7947ba7b6c
bigcode/the-stack
train
55c5b826ba8a477684cac3ff
train
function
def get_credentials_and_project_id(*args, **kwargs) -> Tuple[google.auth.credentials.Credentials, str]: """ Returns the Credentials object for Google API and the associated project_id. """ return _CredentialProvider(*args, **kwargs).get_credentials_and_project()
def get_credentials_and_project_id(*args, **kwargs) -> Tuple[google.auth.credentials.Credentials, str]:
""" Returns the Credentials object for Google API and the associated project_id. """ return _CredentialProvider(*args, **kwargs).get_credentials_and_project()
: self.log.info(*args, **kwargs) def _log_debug(self, *args, **kwargs): if not self.disable_logging: self.log.debug(*args, **kwargs) def get_credentials_and_project_id(*args, **kwargs) -> Tuple[google.auth.credentials.Credentials, str]:
64
64
57
23
41
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
get_credentials_and_project_id
get_credentials_and_project_id
303
307
303
303
48d434deb09af71d24f53dc68b4710fa53f06b57
bigcode/the-stack
train
dc132cf2e15bd8a05da591a4
train
function
@contextmanager def provide_gcp_conn_and_credentials( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Optional[str] = None, ): """ Context manager that provides both: - Google Cloud credentials for application supporting `Application Default Credentials (ADC) s...
@contextmanager def provide_gcp_conn_and_credentials( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Optional[str] = None, ):
""" Context manager that provides both: - Google Cloud credentials for application supporting `Application Default Credentials (ADC) strategy <https://cloud.google.com/docs/authentication/production>`__. - temporary value of :envvar:`AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT` connection :param key_f...
conn = build_gcp_conn(scopes=scopes, key_file_path=key_file_path, project_id=project_id) with patch_environ({AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT: conn}): yield @contextmanager def provide_gcp_conn_and_credentials( key_file_path: Optional[str] = None, scopes: Optional[Sequence] = None, project_id: Option...
88
88
296
42
45
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
provide_gcp_conn_and_credentials
provide_gcp_conn_and_credentials
136
167
136
139
0235e2b82995cfbde03257c89abb1aa47235f5b2
bigcode/the-stack
train
3744d1488276af37e02e23ff
train
function
def build_gcp_conn( key_file_path: Optional[str] = None, scopes: Optional[Sequence[str]] = None, project_id: Optional[str] = None, ) -> str: """ Builds a uri that can be used as :envvar:`AIRFLOW_CONN_{CONN_ID}` with provided service key, scopes and project id. :param key_file_path: Path to ...
def build_gcp_conn( key_file_path: Optional[str] = None, scopes: Optional[Sequence[str]] = None, project_id: Optional[str] = None, ) -> str:
""" Builds a uri that can be used as :envvar:`AIRFLOW_CONN_{CONN_ID}` with provided service key, scopes and project id. :param key_file_path: Path to service key. :type key_file_path: Optional[str] :param scopes: Required OAuth scopes. :type scopes: Optional[List[str]] :param project_id...
FLOW_CONN_GOOGLE_CLOUD_DEFAULT = "AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT" _DEFAULT_SCOPES: Sequence[str] = ('https://www.googleapis.com/auth/cloud-platform',) def build_gcp_conn( key_file_path: Optional[str] = None, scopes: Optional[Sequence[str]] = None, project_id: Optional[str] = None, ) -> str:
80
80
269
42
38
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
build_gcp_conn
build_gcp_conn
45
75
45
49
277e32b1dbf5275c21ebdfe308df9754705ba392
bigcode/the-stack
train
e4e4e7faf1c6639600dfb3ea
train
class
class _CredentialProvider(LoggingMixin): """ Prepare the Credentials object for Google API and the associated project_id Only either `key_path` or `keyfile_dict` should be provided, or an exception will occur. If neither of them are provided, return default credentials for the current environment ...
class _CredentialProvider(LoggingMixin):
""" Prepare the Credentials object for Google API and the associated project_id Only either `key_path` or `keyfile_dict` should be provided, or an exception will occur. If neither of them are provided, return default credentials for the current environment :param key_path: Path to Google Cloud Ser...
provides both: - Google Cloud credentials for application supporting `Application Default Credentials (ADC) strategy <https://cloud.google.com/docs/authentication/production>`__. - temporary value of :envvar:`AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT` connection :param key_file_path: Path to file with Goog...
256
256
1,200
8
247
marcoaaguiar/airflow
airflow/providers/google/cloud/utils/credentials_provider.py
Python
_CredentialProvider
_CredentialProvider
170
300
170
170
929484a45bcd92c0a4ee891ad8125c1e6f58b144
bigcode/the-stack
train
02c241842ddbc4df7b8a0621
train
function
@click.command() @click.argument('model') @click.argument('dataset') @loss_resolver.get_option('-l', '--loss') @sampler_resolver.get_option('--sampler', help="Which sampler should be used?") @click.option('--storage', help="Where to output trials dataframe") @click.option('--n-trials', type=int, help="Number of trials ...
@click.command() @click.argument('model') @click.argument('dataset') @loss_resolver.get_option('-l', '--loss') @sampler_resolver.get_option('--sampler', help="Which sampler should be used?") @click.option('--storage', help="Where to output trials dataframe") @click.option('--n-trials', type=int, help="Number of trials ...
"""Optimize hyper-parameters for a KGE model. For example, use pykeen optimize TransE Nations --loss MarginRankingLoss """ if n_trials is None and timeout is None: click.secho('Must specify either --n-trials or --timeout', fg='red') sys.exit(1) hpo_pipeline_result = hpo_pipeline( ...
@click.command() @click.argument('model') @click.argument('dataset') @loss_resolver.get_option('-l', '--loss') @sampler_resolver.get_option('--sampler', help="Which sampler should be used?") @click.option('--storage', help="Where to output trials dataframe") @click.option('--n-trials', type=int, help="Number of trials ...
168
87
293
168
0
DJRavinszkha/pykeen
src/pykeen/hpo/cli.py
Python
optimize
optimize
15
51
15
33
ebe6ca843c21d7201bfad27cbdb446c538c6382c
bigcode/the-stack
train
adaaab206495a97f1934abf4
train
function
def verify_writes_count(core, writes_before, threshold, io_size, ver_type=VerifyType.NEGATIVE): writes_after = core.get_statistics().block_stats.cache.writes writes_difference = writes_after - writes_before if ver_type is VerifyType.NEGATIVE: if writes_difference < io_size: TestRun.fail...
def verify_writes_count(core, writes_before, threshold, io_size, ver_type=VerifyType.NEGATIVE):
writes_after = core.get_statistics().block_stats.cache.writes writes_difference = writes_after - writes_before if ver_type is VerifyType.NEGATIVE: if writes_difference < io_size: TestRun.fail(f"Wrong writes count: {writes_difference} , expected at least " f"{io_...
() ).run() with TestRun.step("Verify writes to cache count"): verify_writes_count(cores[0], writes_before, threshold, io_size, VerifyType.POSITIVE) def verify_writes_count(core, writes_before, threshold, io_size, ver_type=VerifyType.NEGATIVE):
64
64
190
24
40
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
verify_writes_count
verify_writes_count
229
244
229
229
50be265a57e17ed7c2b10672f2b736a936335eeb
bigcode/the-stack
train
98fedf373e38f6219fcc84f0
train
function
@pytest.mark.parametrize("thresholds_list", [[ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF...
@pytest.mark.parametrize("thresholds_list", [[ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF...
""" title: Sequential cut-off tests during sequential and random IO 'always' policy with 4 cores description: | Testing if amount of data written to cache after sequential writes for different sequential cut-off thresholds on each core, while running sequential IO on 3 out of 4 cores...
ITIVE = auto() EQUAL = auto() @pytest.mark.parametrize("thresholds_list", [[ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))), ...
256
256
930
246
10
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
test_seq_cutoff_multi_core
test_seq_cutoff_multi_core
29
106
29
43
76ba54d56d7a7a92d01927d584364a46c51e263a
bigcode/the-stack
train
c93892d99888b1642d3ed11a
train
function
def prepare(cores_count=1, cache_line_size: CacheLineSize = None): cache_device = TestRun.disks['cache'] core_device = TestRun.disks['core'] cache_device.create_partitions( [(SEQ_CUTOFF_THRESHOLD_MAX * cores_count + Size(5, Unit.GibiByte)).align_down(0x1000)]) partitions = \ [(SEQ_CUTOFF...
def prepare(cores_count=1, cache_line_size: CacheLineSize = None):
cache_device = TestRun.disks['cache'] core_device = TestRun.disks['core'] cache_device.create_partitions( [(SEQ_CUTOFF_THRESHOLD_MAX * cores_count + Size(5, Unit.GibiByte)).align_down(0x1000)]) partitions = \ [(SEQ_CUTOFF_THRESHOLD_MAX + Size(10, Unit.GibiByte)).align_down(0x1000)] * cor...
f"{threshold + io_margin}") elif ver_type is VerifyType.EQUAL: if writes_difference != io_size: TestRun.fail(f"Wrong writes count: {writes_difference} , expected {io_size}") def prepare(cores_count=1, cache_line_size: CacheLineSize = None):
64
65
219
18
46
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
prepare
prepare
247
265
247
247
b1d733bd7b279c2a4394e5d6a4da613e0f1d69a9
bigcode/the-stack
train
faa9e00f072c7564123a46b3
train
function
@pytest.mark.parametrize("threshold_param", [ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))) ]) @pytest.mark.parametrize("policy, verify_type", [(SeqCutOffPolicy.never, VerifyType.NEGATIVE), (SeqCutOffPolicy.always, VerifyType.POSITIVE), ...
@pytest.mark.parametrize("threshold_param", [ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))) ]) @pytest.mark.parametrize("policy, verify_type", [(SeqCutOffPolicy.never, VerifyType.NEGATIVE), (SeqCutOffPolicy.always, VerifyType.POSITIVE), ...
""" title: Sequential cut-off tests for writes and reads for 'never', 'always' and 'full' policies description: | Testing if amount of data written to cache after sequential writes and reads for different sequential cut-off policies with cache configured with different cache line size ...
1], VerifyType.EQUAL) @pytest.mark.parametrize("threshold_param", [ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))) ]) @pytest.mark.parametrize("policy, verify_type", [(SeqCutOffPolicy.never, VerifyType.NEGATIVE), ...
176
176
589
168
8
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
test_seq_cutoff_thresh
test_seq_cutoff_thresh
109
158
109
119
1590ff8b89c4941adb2712c0b6253db5039ad7c0
bigcode/the-stack
train
59d1fa938bcc39e7677ece00
train
function
@pytest.mark.parametrize("threshold_param", [ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))) ]) @pytest.mark.parametrizex("cls", CacheLineSize) @pytest.mark.parametrizex("io_dir", [ReadWrite.write, ReadWrite.read]) @pytest.mark.require_disk("cache", DiskTypeSet([DiskType.optane, DiskType....
@pytest.mark.parametrize("threshold_param", [ random.randint(1, int(SEQ_CUTOFF_THRESHOLD_MAX.get_value(Unit.KibiByte))) ]) @pytest.mark.parametrizex("cls", CacheLineSize) @pytest.mark.parametrizex("io_dir", [ReadWrite.write, ReadWrite.read]) @pytest.mark.require_disk("cache", DiskTypeSet([DiskType.optane, DiskType....
""" title: Sequential cut-off tests during writes and reads on full cache for 'full' policy description: | Testing if amount of data written to cache after sequential io against fully occupied cache for 'full' sequential cut-off policy with cache configured with different cache line ...
sync() writes_before = cores[0].get_statistics().block_stats.cache.writes (Fio().create_command() .io_engine(IoEngine.libaio) .size(io_size) .read_write(io_dir) .target(f"{cores[0].system_path}") .direct() ).run() with ...
217
217
726
113
104
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
test_seq_cutoff_thresh_fill
test_seq_cutoff_thresh_fill
161
226
161
168
ab10f89296ed6d949c0fe3853953c41d8a26a957
bigcode/the-stack
train
9b5d1627153c7cda886f8bbd
train
class
class VerifyType(Enum): NEGATIVE = auto() POSITIVE = auto() EQUAL = auto()
class VerifyType(Enum):
NEGATIVE = auto() POSITIVE = auto() EQUAL = auto()
import DiskType, DiskTypeSet, DiskTypeLowerThan from test_tools.fio.fio import Fio from test_tools.fio.fio_param import ReadWrite, IoEngine from test_utils.os_utils import Udev, sync from test_utils.size import Size, Unit class VerifyType(Enum):
64
64
23
5
58
anatol/open-cas-linux
test/functional/tests/cache_ops/test_seq_cutoff.py
Python
VerifyType
VerifyType
23
26
23
23
03402065126dffbfe9378194ac94963542da253e
bigcode/the-stack
train
405ec8fca768f83d3d7a3029
train
class
class UserProfile(AbstractBaseUser, PermissionsMixin): """Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects ...
class UserProfile(AbstractBaseUser, PermissionsMixin):
"""Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'email' ...
password): """Create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin):
64
64
148
10
53
danielhau/profiles-rest-api
profiles_api/models.py
Python
UserProfile
UserProfile
34
56
34
34
66fac266775ebdd700e6ebba21ac48f45296bedf
bigcode/the-stack
train
5c7d6c285dde5ff98a9225fb
train
class
class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user...
class UserProfileManager(BaseUserManager):
"""Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) ...
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager):
43
64
156
8
34
danielhau/profiles-rest-api
profiles_api/models.py
Python
UserProfileManager
UserProfileManager
7
32
7
7
73e68b306748c7a0e54ffae0a0a1c3b08b16beed
bigcode/the-stack
train
c9cbef0fc3ea3ec7b7e36b61
train
class
class RenderMode(object): """Supported rendering modes. """ SEGMASK = 'segmask' DEPTH = 'depth' DEPTH_SCENE = 'depth_scene' SCALED_DEPTH = 'scaled_depth' COLOR = 'color' COLOR_SCENE = 'color_scene' GRAY = 'gray' GD = 'gd' RGBD = 'rgbd' RGBD_SCENE = 'rgbd_scene' GRAYSC...
class RenderMode(object):
"""Supported rendering modes. """ SEGMASK = 'segmask' DEPTH = 'depth' DEPTH_SCENE = 'depth_scene' SCALED_DEPTH = 'scaled_depth' COLOR = 'color' COLOR_SCENE = 'color_scene' GRAY = 'gray' GD = 'gd' RGBD = 'rgbd' RGBD_SCENE = 'rgbd_scene' GRAYSCALE = 'gray'
""" Render modes Author: Jeff Mahler """ class RenderMode(object):
16
64
104
5
11
peter0749/PointNetGPD
meshpy/meshpy/render_modes.py
Python
RenderMode
RenderMode
5
18
5
5
f6b76c7accf07b04fb32d4c0d70b5b78a7f2f8a0
bigcode/the-stack
train
d488e0af02a5d0fa539c0702
train
class
class KeypointGANModel(BaseModel): def name(self): return 'KeypointGANModel' @staticmethod def modify_commandline_options(parser, is_train=True): # default CycleGAN did not use dropout parser.set_defaults(no_dropout=True) if is_train: parser.add_argument('--lambd...
class KeypointGANModel(BaseModel):
def name(self): return 'KeypointGANModel' @staticmethod def modify_commandline_options(parser, is_train=True): # default CycleGAN did not use dropout parser.set_defaults(no_dropout=True) if is_train: parser.add_argument('--lambda_A', type=float, default=10.0, hel...
import cPickle as cp import itertools import os import pickle from argparse import Namespace import torch from torch.autograd import Variable from torch.nn import functional as F import data.human36m_skeleton from data import CreateDataLoader from data.human36m_skeleton import simple_link_indices as human36m_link_ind...
143
256
5,510
8
134
VMReyes/keypointgan
models/keypoint_gan_model.py
Python
KeypointGANModel
KeypointGANModel
25
615
25
25
fd92565118eb5bc09101586acb7887df7ac1b040
bigcode/the-stack
train
d8a42c8785847c4177dfcb55
train
class
class PortForwardingRule(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map ...
class PortForwardingRule(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ server OpenAPI spec version: 2018-06-22T02:34:44Z Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from ncloud_server.model.server_instance import ServerInstance # noqa: F401,E501 class PortForwardingRule(ob...
89
256
1,175
7
81
KidongSohn/ncloud-sdk-py
lib/services/server/ncloud_server/model/port_forwarding_rule.py
Python
PortForwardingRule
PortForwardingRule
20
170
20
20
6324c0361579187f49b6cc42c39287377ac14474
bigcode/the-stack
train
ba0ab20f3a795a81a050df85
train
function
def cut_texts(texts=None, need_cut=True, word_len=1): ''' Use jieba to cut texts :param texts:list of texts :param need_cut:whether need cut text :param word_len:min length of words to keep,in order to delete stop-words :param savepath:path to save word list in json file :return: ''' ...
def cut_texts(texts=None, need_cut=True, word_len=1):
''' Use jieba to cut texts :param texts:list of texts :param need_cut:whether need cut text :param word_len:min length of words to keep,in order to delete stop-words :param savepath:path to save word list in json file :return: ''' if need_cut: if word_len > 1: tex...
import jieba jieba.setLogLevel('WARN') def cut_texts(texts=None, need_cut=True, word_len=1):
29
64
195
17
12
renjunxiang/chatbot_by_similarity
chatbot/cut_text.py
Python
cut_texts
cut_texts
6
26
6
6
bc9ca7e597515f93beba5d44671217a766ec5310
bigcode/the-stack
train
fef9a6a60bb77ab6939c30c0
train
class
class MultipleManyToOneRecursiveTests(TestCase): def setUp(self): self.dad = Person(full_name='John Smith Senior', mother=None, father=None) self.dad.save() self.mom = Person(full_name='Jane Smith', mother=None, father=None) self.mom.save() self.kid = Person(full_name...
class MultipleManyToOneRecursiveTests(TestCase):
def setUp(self): self.dad = Person(full_name='John Smith Senior', mother=None, father=None) self.dad.save() self.mom = Person(full_name='Jane Smith', mother=None, father=None) self.mom.save() self.kid = Person(full_name='John Smith Junior', mother=self.mom, father=self.d...
self.assertEqual(self.r.child_set.get(name__startswith='Child').id, self.c.id) self.assertIsNone(self.r.parent) self.assertQuerysetEqual(self.c.child_set.all(), []) self.assertEqual(self.c.parent.id, self.r.id) class MultipleManyToOneRecursiveTests(TestCase):
66
66
220
10
56
Yoann-Vie/esgi-hearthstone
tests/m2o_recursive/tests.py
Python
MultipleManyToOneRecursiveTests
MultipleManyToOneRecursiveTests
23
41
23
24
08c5e994036ec7b5d60f91236a5ca7ed190307e0
bigcode/the-stack
train
2da6c65520958ccb3e95c0e6
train
class
class ManyToOneRecursiveTests(TestCase): def setUp(self): self.r = Category(id=None, name='Root category', parent=None) self.r.save() self.c = Category(id=None, name='Child category', parent=self.r) self.c.save() def test_m2o_recursive(self): self.assertQueryse...
class ManyToOneRecursiveTests(TestCase):
def setUp(self): self.r = Category(id=None, name='Root category', parent=None) self.r.save() self.c = Category(id=None, name='Child category', parent=self.r) self.c.save() def test_m2o_recursive(self): self.assertQuerysetEqual(self.r.child_set.all(), ...
from django.test import TestCase from .models import Category, Person class ManyToOneRecursiveTests(TestCase):
24
64
145
9
14
Yoann-Vie/esgi-hearthstone
tests/m2o_recursive/tests.py
Python
ManyToOneRecursiveTests
ManyToOneRecursiveTests
6
20
6
7
2eed337bed235647f8c8d0f8271e7c918ee6b7f3
bigcode/the-stack
train
c6b84f6fff07477faffce8ad
train
class
class IntrinsicCuriosityWorldOptionModel(SupervisedModel): """ Combines an inverse dynamics network, predicting actions that lead from state s to state s', with a forward model ("world option model"), predicting a distribution over a latent feature-vector for s', when given s and a. Uses a single loss f...
class IntrinsicCuriosityWorldOptionModel(SupervisedModel):
""" Combines an inverse dynamics network, predicting actions that lead from state s to state s', with a forward model ("world option model"), predicting a distribution over a latent feature-vector for s', when given s and a. Uses a single loss function, combining the loss terms for both these prediction...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing pe...
256
256
2,689
13
242
RLGraph/RLGraph
rlgraph/components/models/intrinsic_curiosity_world_option_model.py
Python
IntrinsicCuriosityWorldOptionModel
IntrinsicCuriosityWorldOptionModel
36
298
36
36
cc957d88c0ce653549621b82f34ac5c554263fb6
bigcode/the-stack
train
60b0a491146e94b13e824453
train
class
class KubernetesRawModule(KubernetesAnsibleModule): @property def validate_spec(self): return dict( fail_on_error=dict(type='bool'), version=dict(), strict=dict(type='bool', default=True) ) @property def condition_spec(self): return dict( ...
class KubernetesRawModule(KubernetesAnsibleModule): @property
def validate_spec(self): return dict( fail_on_error=dict(type='bool'), version=dict(), strict=dict(type='bool', default=True) ) @property def condition_spec(self): return dict( type=dict(), status=dict(default=True, choices...
AUTH_ARG_SPEC, COMMON_ARG_SPEC from ansible.module_utils.six import string_types from ansible_collections.community.kubernetes.plugins.module_utils.common import KubernetesAnsibleModule from ansible.module_utils.common.dict_transformations import dict_merge try: import yaml from openshift.dynamic.exceptions ...
256
256
4,194
14
241
camilamacedo86/ocp-release-operator-sdk
release/ansible/ansible_collections/community/kubernetes/plugins/module_utils/raw.py
Python
KubernetesRawModule
KubernetesRawModule
66
520
66
68
fd317d88d0a139ed6befc88302e5c10183174b25
bigcode/the-stack
train
8f92cf45441bccf8fff4dd2f
train
function
def must_be_int(val: int): return val
def must_be_int(val: int):
return val
], int] = lambda a, b: a + b # This should generate an error because x should be # determined to be an "int", so "len(x)" is invalid. map(lambda x: len(x), [1, 2, 3]) def must_be_int(val: int):
64
64
12
8
56
lego0901/pytea
packages/pyright-internal/src/tests/samples/assignment3.py
Python
must_be_int
must_be_int
13
14
13
13
18f25b4570f139675d484c3a0113698271714134
bigcode/the-stack
train
0468850e2f4dc975d073af19
train
function
def analyze_sightline(m): """Iterate through the room & build two lists of indices. -- add to 'going_to_sit' Simultainesouly look for filled chairs that ALSO have 5+ neighbors -- add to 'going_to_leave' return (arrive_rows, arrive_cols), (leave_rows, leave_cols) which can be used lat...
def analyze_sightline(m):
"""Iterate through the room & build two lists of indices. -- add to 'going_to_sit' Simultainesouly look for filled chairs that ALSO have 5+ neighbors -- add to 'going_to_leave' return (arrive_rows, arrive_cols), (leave_rows, leave_cols) which can be used later to slice into 'm' "...
== 0): arrive_rows.append(row) arrive_cols.append(col) # Will this chair vacate? (cutoff @ 5 because of counting self) if (val == 1) and (np.nansum(rolling_window) >= 5): leave_rows.append(row) leave_cols.append(col) return (...
94
94
315
7
87
UpwardTrajectory/advent-of-code
2020/day11/day11.py
Python
analyze_sightline
analyze_sightline
44
75
44
44
1c7bf659248f4274e5c68628073d18bbf9669385
bigcode/the-stack
train
3fec6ba1cf19a774ac4be4cd
train
function
def cycle_once(m, func=analyze_chairs): """Analyze a seating map (m) and change it in place. Return the updated map, and a flag for whether the room is still unstable """ going_to_sit, going_to_leave = func(m) print( f"Arrived {len(going_to_sit[0])} | {len(going_to_leave[0])} Left | Cur...
def cycle_once(m, func=analyze_chairs):
"""Analyze a seating map (m) and change it in place. Return the updated map, and a flag for whether the room is still unstable """ going_to_sit, going_to_leave = func(m) print( f"Arrived {len(going_to_sit[0])} | {len(going_to_leave[0])} Left | Current {int(np.nansum(m))}" ) if...
for view in [up, down, left, right, d1u, d2u, d1d, d2d]: view = view[~np.isnan(view)] total_seen += view[0] return total_seen def cycle_once(m, func=analyze_chairs):
64
64
167
12
51
UpwardTrajectory/advent-of-code
2020/day11/day11.py
Python
cycle_once
cycle_once
109
126
109
109
da15b98355902d316958ef5d7f91d4efd001b267
bigcode/the-stack
train
2b1564f00066b0fd25d9d269
train
function
def stabalize_room(data, func=analyze_chairs): """Parse the raw data, then alternate between filling & vacating chairs in the waiting room. When no more changes can occur, exit the cycle & return the total number of seated visitors. """ m, still_in_flux = map_area(data), True while st...
def stabalize_room(data, func=analyze_chairs):
"""Parse the raw data, then alternate between filling & vacating chairs in the waiting room. When no more changes can occur, exit the cycle & return the total number of seated visitors. """ m, still_in_flux = map_area(data), True while still_in_flux: m, still_in_flux = cycle_o...
_leave: print("No changes! Exiting . . . ") return m, False m[going_to_sit] = 1 m[going_to_leave] = 0 return m, True def stabalize_room(data, func=analyze_chairs):
64
64
102
14
49
UpwardTrajectory/advent-of-code
2020/day11/day11.py
Python
stabalize_room
stabalize_room
129
141
129
129
eeb235d1c8bd6f370ec40bf0f509cfb677298725
bigcode/the-stack
train
289934f816631f18580afd62
train
function
def analyze_chairs(m): """Iterate through the room & build two lists of indices. Use a rolling window to search for empty chairs w/ no-one seated nearby -- add to 'going_to_sit' Simultainesouly look for filled chairs that ALSO have 4+ neighbors -- add to 'going_to_leave' return (arrive_ro...
def analyze_chairs(m):
"""Iterate through the room & build two lists of indices. Use a rolling window to search for empty chairs w/ no-one seated nearby -- add to 'going_to_sit' Simultainesouly look for filled chairs that ALSO have 4+ neighbors -- add to 'going_to_leave' return (arrive_rows, arrive_cols), (leav...
import numpy as np from chairs import sample, sample2, waiting_area def map_area(data): return np.array( [[np.nan if c == "." else 0 for c in row] for row in data.split("\n")] ) def analyze_chairs(m):
58
99
333
6
52
UpwardTrajectory/advent-of-code
2020/day11/day11.py
Python
analyze_chairs
analyze_chairs
11
41
11
11
8e22890c39437f4565fe80b9d377aca46cc60e63
bigcode/the-stack
train