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
55866128629097147df4984a
train
function
@pytest.fixture def pool(repository): pool = Pool() pool.add_repository(repository) return pool
@pytest.fixture def pool(repository):
pool = Pool() pool.add_repository(repository) return pool
run(self, bin, *args): raise EnvCommandError(CalledProcessError(1, "python", output="")) @pytest.fixture def root(): return ProjectPackage("root", "1.2.3") @pytest.fixture def repository(): return Repository() @pytest.fixture def pool(repository):
64
64
22
7
57
mgasner/poetry
tests/puzzle/test_provider.py
Python
pool
pool
37
42
37
38
9343464e3d321f3f8eb86653a8824128b5426a1d
bigcode/the-stack
train
35c3885590680ac74bca495c
train
function
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_vcs_read_setup_with_extras(provider, mocker): mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git") dependenc...
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_vcs_read_setup_with_extras(provider, mocker):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = VCSDependency("demo", "git", "https://github.com/demo/demo.git") dependency.extras.append("foo") package = provider.search_for_vcs(dependency)[0] assert package.name == "demo" assert package.version.text == "...
"foo": [get_dependency("cleo")], "bar": [get_dependency("tomlkit")], } @pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_vcs_read_setup_with_extras(provider, mocker):
64
64
185
38
26
mgasner/poetry
tests/puzzle/test_provider.py
Python
test_search_for_vcs_read_setup_with_extras
test_search_for_vcs_read_setup_with_extras
99
117
99
100
990f30c4e58f2dc2ed28195764a696a03cce697c
bigcode/the-stack
train
458e6cbfa4733fb26932b66d
train
function
def test_search_for_file_sdist(provider): dependency = FileDependency( "demo", Path(__file__).parent.parent / "fixtures" / "distributions" / "demo-0.1.0.tar.gz", ) package = provider.search_for_file(dependency)[0] assert package.name == "demo" assert package...
def test_search_for_file_sdist(provider):
dependency = FileDependency( "demo", Path(__file__).parent.parent / "fixtures" / "distributions" / "demo-0.1.0.tar.gz", ) package = provider.search_for_file(dependency)[0] assert package.name == "demo" assert package.version.text == "0.1.0" assert packag...
.4")] assert package.extras == { "extras_a": [get_dependency("pendulum", ">=1.4.4")], "extras_b": [get_dependency("cachy", ">=0.2.0")], } def test_search_for_file_sdist(provider):
64
64
139
9
55
mgasner/poetry
tests/puzzle/test_provider.py
Python
test_search_for_file_sdist
test_search_for_file_sdist
286
303
286
286
f90077d2708cf68ee6cc92b20da4b755a3383c58
bigcode/the-stack
train
b2475bdde7271d968c6bfb21
train
function
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_extras(provider, mocker): mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = DirectoryDependency( "demo", Path(__file__).parent...
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_extras(provider, mocker):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = DirectoryDependency( "demo", Path(__file__).parent.parent / "fixtures" / "git" / "github.com" / "demo" / "demo", ) dependency.extras.append("foo") package = ...
"foo": [get_dependency("cleo")], "bar": [get_dependency("tomlkit")], } @pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_extras(provider, mocker):
64
64
209
38
26
mgasner/poetry
tests/puzzle/test_provider.py
Python
test_search_for_directory_setup_read_setup_with_extras
test_search_for_directory_setup_read_setup_with_extras
202
228
202
203
57de0b095b94b3f2d7066cba193be01760381280
bigcode/the-stack
train
b930d9338e3eb4f068d53b29
train
function
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_no_dependencies(provider, mocker): mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = DirectoryDependency( "demo", Path(__file_...
@pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_no_dependencies(provider, mocker):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=MockEnv()) dependency = DirectoryDependency( "demo", Path(__file__).parent.parent / "fixtures" / "git" / "github.com" / "demo" / "no-dependencies", ) package = provider.search_for_direc...
"foo": [get_dependency("cleo")], "bar": [get_dependency("tomlkit")], } @pytest.mark.skipif(not PY35, reason="AST parsing does not work for Python <3.4") def test_search_for_directory_setup_read_setup_with_no_dependencies(provider, mocker):
64
64
151
38
26
mgasner/poetry
tests/puzzle/test_provider.py
Python
test_search_for_directory_setup_read_setup_with_no_dependencies
test_search_for_directory_setup_read_setup_with_no_dependencies
231
250
231
232
1b8caa5ac82ceffd4a4bc2b73b34857e95162110
bigcode/the-stack
train
4abd27fbecfefe1b8ba0241e
train
class
class HeaderCounter(Counter): """[summary] Args: Counter ([type]): [description] """ def __init__(self, reader): super().__init__() self = self.build_from(reader) def __str__(self): return f'{self.most_common()}' def build_from(self, reader): for email...
class HeaderCounter(Counter):
"""[summary] Args: Counter ([type]): [description] """ def __init__(self, reader): super().__init__() self = self.build_from(reader) def __str__(self): return f'{self.most_common()}' def build_from(self, reader): for email in reader: for k ...
from collections import Counter from email.header import decode_header from emailnetwork.utils import clean_subject class HeaderCounter(Counter):
26
72
240
6
19
utomoreza/emailnetwork
build/lib/emailnetwork/header.py
Python
HeaderCounter
HeaderCounter
6
41
6
6
8253e1a181692abea2d85a47567f0840a4125de6
bigcode/the-stack
train
38767773ca91efd027a635b5
train
class
class UserModelTests(unittest.TestCase): def setUp(self): pass def test_unique_users(self): """ there should not be two users with the same user_type and user_id """ for auth_system, auth_system_module in AUTH_SYSTEMS.iteritems(): models.User.objects.create(...
class UserModelTests(unittest.TestCase):
def setUp(self): pass def test_unique_users(self): """ there should not be two users with the same user_type and user_id """ for auth_system, auth_system_module in AUTH_SYSTEMS.iteritems(): models.User.objects.create(user_type = auth_system, user_id = 'foobar...
""" Unit Tests for Auth Systems """ import unittest import models from django.db import IntegrityError, transaction from django.test.client import Client from django.test import TestCase from django.core import mail from auth_systems import AUTH_SYSTEMS class UserModelTests(unittest.TestCase):
60
197
658
8
51
IspBrasil/helios-server
helios_auth/tests.py
Python
UserModelTests
UserModelTests
17
89
17
18
d436a5235cffc7ce2e395eed852c11616e8721b6
bigcode/the-stack
train
c38f84e07b0ac693952e8ae4
train
class
class UserBlackboxTests(TestCase): def setUp(self): # create a bogus user self.test_user = models.User.objects.create(user_type='password',user_id='foobar-test@adida.net',name="Foobar User", info={'password':'foobaz'}) def test_password_login(self): ## we can't test this anymore until ...
class UserBlackboxTests(TestCase):
def setUp(self): # create a bogus user self.test_user = models.User.objects.create(user_type='password',user_id='foobar-test@adida.net',name="Foobar User", info={'password':'foobaz'}) def test_password_login(self): ## we can't test this anymore until it's election specific pass ...
Foo Bar Status Update'}) u2 = models.User.update_or_create(user_type = auth_system, user_id = 'foobar_eq', info={'name':'Foo Bar Status Update'}) self.assertEquals(u, u2) import views import auth_systems.password as password_views from django.urls import reverse # FIXME: login CSRF should ma...
92
92
309
8
83
IspBrasil/helios-server
helios_auth/tests.py
Python
UserBlackboxTests
UserBlackboxTests
99
130
99
100
e2b3f3d551ff07c7fbc153f601e06fa73d5d4e1d
bigcode/the-stack
train
e4b9c73d24a46b5ee3d39591
train
class
class PosixGroupsTester(unittest.TestCase): def setUp(self): if posix.getuid() != 0: raise unittest.SkipTest("not enough privileges") if not hasattr(posix, 'getgroups'): raise unittest.SkipTest("need posix.getgroups") if sys.platform == 'darwin': raise un...
class PosixGroupsTester(unittest.TestCase):
def setUp(self): if posix.getuid() != 0: raise unittest.SkipTest("not enough privileges") if not hasattr(posix, 'getgroups'): raise unittest.SkipTest("need posix.getgroups") if sys.platform == 'darwin': raise unittest.SkipTest("getgroups(2) is broken on OS...
.O_WRONLY | os.O_CREAT) # raises finally: if fd is not None: os.close(fd) self.assertFalse(os.path.exists(fn)) self.assertRaises(ValueError, os.mkdir, fn_with_NUL) self.assertFalse(os.path.exists(fn)) open(fn, 'wb').close() self.assertRaises(Va...
92
92
309
9
83
zgrge/cpython
Lib/test/test_posix.py
Python
PosixGroupsTester
PosixGroupsTester
1,216
1,249
1,216
1,217
a4a1b733e4c51905c1f4e30ddd10acae378b2c38
bigcode/the-stack
train
0ba877bdd90aa0d8a74f30b4
train
function
def test_main(): try: support.run_unittest(PosixTester, PosixGroupsTester) finally: support.reap_children()
def test_main():
try: support.run_unittest(PosixTester, PosixGroupsTester) finally: support.reap_children()
.skipUnless(hasattr(posix, 'setgroups'), "test needs posix.setgroups()") def test_setgroups(self): for groups in [[0], list(range(16))]: posix.setgroups(groups) self.assertListEqual(groups, posix.getgroups()) def test_main():
64
64
30
4
60
zgrge/cpython
Lib/test/test_posix.py
Python
test_main
test_main
1,251
1,255
1,251
1,251
9a47facbbd32165b8a65a221b67a21f1be2dd59c
bigcode/the-stack
train
be4a55f9910935287efeeb9c
train
class
class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(support.TESTFN, 'w+') fp.close() self.teardown_files = [ support.TESTFN ] self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filter...
class PosixTester(unittest.TestCase):
def setUp(self): # create empty file fp = open(support.TESTFN, 'w+') fp.close() self.teardown_files = [ support.TESTFN ] self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings('ignore', '.* potential securi...
"Test posix functions" from test import support # Skip these tests if there is no posix module. posix = support.import_module('posix') import errno import sys import time import os import platform import pwd import stat import tempfile import unittest import warnings _DUMMY_SYMLINK = os.path.join(tempfile.gettempdi...
97
256
12,415
8
89
zgrge/cpython
Lib/test/test_posix.py
Python
PosixTester
PosixTester
22
1,214
22
23
66fa3f1dd9c2f4a1ad5bfaa6f09a32daa150b4d3
bigcode/the-stack
train
68dc401d4c7dc33375f05de8
train
function
def test_api_users_get_admins(): """Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status_...
def test_api_users_get_admins():
"""Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status_code == 200 set_confi...
r = client.get("/api/v1/users") assert r.status_code == 302 set_config("account_visibility", "admins") r = client.get("/api/v1/users") assert r.status_code == 404 destroy_ctfd(app) def test_api_users_get_admins():
64
64
142
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_get_admins
test_api_users_get_admins
58
72
58
58
9674150bb143d09783318120f635a786df532515
bigcode/the-stack
train
5b9787cf56d6c4199c3c1a96
train
function
def test_api_user_get_me_logged_in(): """Can a user get /api/v1/users/me if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me") assert r.status_code == 200 destro...
def test_api_user_get_me_logged_in():
"""Can a user get /api/v1/users/me if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me") assert r.status_code == 200 destroy_ctfd(app)
/me if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me") assert r.status_code == 302 destroy_ctfd(app) def test_api_user_get_me_logged_in():
64
64
80
9
55
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_logged_in
test_api_user_get_me_logged_in
353
361
353
353
89ea270ad39039b0334bb92cdfd1ad9e96b00375
bigcode/the-stack
train
c532dea5bf59f7128aa9902c
train
function
def test_api_user_change_email_under_whitelist(): """Test that users can only change emails to ones in the whitelist""" app = create_ctfd() with app.app_context(): register_user(app) set_config( "domain_whitelist", "whitelisted.com, whitelisted.org, whitelisted.net" ...
def test_api_user_change_email_under_whitelist():
"""Test that users can only change emails to ones in the whitelist""" app = create_ctfd() with app.app_context(): register_user(app) set_config( "domain_whitelist", "whitelisted.com, whitelisted.org, whitelisted.net" ) with login_as_user(app) as client: ...
resp = r.get_json() assert resp["data"]["email"] == "new_email@email.com" assert resp["success"] is True user = Users.query.filter_by(id=2).first() assert user.verified is False destroy_ctfd(app) def test_api_user_change_email_under_whitelist():
68
68
227
10
58
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_change_email_under_whitelist
test_api_user_change_email_under_whitelist
509
535
509
509
b3f699bc130f6f5e025f5980ae0471350608f5d5
bigcode/the-stack
train
bbc99e1919d7e9f194b3fd02
train
function
def test_api_user_delete_admin(): """Can a user patch /api/v1/users/<user_id> if admin""" app = create_ctfd() with app.app_context(): register_user(app) user = Users.query.filter_by(id=2).first() simulate_user_activity(app.db, user=user) with login_as_user(app, "admin"...
def test_api_user_delete_admin():
"""Can a user patch /api/v1/users/<user_id> if admin""" app = create_ctfd() with app.app_context(): register_user(app) user = Users.query.filter_by(id=2).first() simulate_user_activity(app.db, user=user) with login_as_user(app, "admin") as client: r = clien...
= create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.delete("/api/v1/teams/2", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_delete_admin():
64
64
138
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_delete_admin
test_api_user_delete_admin
328
340
328
328
75bc638600ba4ac6aa03dfbe61a3d54a19072b07
bigcode/the-stack
train
c9650f7537f7f90899831e18
train
function
def test_api_users_post_admin_with_attributes(): """Can a user post /api/v1/users with user settings""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: # Create user r = client.post( "/api/v1/users", ...
def test_api_users_post_admin_with_attributes():
"""Can a user post /api/v1/users with user settings""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: # Create user r = client.post( "/api/v1/users", json={ "name": "user", ...
assert user assert verify_password("password", user.password) # Make sure user can login with the creds client = login_as_user(app) r = client.get("/profile") assert r.status_code == 200 destroy_ctfd(app) def test_api_users_post_admin_with_attribu...
64
64
190
9
55
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_post_admin_with_attributes
test_api_users_post_admin_with_attributes
109
135
109
109
1407b8b725387ced9e418ebf8e915c04d78a4dbd
bigcode/the-stack
train
ffdf8df458377db3741bd0fd
train
function
def test_api_user_change_verify_email(): """Test that users are marked unconfirmed if they change their email and verify_emails is turned on""" app = create_ctfd() with app.app_context(): set_config("verify_emails", True) register_user(app) user = Users.query.filter_by(id=2).fi...
def test_api_user_change_verify_email():
"""Test that users are marked unconfirmed if they change their email and verify_emails is turned on""" app = create_ctfd() with app.app_context(): set_config("verify_emails", True) register_user(app) user = Users.query.filter_by(id=2).first() user.verified = True ...
_json() assert resp["data"]["email"] == "new_email@email.com" assert resp["success"] is True user = Users.query.filter_by(id=2).first() assert user.email == "new_email@email.com" destroy_ctfd(app) def test_api_user_change_verify_email():
64
64
194
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_change_verify_email
test_api_user_change_verify_email
486
506
486
486
f78dadda9f99059f8fcb0bf1a3d4a005b278946d
bigcode/the-stack
train
3f57b4a82c62277a96aadfb4
train
function
def test_api_user_get_me_awards_logged_in(): """Can a user get /api/v1/users/me/awards if logged in""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/awards") a...
def test_api_user_get_me_awards_logged_in():
"""Can a user get /api/v1/users/me/awards if logged in""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/awards") assert r.status_code == 200 destroy_ctfd(a...
= create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/awards", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_get_me_awards_logged_in():
64
64
92
11
53
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_awards_logged_in
test_api_user_get_me_awards_logged_in
695
703
695
695
2ceae8e29cec04e89155434d024491d3b56e9cec
bigcode/the-stack
train
9994473d23e514f424c21fa6
train
function
def test_api_team_get_public(): """Can a user get /api/v1/team/<user_id> if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") gen_user(app.db) r = client.get("/api/v1...
def test_api_team_get_public():
"""Can a user get /api/v1/team/<user_id> if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") gen_user(app.db) r = client.get("/api/v1/users/2") assert r....
"confirm": "password"}, ) resp = r.get_json() assert r.status_code == 400 assert resp["errors"]["name"] assert resp["success"] is False assert Users.query.count() == 3 destroy_ctfd(app) def test_api_team_get_public():
64
64
157
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_team_get_public
test_api_team_get_public
228
243
228
228
091f50dfc0f3e9cd78cedf69cd3814ed14e19aba
bigcode/the-stack
train
3712e1ba13ba3bd2c5d7618d
train
function
def test_api_users_post_admin(): """Can a user post /api/v1/users if admin""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: # Create user r = client.post( "/api/v1/users", json={"name": "user", ...
def test_api_users_post_admin():
"""Can a user post /api/v1/users if admin""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: # Create user r = client.post( "/api/v1/users", json={"name": "user", "email": "user@user.com", "passwor...
1/users if not admin""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.post("/api/v1/users", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_users_post_admin():
64
64
180
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_post_admin
test_api_users_post_admin
85
106
85
85
6285010eaa607610218b9370fa36b0f4613f8198
bigcode/the-stack
train
b7ee9dcf16dbcf1b15421fbd
train
function
def test_api_user_get_me_fails_not_logged_in(): """Can a user get /api/v1/users/me/fails if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/fails", json="") assert r.status_code == 403 ...
def test_api_user_get_me_fails_not_logged_in():
"""Can a user get /api/v1/users/me/fails if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/fails", json="") assert r.status_code == 403 destroy_ctfd(app)
admin = login_as_user(app, name="admin") r = admin.get("/api/v1/users/2/solves") data = r.get_json()["data"] assert len(data) == 2 destroy_ctfd(app) def test_api_user_get_me_fails_not_logged_in():
64
64
85
12
52
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_fails_not_logged_in
test_api_user_get_me_fails_not_logged_in
613
620
613
613
70dbd77e700b047c6bb890c54cd35bb19d5f5225
bigcode/the-stack
train
938da32f97c4357ec70cb627
train
function
def test_api_accessing_hidden_users(): """Hidden users should not be visible to normal users, only to admins""" app = create_ctfd() with app.app_context(): register_user(app, name="visible_user", email="visible_user@ctfd.io") register_user(app, name="hidden_user", email="hidden_user@ctf...
def test_api_accessing_hidden_users():
"""Hidden users should not be visible to normal users, only to admins""" app = create_ctfd() with app.app_context(): register_user(app, name="visible_user", email="visible_user@ctfd.io") register_user(app, name="hidden_user", email="hidden_user@ctfd.io") # ID 3 user = Users.que...
name="user2") r = client.get("/api/v1/users/2/awards") data = r.get_json()["data"] assert len(data) == 1 # Admins should see all awards for the user admin = login_as_user(app, name="admin") r = admin.get("/api/v1/users/2/awards") ...
111
111
370
8
103
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_accessing_hidden_users
test_api_accessing_hidden_users
756
784
756
756
d6d8b77f3120065c5370c787c8c884c3a3eed63f
bigcode/the-stack
train
9172beef3e625bddf340a3a4
train
function
def test_api_user_patch_admin(): """Can a user patch /api/v1/users/<user_id> if admin""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app, "admin") as client: r = client.patch( "/api/v1/users/2", json={ ...
def test_api_user_patch_admin():
"""Can a user patch /api/v1/users/<user_id> if admin""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app, "admin") as client: r = client.patch( "/api/v1/users/2", json={ "name": "user...
app = create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.patch("/api/v1/users/2", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_patch_admin():
64
64
165
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_patch_admin
test_api_user_patch_admin
294
314
294
294
6ec4acd3be7de92259d8aaaed3faa8d2671dd834
bigcode/the-stack
train
ec81b87cfe6f8d35c7b0af00
train
function
def test_api_user_send_email(): """Can an admin post /api/v1/users/<user_id>/email""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.post( "/api/v1/users/2/email", json={"text": "email should...
def test_api_user_send_email():
"""Can an admin post /api/v1/users/<user_id>/email""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.post( "/api/v1/users/2/email", json={"text": "email should get rejected"} ) ...
get_json()["data"] assert len(list_users) == 3 assert client.get("/api/v1/users/3").status_code == 200 assert client.get("/api/v1/users/3/solves").status_code == 200 assert client.get("/api/v1/users/3/fails").status_code == 200 assert client.get("/api/v...
108
108
361
7
101
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_send_email
test_api_user_send_email
818
862
818
818
382bebe7e45bbaf14c29aea28bf43be0afbdea25
bigcode/the-stack
train
607ff5f47837e02fd5141090
train
function
def test_api_user_get_me_fails_logged_in(): """Can a user get /api/v1/users/me/fails if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/fails") assert r.status_code ...
def test_api_user_get_me_fails_logged_in():
"""Can a user get /api/v1/users/me/fails if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/fails") assert r.status_code == 200 destroy_ctfd(app)
app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/fails", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_get_me_fails_logged_in():
64
64
86
11
53
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_fails_logged_in
test_api_user_get_me_fails_logged_in
623
631
623
623
d148c26cd36194c2edaefea3f64af96f33073f7a
bigcode/the-stack
train
148193fa4f977e921f3611be
train
function
def test_api_user_get_solves_after_freze_time(): """Can a user get /api/v1/users/<user_id>/solves after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd....
def test_api_user_get_solves_after_freze_time():
"""Can a user get /api/v1/users/<user_id>/solves after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd.io") # Friday, October 6, 2017 12:00:00...
.get("/api/v1/users/me/solves") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_solves(): """Can a user get /api/v1/users/<user_id>/solves if logged in""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app) with logi...
131
131
438
13
118
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_solves_after_freze_time
test_api_user_get_solves_after_freze_time
570
610
570
570
9def1445236a00d329e00fbb8be1f92b6161dc45
bigcode/the-stack
train
897e0f643407fd9caec5f639
train
function
def test_api_users_post_admin_duplicate_information(): """Can an admin create a user with duplicate information""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app, "admin") as client: # Duplicate email r = client.post( ...
def test_api_users_post_admin_duplicate_information():
"""Can an admin create a user with duplicate information""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app, "admin") as client: # Duplicate email r = client.post( "/api/v1/users", json={"na...
# Make sure password was hashed properly user = Users.query.filter_by(email="user@user.com").first() assert user assert verify_password("password", user.password) assert user.banned assert user.hidden assert user.verified destroy_ctfd(a...
70
70
234
9
61
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_post_admin_duplicate_information
test_api_users_post_admin_duplicate_information
138
165
138
138
66e682345272e8c23d2e2279f29eec363cdc9ea3
bigcode/the-stack
train
8e1285eec40491832598a1e3
train
function
def test_api_user_change_name(): """Can a user change their name via the API""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.patch("/api/v1/users/me", json={"name": "user2"}) assert r.status_code =...
def test_api_user_change_name():
"""Can a user change their name via the API""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.patch("/api/v1/users/me", json={"name": "user2"}) assert r.status_code == 200 resp = r.get_js...
password": "password", "confirm": "password", "country": "US", }, ) assert r.status_code == 200 assert r.get_json()["data"]["country"] == "US" user = Users.query.filter_by(id=1).first() assert u...
92
92
309
7
85
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_change_name
test_api_user_change_name
419
452
419
419
0e11f82aff702bf3ecee73bc6ef448d0f64eecc0
bigcode/the-stack
train
db462fc7873191e2204a0f02
train
function
def test_api_user_get_me_solves_not_logged_in(): """Can a user get /api/v1/users/me/solves if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/solves", json="") assert r.status_code == 403 ...
def test_api_user_get_me_solves_not_logged_in():
"""Can a user get /api/v1/users/me/solves if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/solves", json="") assert r.status_code == 403 destroy_ctfd(app)
password"}, ) assert r.status_code == 200 resp = r.get_json() assert resp["data"]["email"] == "new_email@whitelisted.com" assert resp["success"] is True destroy_ctfd(app) def test_api_user_get_me_solves_not_logged_in():
64
64
87
12
52
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_solves_not_logged_in
test_api_user_get_me_solves_not_logged_in
538
545
538
538
a91f0f6c6328c1a53ef3abdb6ca10701ff5691f3
bigcode/the-stack
train
c2e089972645b68c765889d2
train
function
def test_api_user_patch_me_not_logged_in(): """Can a user patch /api/v1/users/me if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.patch("/api/v1/users/me", json="") assert r.status_code == 403 destroy_ctfd...
def test_api_user_patch_me_not_logged_in():
"""Can a user patch /api/v1/users/me if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.patch("/api/v1/users/me", json="") assert r.status_code == 403 destroy_ctfd(app)
app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_patch_me_not_logged_in():
64
64
79
10
54
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_patch_me_not_logged_in
test_api_user_patch_me_not_logged_in
364
371
364
364
bd6495f849702f4d297c9990cc9eabeca0af1188
bigcode/the-stack
train
ab0f084eaab3d574675e3d92
train
function
def test_api_users_get_public(): """Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status_...
def test_api_users_get_public():
"""Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status_code == 200 set_confi...
import verify_password from tests.helpers import ( create_ctfd, destroy_ctfd, gen_award, gen_challenge, gen_fail, gen_solve, gen_user, login_as_user, register_user, simulate_user_activity, ) def test_api_users_get_public():
64
64
141
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_get_public
test_api_users_get_public
24
38
24
24
930dd240926d1852a13048aeaf50fc2f6847671c
bigcode/the-stack
train
b4b9220249b7c92140714450
train
function
def test_api_user_change_email(): """Test that users can change their email via the API""" app = create_ctfd() with app.app_context(): register_user(app) user = Users.query.filter_by(id=2).first() app.db.session.commit() with login_as_user(app) as client: ...
def test_api_user_change_email():
"""Test that users can change their email via the API""" app = create_ctfd() with app.app_context(): register_user(app) user = Users.query.filter_by(id=2).first() app.db.session.commit() with login_as_user(app) as client: # Test users can't submit null ...
_changes", True) r = client.patch("/api/v1/users/me", json={"name": "new_name"}) assert r.status_code == 200 resp = r.get_json() assert resp["data"]["name"] == "new_name" assert resp["success"] is True destroy_ctfd(app) def test_api_user_change_email...
76
76
254
7
69
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_change_email
test_api_user_change_email
455
483
455
455
725b2e49ee243fcabc15414adab33d33ed4cac8b
bigcode/the-stack
train
7aac3ce0adf18823fed7a329
train
function
def test_api_team_get_private(): """Can a user get /api/v1/users/<user_id> if users are private""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: set_config("account_visibility", "public") r = client.get("/api/...
def test_api_team_get_private():
"""Can a user get /api/v1/users/<user_id> if users are private""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: set_config("account_visibility", "public") r = client.get("/api/v1/users/2") print(r....
client.get("/api/v1/users/2") assert r.status_code == 302 set_config("account_visibility", "admins") r = client.get("/api/v1/users/2") assert r.status_code == 404 destroy_ctfd(app) def test_api_team_get_private():
64
64
164
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_team_get_private
test_api_team_get_private
246
262
246
246
8865d3970241412854f40259c35349b3a953837f
bigcode/the-stack
train
6c8ac8d5625972ed7f6199f4
train
function
def test_api_users_patch_admin_duplicate_information(): """Can an admin modify a user with duplicate information""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io", password="password") register_user(app, name="user2", email="user2@ctfd...
def test_api_users_patch_admin_duplicate_information():
"""Can an admin modify a user with duplicate information""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io", password="password") register_user(app, name="user2", email="user2@ctfd.io", password="password") with login_as_user(ap...
"user", "email": "user2@ctfd.io", "password": "password"}, ) resp = r.get_json() assert r.status_code == 400 assert resp["errors"]["name"] assert resp["success"] is False assert Users.query.count() == 2 destroy_ctfd(app) def test_api_us...
80
80
269
9
71
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_patch_admin_duplicate_information
test_api_users_patch_admin_duplicate_information
168
195
168
168
1c723b663917c57ba39c68aa80471eb23f05828d
bigcode/the-stack
train
9c2341fc9a356c473ec0430f
train
function
def test_api_users_get_private(): """Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status...
def test_api_users_get_private():
"""Can a user get /api/v1/users if users are public""" app = create_ctfd() with app.app_context(): with app.test_client() as client: set_config("account_visibility", "public") r = client.get("/api/v1/users") assert r.status_code == 200 set_confi...
") r = client.get("/api/v1/users") assert r.status_code == 302 set_config("account_visibility", "admins") r = client.get("/api/v1/users") assert r.status_code == 404 destroy_ctfd(app) def test_api_users_get_private():
64
64
141
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_get_private
test_api_users_get_private
41
55
41
41
04d448be3af5fc1b7e698ea9d338131eae2bf0d3
bigcode/the-stack
train
84b6b303c52065e0bec038fa
train
function
def test_api_user_get_me_solves_logged_in(): """Can a user get /api/v1/users/me/solves if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/solves") assert r.status_co...
def test_api_user_get_me_solves_logged_in():
"""Can a user get /api/v1/users/me/solves if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/solves") assert r.status_code == 200 destroy_ctfd(app)
= create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/solves", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_get_me_solves_logged_in():
64
64
88
11
53
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_solves_logged_in
test_api_user_get_me_solves_logged_in
548
556
548
548
1bdb6015d64304901ad52725f89859964b8cc2b2
bigcode/the-stack
train
20f3fdd459fd1687cf67cbce
train
function
def test_api_user_get_solves(): """Can a user get /api/v1/users/<user_id>/solves if logged in""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/solves") assert r...
def test_api_user_get_solves():
"""Can a user get /api/v1/users/<user_id>/solves if logged in""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/solves") assert r.status_code == 200 destroy_...
= create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/solves") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_solves():
64
64
92
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_solves
test_api_user_get_solves
559
567
559
559
d044e4d975fb918905dc576117f23cb39267d404
bigcode/the-stack
train
15c820fbcb1d65fb44c294e4
train
function
def test_api_accessing_banned_users(): """Banned users should not be visible to normal users, only to admins""" app = create_ctfd() with app.app_context(): register_user(app, name="visible_user", email="visible_user@ctfd.io") register_user(app, name="banned_user", email="banned_user@ctf...
def test_api_accessing_banned_users():
"""Banned users should not be visible to normal users, only to admins""" app = create_ctfd() with app.app_context(): register_user(app, name="visible_user", email="visible_user@ctfd.io") register_user(app, name="banned_user", email="banned_user@ctfd.io") # ID 3 user = Users.que...
admin").get_json()["data"] assert len(list_users) == 3 assert client.get("/api/v1/users/3").status_code == 200 assert client.get("/api/v1/users/3/solves").status_code == 200 assert client.get("/api/v1/users/3/fails").status_code == 200 assert client.get...
112
112
376
9
103
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_accessing_banned_users
test_api_accessing_banned_users
787
815
787
787
aba40ccd3751b307ee2b26609b23285190b68b29
bigcode/the-stack
train
a76a5f9b9a0c447a8a64aa0a
train
function
def test_api_users_post_non_admin(): """Can a user post /api/v1/users if not admin""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.post("/api/v1/users", json="") assert r.status_code == 403 destroy_ctfd(app)
def test_api_users_post_non_admin():
"""Can a user post /api/v1/users if not admin""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.post("/api/v1/users", json="") assert r.status_code == 403 destroy_ctfd(app)
r = client.get("/api/v1/users") assert r.status_code == 302 set_config("account_visibility", "admins") r = client.get("/api/v1/users") assert r.status_code == 404 destroy_ctfd(app) def test_api_users_post_non_admin():
64
64
74
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_post_non_admin
test_api_users_post_non_admin
75
82
75
75
227b6b3f08355e1ac0c17f881a4d3beb9dcaa4d7
bigcode/the-stack
train
4714c08c995ecda6986e238d
train
function
def test_api_user_patch_me_logged_in(): """Can a user patch /api/v1/users/me if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.patch( "/api/v1/users/me", json={ ...
def test_api_user_patch_me_logged_in():
"""Can a user patch /api/v1/users/me if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.patch( "/api/v1/users/me", json={ "name": "user", ...
logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.patch("/api/v1/users/me", json="") assert r.status_code == 403 destroy_ctfd(app) def test_api_user_patch_me_logged_in():
64
64
143
9
55
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_patch_me_logged_in
test_api_user_patch_me_logged_in
374
392
374
374
a1eaa67bce052f6e631799989d334bc38b437947
bigcode/the-stack
train
85fd76888d6a0dcb6fd110b6
train
function
def test_api_user_delete_non_admin(): """Can a user delete /api/v1/users/<user_id> if not admin""" app = create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.delete("/api/v1/teams/2", json="") assert r.status_cod...
def test_api_user_delete_non_admin():
"""Can a user delete /api/v1/users/<user_id> if not admin""" app = create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.delete("/api/v1/teams/2", json="") assert r.status_code == 403 destroy_ctfd(app)
verified": True, }, ) assert r.status_code == 200 user_data = r.get_json()["data"][0] assert user_data["country"] == "US" assert user_data["verified"] is True destroy_ctfd(app) def test_api_user_delete_non_admin():
64
64
86
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_delete_non_admin
test_api_user_delete_non_admin
317
325
317
317
94f71d7818a2bd7ef8ed55ffcd3b15a38447da7d
bigcode/the-stack
train
2d23b7262f065ad122f08a5d
train
function
def test_api_users_patch_duplicate_information(): """Can a user modify their information to another user's""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io", password="password") register_user(app, name="user2", email="user2@ctfd.io", ...
def test_api_users_patch_duplicate_information():
"""Can a user modify their information to another user's""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io", password="password") register_user(app, name="user2", email="user2@ctfd.io", password="password") with login_as_user(ap...
": "user", "email": "user2@ctfd.io", "password": "password"}, ) resp = r.get_json() assert r.status_code == 400 assert resp["errors"]["email"] assert resp["success"] is False assert Users.query.count() == 3 destroy_ctfd(app) def test_api...
80
80
269
8
72
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_users_patch_duplicate_information
test_api_users_patch_duplicate_information
198
225
198
198
f27538bbe8a3979dff8072717f2c610b7aa62ce4
bigcode/the-stack
train
77af32a8bcad4990cd46650d
train
function
def test_api_admin_user_patch_me_logged_in(): """Can an admin patch /api/v1/users/me""" app = create_ctfd() with app.app_context(): with login_as_user(app, name="admin") as client: r = client.patch( "/api/v1/users/me", json={ "n...
def test_api_admin_user_patch_me_logged_in():
"""Can an admin patch /api/v1/users/me""" app = create_ctfd() with app.app_context(): with login_as_user(app, name="admin") as client: r = client.patch( "/api/v1/users/me", json={ "name": "user", "email": "us...
"password": "password", "confirm": "password", "country": "US", }, ) assert r.status_code == 200 assert r.get_json()["data"]["country"] == "US" destroy_ctfd(app) def test_api_admin_user_patch_me_lo...
64
64
173
10
54
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_admin_user_patch_me_logged_in
test_api_admin_user_patch_me_logged_in
395
416
395
395
2d24d0750d7d166985aad427b604e8ec374442fe
bigcode/the-stack
train
4c939fe50a62f71fdc5634e9
train
function
def test_api_user_patch_non_admin(): """Can a user patch /api/v1/users/<user_id> if not admin""" app = create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.patch("/api/v1/users/2", json="") assert r.status_code =...
def test_api_user_patch_non_admin():
"""Can a user patch /api/v1/users/<user_id> if not admin""" app = create_ctfd() with app.app_context(): register_user(app) with app.test_client() as client: r = client.patch("/api/v1/users/2", json="") assert r.status_code == 403 destroy_ctfd(app)
.get("/api/v1/users/2") assert r.status_code == 200 set_config("account_visibility", "admins") r = client.get("/api/v1/users/2") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_patch_non_admin():
64
64
85
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_patch_non_admin
test_api_user_patch_non_admin
283
291
283
283
a442bbcdabfe7fa8ee7c4b4274de135495328560
bigcode/the-stack
train
272fc9be8948e46ca002aea0
train
function
def test_api_user_get_fails(): """Can a user get /api/v1/users/<user_id>/fails if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/fails") assert r.status_code == 200 ...
def test_api_user_get_fails():
"""Can a user get /api/v1/users/<user_id>/fails if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/fails") assert r.status_code == 200 destroy_ctfd(app)
app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/fails") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_fails():
64
64
86
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_fails
test_api_user_get_fails
634
642
634
634
98477c1c9b42a21921e8493460f98b62b8b4cd59
bigcode/the-stack
train
bdfa04e442dd245b6a5d4163
train
function
def test_api_user_get_me_awards_not_logged_in(): """Can a user get /api/v1/users/me/awards if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/awards", json="") assert r.status_code == 403 ...
def test_api_user_get_me_awards_not_logged_in():
"""Can a user get /api/v1/users/me/awards if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me/awards", json="") assert r.status_code == 403 destroy_ctfd(app)
fails for the user admin = login_as_user(app, name="admin") r = admin.get("/api/v1/users/2/fails") assert r.get_json()["meta"]["count"] == 2 destroy_ctfd(app) def test_api_user_get_me_awards_not_logged_in():
64
64
87
12
52
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_awards_not_logged_in
test_api_user_get_me_awards_not_logged_in
685
692
685
685
ec1b8b185adde4d23fc09ffe9252e01dc320e2c6
bigcode/the-stack
train
fccb6ef46fc56d4a3cdd36ea
train
function
def test_api_user_get_awards(): """Can a user get /api/v1/users/<user_id>/awards if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/awards") assert r.status_code == 2...
def test_api_user_get_awards():
"""Can a user get /api/v1/users/<user_id>/awards if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/2/awards") assert r.status_code == 200 destroy_ctfd(app)
(user_mode="users") with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v1/users/me/awards") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_awards():
64
64
88
8
56
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_awards
test_api_user_get_awards
706
714
706
706
c2bceb1fd7b0769eafcbce57d6bec2493c87e502
bigcode/the-stack
train
2ed0a7bc2d9fbef0a1d3d704
train
function
def test_api_user_get_fails_after_freze_time(): """Can a user get /api/v1/users/<user_id>/fails after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd.io...
def test_api_user_get_fails_after_freze_time():
"""Can a user get /api/v1/users/<user_id>/fails after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd.io") # Friday, October 6, 2017 12:00:00 ...
= client.get("/api/v1/users/me/fails") assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_fails(): """Can a user get /api/v1/users/<user_id>/fails if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(a...
126
126
420
13
113
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_fails_after_freze_time
test_api_user_get_fails_after_freze_time
645
682
645
645
d77aba8ca682e61ff9fdb80ed80fbbc960a4aa04
bigcode/the-stack
train
9fe06defd72089241603947f
train
function
def test_api_user_get_me_not_logged_in(): """Can a user get /api/v1/users/me if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me") assert r.status_code == 302 destroy_ctfd(app)
def test_api_user_get_me_not_logged_in():
"""Can a user get /api/v1/users/me if not logged in""" app = create_ctfd() with app.app_context(): with app.test_client() as client: r = client.get("/api/v1/users/me") assert r.status_code == 302 destroy_ctfd(app)
("/api/v1/users/2", json="") assert r.status_code == 200 assert r.get_json().get("data") is None assert Users.query.filter_by(id=2).first() is None destroy_ctfd(app) def test_api_user_get_me_not_logged_in():
64
64
76
10
54
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_me_not_logged_in
test_api_user_get_me_not_logged_in
343
350
343
343
65bf792702a247579690c40061fc89dededc39b3
bigcode/the-stack
train
76fef39a4e2d0e1c60b6936f
train
function
def test_api_user_get_schema(): """Can a user get /api/v1/users/<user_id> doesn't return unnecessary data""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") # ID 2 register_user(app, name="user2", email="user2@ctfd.io") # ID 3 ...
def test_api_user_get_schema():
"""Can a user get /api/v1/users/<user_id> doesn't return unnecessary data""" app = create_ctfd() with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") # ID 2 register_user(app, name="user2", email="user2@ctfd.io") # ID 3 with app.test_client() as cl...
with login_as_user(app, "admin") as admin: r = admin.post( "/api/v1/users/2/email", json={"text": "email should be accepted"} ) assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_schema():
64
64
214
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_schema
test_api_user_get_schema
865
885
865
865
3cdb65e54856baf74f798b0780fb7b6799d19dd6
bigcode/the-stack
train
5423278c7cf5461bf5576238
train
function
def test_api_user_get_awards_after_freze_time(): """Can a user get /api/v1/users/<user_id>/awards after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd....
def test_api_user_get_awards_after_freze_time():
"""Can a user get /api/v1/users/<user_id>/awards after freeze time""" app = create_ctfd(user_mode="users") with app.app_context(): register_user(app, name="user1", email="user1@ctfd.io") register_user(app, name="user2", email="user2@ctfd.io") # Friday, October 6, 2017 12:00:00...
assert r.status_code == 200 destroy_ctfd(app) def test_api_user_get_awards(): """Can a user get /api/v1/users/<user_id>/awards if logged in""" app = create_ctfd() with app.app_context(): register_user(app) with login_as_user(app) as client: r = client.get("/api/v...
115
115
386
13
102
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_user_get_awards_after_freze_time
test_api_user_get_awards_after_freze_time
717
753
717
717
d40bfa5a62e6ccf885f59cf9e06d9240b16ae918
bigcode/the-stack
train
b75ec9d0b8a85cd69aa1334c
train
function
def test_api_team_get_admin(): """Can a user get /api/v1/users/<user_id> if users are viewed by admins only""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: gen_user(app.db) set_config("account_visibility", "public") ...
def test_api_team_get_admin():
"""Can a user get /api/v1/users/<user_id> if users are viewed by admins only""" app = create_ctfd() with app.app_context(): with login_as_user(app, "admin") as client: gen_user(app.db) set_config("account_visibility", "public") r = client.get("/api/v1/users/...
client.get("/api/v1/users/2") assert r.status_code == 200 set_config("account_visibility", "admins") r = client.get("/api/v1/users/2") assert r.status_code == 404 destroy_ctfd(app) def test_api_team_get_admin():
64
64
164
7
57
KaitoRyouga/CTFd
tests/api/v1/test_users.py
Python
test_api_team_get_admin
test_api_team_get_admin
265
280
265
265
d21ffbf18ac6d50d6c27ae8f427a900c6a6eacba
bigcode/the-stack
train
dfbde0d2342af7d3b1cc4e8f
train
class
class IncorrectArgumentsError(ValueError): pass
class IncorrectArgumentsError(ValueError):
pass
__all__ = [ "SamplingError", "IncorrectArgumentsError", "TraceDirectoryError", "ImputationWarning", ] class SamplingError(RuntimeError): pass class IncorrectArgumentsError(ValueError):
45
64
10
7
37
He1oise/pymc3
pymc3/exceptions.py
Python
IncorrectArgumentsError
IncorrectArgumentsError
13
14
13
13
8f8c772a24acc333d83facee98e4196f45cce573
bigcode/the-stack
train
f2bee01daf82c0f354eb23f7
train
class
class SamplingError(RuntimeError): pass
class SamplingError(RuntimeError):
pass
__all__ = [ "SamplingError", "IncorrectArgumentsError", "TraceDirectoryError", "ImputationWarning", ] class SamplingError(RuntimeError):
35
64
9
6
29
He1oise/pymc3
pymc3/exceptions.py
Python
SamplingError
SamplingError
9
10
9
9
8451423b20fb42b590e5ab4b2bfa9fbc9617600c
bigcode/the-stack
train
fdd15d9a5185833df030c8f5
train
class
class ImputationWarning(UserWarning): """Warning that there are missing values that will be imputed.""" pass
class ImputationWarning(UserWarning):
"""Warning that there are missing values that will be imputed.""" pass
DirectoryError", "ImputationWarning", ] class SamplingError(RuntimeError): pass class IncorrectArgumentsError(ValueError): pass class TraceDirectoryError(ValueError): """Error from trying to load a trace from an incorrectly-structured directory,""" pass class ImputationWarning(UserWarning):
64
64
24
7
56
He1oise/pymc3
pymc3/exceptions.py
Python
ImputationWarning
ImputationWarning
23
26
23
23
e0c64f745c473a865e00bdb7dc642a34709ea401
bigcode/the-stack
train
8136002e7b0cc67695bec6a6
train
class
class TraceDirectoryError(ValueError): """Error from trying to load a trace from an incorrectly-structured directory,""" pass
class TraceDirectoryError(ValueError):
"""Error from trying to load a trace from an incorrectly-structured directory,""" pass
__all__ = [ "SamplingError", "IncorrectArgumentsError", "TraceDirectoryError", "ImputationWarning", ] class SamplingError(RuntimeError): pass class IncorrectArgumentsError(ValueError): pass class TraceDirectoryError(ValueError):
55
64
28
7
47
He1oise/pymc3
pymc3/exceptions.py
Python
TraceDirectoryError
TraceDirectoryError
17
20
17
17
57520028f03223df108a4c21d5191e15120d8cd3
bigcode/the-stack
train
028671dd16a7f6e458c7039d
train
function
def get_diagonale_code(grid: str) -> str: flag=True temp=grid.split("\n") for i,j in enumerate(temp): temp[i]=j.split() res="" x=0 y=0 while True: try: res+=temp[y][x] if y==len(temp)-1: flag=False elif y==0 and not flag: ...
def get_diagonale_code(grid: str) -> str:
flag=True temp=grid.split("\n") for i,j in enumerate(temp): temp[i]=j.split() res="" x=0 y=0 while True: try: res+=temp[y][x] if y==len(temp)-1: flag=False elif y==0 and not flag: flag=True y+=1 i...
def get_diagonale_code(grid: str) -> str:
13
64
115
13
0
mwk0408/codewars_solutions
6 kyu/Decode Diagonal.py
Python
get_diagonale_code
get_diagonale_code
1
19
1
1
45ca3ce23d23a665b033df99418e10ab38cbd444
bigcode/the-stack
train
43edba37bfdab2975aef2528
train
class
class BAT(MgmtObj): def __init__(self, dct:JSON=None, pi:str=None, create:bool=False) -> None: self.resourceAttributePolicies = batPolicies # only the resource type's own policies super().__init__(dct, pi, mgd=T.BAT, create=create, attributePolicies=attributePolicies) if self.dict is not None: self.setAttri...
class BAT(MgmtObj):
def __init__(self, dct:JSON=None, pi:str=None, create:bool=False) -> None: self.resourceAttributePolicies = batPolicies # only the resource type's own policies super().__init__(dct, pi, mgd=T.BAT, create=create, attributePolicies=attributePolicies) if self.dict is not None: self.setAttribute('btl', defaultBa...
= 3 btsDAMAGED = 4 btsLOW_BATTERY = 5 btsNOT_INSTALLED = 6 btsUNKNOWN = 7 defaultBatteryLevel = 100 defaultBatteryStatus = btsUNKNOWN class BAT(MgmtObj):
64
64
111
6
57
ROTehc/ACME-oneM2M-CSE
acme/resources/BAT.py
Python
BAT
BAT
34
42
34
35
bd02cc1eda5a6dd3dc3aeee325458b2b0e78842f
bigcode/the-stack
train
4dfe8254838f624522db98fd
train
class
class InstalledDepsB(Package): """Used by test_installed_deps test case.""" # a # / \ # b c b --> d build/link # |\ /| b --> e build/link # |/ \| c --> d build # d e c --> e build/link homepage = "http://www.example.com" url = "http://www.example.com/...
class InstalledDepsB(Package):
"""Used by test_installed_deps test case.""" # a # / \ # b c b --> d build/link # |\ /| b --> e build/link # |/ \| c --> d build # d e c --> e build/link homepage = "http://www.example.com" url = "http://www.example.com/b-1.0.tar.gz" version("1",...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class InstalledDepsB(Package):
62
64
195
7
55
jeanbez/spack
var/spack/repos/builtin.mock/packages/installed-deps-b/package.py
Python
InstalledDepsB
InstalledDepsB
9
26
9
9
6e1ab154c864e32186c3332a8744dc74054ff40f
bigcode/the-stack
train
0f70af3f398b522ac8abc6ee
train
function
def getext(filename): #ret = os.path.splitext(filename)[-1].lower() ret = os.path.basename(filename).lower() if(len(ret) == 0) : return "none" return ret
def getext(filename): #ret = os.path.splitext(filename)[-1].lower()
ret = os.path.basename(filename).lower() if(len(ret) == 0) : return "none" return ret
setup( ) : load_blacklist('blacklist.json') #---------------------------- #---------------------------- # Watchdog BASEDIR = os.path.abspath(os.path.dirname(__file__)) TARGET_FILE = ('blacklist.json') def getext(filename): #ret = os.path.splitext(filename)[-1].lower()
64
64
48
19
45
rainforest-tokyo/pfloyd
netBlocker.py
Python
getext
getext
45
50
45
46
dafb11582bccc9f7e228b819c81db7af8f50e12d
bigcode/the-stack
train
f7c527501aea3447e33855f7
train
function
def main(argv) : global logger filename = os.path.join( BASEDIR, TARGET_FILE ) load_blacklist(filename) print( '#### START ####' ) sys.stdout.flush() setup() logger = Logger("/var/log/pfloyd.log", False) event_handler = ChangeHandler() observer = Observer() observer.schedule...
def main(argv) :
global logger filename = os.path.join( BASEDIR, TARGET_FILE ) load_blacklist(filename) print( '#### START ####' ) sys.stdout.flush() setup() logger = Logger("/var/log/pfloyd.log", False) event_handler = ChangeHandler() observer = Observer() observer.schedule(event_handler,BA...
, "port":0, "protocol":""} result = check_ip( data ) if result : print( data ) logger.log( data ) sys.stdout.flush() pkt.drop() else: sys.stdout.flush() pkt.accept() #---------------------------- def main(argv) :
63
64
138
5
58
rainforest-tokyo/pfloyd
netBlocker.py
Python
main
main
107
134
107
107
8aff371a625a3aeae960d9ee3b19c15a6f30658d
bigcode/the-stack
train
83f4787ddd3d2e5d12611e44
train
function
def setup( ) : load_blacklist('blacklist.json')
def setup( ) :
load_blacklist('blacklist.json')
from watchdog.observers import Observer from Logger import Logger #---------------------------- # BlackList blacklist = [] def load_blacklist( filename ) : global blacklist with open(filename, 'r') as f: blacklist = json.load(f) print (blacklist) def setup( ) :
64
64
14
5
59
rainforest-tokyo/pfloyd
netBlocker.py
Python
setup
setup
36
37
36
36
57c114abd4a60fc36bb695b7c7b82f9cc324a27c
bigcode/the-stack
train
acdd95f328c13db9f4e80d94
train
class
class ChangeHandler(FileSystemEventHandler): def on_created(self, event): if event.is_directory: return #if getext(event.src_path) in TARGET_FILE: # print('%s has been created.' % event.src_path) def on_modified(self, event): if event.is_directory: re...
class ChangeHandler(FileSystemEventHandler):
def on_created(self, event): if event.is_directory: return #if getext(event.src_path) in TARGET_FILE: # print('%s has been created.' % event.src_path) def on_modified(self, event): if event.is_directory: return if getext(event.src_path) in TARG...
TARGET_FILE = ('blacklist.json') def getext(filename): #ret = os.path.splitext(filename)[-1].lower() ret = os.path.basename(filename).lower() if(len(ret) == 0) : return "none" return ret class ChangeHandler(FileSystemEventHandler):
64
64
107
8
55
rainforest-tokyo/pfloyd
netBlocker.py
Python
ChangeHandler
ChangeHandler
52
68
52
53
aeba8649a90b6454324c1c9f664a2217afe9f714
bigcode/the-stack
train
c0bc8221c27f12a890c297d9
train
function
def load_blacklist( filename ) : global blacklist with open(filename, 'r') as f: blacklist = json.load(f) print (blacklist)
def load_blacklist( filename ) :
global blacklist with open(filename, 'r') as f: blacklist = json.load(f) print (blacklist)
os import json import ipaddress from scapy.all import * from netfilterqueue import NetfilterQueue from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer from Logger import Logger #---------------------------- # BlackList blacklist = [] def load_blacklist( filename ) :
64
64
36
8
56
rainforest-tokyo/pfloyd
netBlocker.py
Python
load_blacklist
load_blacklist
29
34
29
29
4987613814554666dcaaaf96bad6a470a317301b
bigcode/the-stack
train
6fe385a75d4df15b14be3e91
train
function
def netblocker(pkt): packet = IP(pkt.get_payload()) data = {"ip":packet.src, "port":0, "protocol":""} result = check_ip( data ) if result : print( data ) logger.log( data ) sys.stdout.flush() pkt.drop() else: sys.stdout.flush() pkt.accept()
def netblocker(pkt):
packet = IP(pkt.get_payload()) data = {"ip":packet.src, "port":0, "protocol":""} result = check_ip( data ) if result : print( data ) logger.log( data ) sys.stdout.flush() pkt.drop() else: sys.stdout.flush() pkt.accept()
["port"] != 0) and (ip_info["port"] not in blacklist["port"])) : continue if((ip_info["protocol"] != "") and (ip_info["protocol"] != blacklist["protocol"])) : continue return True return False def netblocker(pkt):
64
64
77
6
57
rainforest-tokyo/pfloyd
netBlocker.py
Python
netblocker
netblocker
93
104
93
93
3277e6aa864b32f79a841e4439ccba3b1415a3a2
bigcode/the-stack
train
0e9bccaf1382de26a3261afc
train
function
def check_ip( ip_info ) : global blacklist global logger for item in blacklist : ip=ipaddress.ip_address(u""+ip_info["ip"]) #net=ipaddress.ip_network(u""+item["ip"]) net=ipaddress.ip_network(u""+item["ip"], False) if ip in net: if((ip_info["port"] != 0) and (ip_i...
def check_ip( ip_info ) :
global blacklist global logger for item in blacklist : ip=ipaddress.ip_address(u""+ip_info["ip"]) #net=ipaddress.ip_network(u""+item["ip"]) net=ipaddress.ip_network(u""+item["ip"], False) if ip in net: if((ip_info["port"] != 0) and (ip_info["port"] not in blackli...
TARGET_FILE: # print('%s has been deleted.' % event.src_path) #---------------------------- #---------------------------- # TCP/UDP Block # ip_info = {"ip":"192.168.0.32", "port":0, "protocol":""} def check_ip( ip_info ) :
64
64
137
8
56
rainforest-tokyo/pfloyd
netBlocker.py
Python
check_ip
check_ip
76
91
76
76
3fa3e448d94acb73f1289cfa402cfb9724d57f70
bigcode/the-stack
train
56977ff2649c9e501e3cf979
train
class
class V1ReplicationController(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, metadata=None, spec=None, status=None): """ V1ReplicationController - a model defined in Swagger :param...
class V1ReplicationController(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, metadata=None, spec=None, status=None): """ V1ReplicationController - a model defined in Swagger :param dict swaggerTypes: The key is attribut...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.5.0-beta.1 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "Lice...
201
256
1,127
7
193
SEJeff/client-python
kubernetes/client/models/v1_replication_controller.py
Python
V1ReplicationController
V1ReplicationController
30
178
30
30
2637d4678fbf7174e3fa4bb26f0555b64cbcc84f
bigcode/the-stack
train
39c6bfee99ef803ba6092c2b
train
class
class IloPXEDeployTestCase(db_base.DbTestCase): def setUp(self): super(IloPXEDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="pxe_ilo") self.node = obj_utils.create_test_node( self.context, driver='pxe_ilo', driver_info=INFO_DICT) @mock.patch.objec...
class IloPXEDeployTestCase(db_base.DbTestCase):
def setUp(self): super(IloPXEDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="pxe_ilo") self.node = obj_utils.create_test_node( self.context, driver='pxe_ilo', driver_info=INFO_DICT) @mock.patch.object(iscsi_deploy.ISCSIDeploy, 'validate', spec_set=...
_erase_devices=0, group='ilo') get_clean_step_mock.return_value = [{ 'step': 'erase_devices', 'priority': 10, 'interface': 'deploy', 'reboot_requested': False }] with task_manager.acquire(self.context, self.node.uuid, ...
256
256
1,238
13
243
pyrrrat/moved-ironic
ironic/tests/unit/drivers/modules/ilo/test_deploy.py
Python
IloPXEDeployTestCase
IloPXEDeployTestCase
419
533
419
420
867bf94f5131488c8235549b4483a89baa3a777b
bigcode/the-stack
train
2843e297f2583a189f7631cc
train
class
class IloDeployPrivateMethodsTestCase(db_base.DbTestCase): def setUp(self): super(IloDeployPrivateMethodsTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="iscsi_ilo") self.node = obj_utils.create_test_node( self.context, driver='iscsi_ilo', driver_info=INFO_DI...
class IloDeployPrivateMethodsTestCase(db_base.DbTestCase):
def setUp(self): super(IloDeployPrivateMethodsTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="iscsi_ilo") self.node = obj_utils.create_test_node( self.context, driver='iscsi_ilo', driver_info=INFO_DICT) @mock.patch.object(ilo_common, 'set_secure_boot_mod...
" 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. """Test class for deploy methods used by iLO modules.""" import mock from oslo_config import cfg import six from ironic.c...
256
256
1,494
13
242
pyrrrat/moved-ironic
ironic/tests/unit/drivers/modules/ilo/test_deploy.py
Python
IloDeployPrivateMethodsTestCase
IloDeployPrivateMethodsTestCase
47
193
47
48
7faabf472875f7dc5b74f488013d46a40c454bed
bigcode/the-stack
train
7afe9e3d09b2f3d7ebab6365
train
class
class IloVirtualMediaIscsiDeployTestCase(db_base.DbTestCase): def setUp(self): super(IloVirtualMediaIscsiDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="iscsi_ilo") self.node = obj_utils.create_test_node( self.context, driver='iscsi_ilo', driver_info=I...
class IloVirtualMediaIscsiDeployTestCase(db_base.DbTestCase):
def setUp(self): super(IloVirtualMediaIscsiDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="iscsi_ilo") self.node = obj_utils.create_test_node( self.context, driver='iscsi_ilo', driver_info=INFO_DICT) @mock.patch.object(ilo_common, 'update_secure_bo...
autospec=True) @mock.patch.object(ilo_deploy, '_disable_secure_boot', spec_set=True, autospec=True) @mock.patch.object(manager_utils, 'node_power_action', spec_set=True, autospec=True) def test__prepare_node_for_deploy_sec_boot_on_inst_inf...
256
256
943
16
240
pyrrrat/moved-ironic
ironic/tests/unit/drivers/modules/ilo/test_deploy.py
Python
IloVirtualMediaIscsiDeployTestCase
IloVirtualMediaIscsiDeployTestCase
196
284
196
197
e164b48f4525a7d145010f6c6d85b985d310f847
bigcode/the-stack
train
5a42254a68872101c50c3260
train
class
class IloVirtualMediaAgentDeployTestCase(db_base.DbTestCase): def setUp(self): super(IloVirtualMediaAgentDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="agent_ilo") self.node = obj_utils.create_test_node( self.context, driver='agent_ilo', driver_info=I...
class IloVirtualMediaAgentDeployTestCase(db_base.DbTestCase):
def setUp(self): super(IloVirtualMediaAgentDeployTestCase, self).setUp() mgr_utils.mock_the_extension_manager(driver="agent_ilo") self.node = obj_utils.create_test_node( self.context, driver='agent_ilo', driver_info=INFO_DICT) @mock.patch.object(agent.AgentDeploy, 'tear_down...
, '_prepare_node_for_deploy', spec_set=True, autospec=True) def test_prepare(self, func_prepare_node_for_deploy, iscsi_deploy_prepare_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: ...
256
256
1,224
14
242
pyrrrat/moved-ironic
ironic/tests/unit/drivers/modules/ilo/test_deploy.py
Python
IloVirtualMediaAgentDeployTestCase
IloVirtualMediaAgentDeployTestCase
287
416
287
288
36d95721eb6d6fbc0c2b80c3c75866a0a4a25cb2
bigcode/the-stack
train
f268dbbd30657f9d8ae0e01a
train
function
@cache(maxsize=None) def ao(s1, s2, c): if s1 and s2: return 0.25 return 1 - (s1 + s2 + c) / 4
@cache(maxsize=None) def ao(s1, s2, c):
if s1 and s2: return 0.25 return 1 - (s1 + s2 + c) / 4
= max(a, min_val) b = max(b, min_val) c = max(c, min_val) d = max(d, min_val) return (a + b + c + d) / 4 @cache(maxsize=None) def ao(s1, s2, c):
64
64
47
16
47
CrispyFlowe/python-minecraft-clone
community/subchunk.py
Python
ao
ao
20
24
20
21
b45a9ecef1cc33af258ae521c5d54816a1090d7f
bigcode/the-stack
train
d5a039a1f45499038373656b
train
function
@cache(maxsize=None) def smooth(a, b, c, d): if not a or not b or not c or not d: l = (a, *(i for i in (b, c, d) if i)) min_val = min(l) a = max(a, min_val) b = max(b, min_val) c = max(c, min_val) d = max(d, min_val) return (a + b + c + d) / 4
@cache(maxsize=None) def smooth(a, b, c, d):
if not a or not b or not c or not d: l = (a, *(i for i in (b, c, d) if i)) min_val = min(l) a = max(a, min_val) b = max(b, min_val) c = max(c, min_val) d = max(d, min_val) return (a + b + c + d) / 4
from util import * import glm from functools import lru_cache as cache SUBCHUNK_WIDTH = 4 SUBCHUNK_HEIGHT = 4 SUBCHUNK_LENGTH = 4 @cache(maxsize=None) def smooth(a, b, c, d):
57
64
107
16
40
CrispyFlowe/python-minecraft-clone
community/subchunk.py
Python
smooth
smooth
9
18
9
10
63b5f7e1a57df1143a09a621666ca0d48c71e7f1
bigcode/the-stack
train
928f7c092ae35dce90e88783
train
class
class Subchunk: def __init__(self, parent, subchunk_position): self.parent = parent self.world = self.parent.world self.subchunk_position = subchunk_position self.local_position = ( self.subchunk_position[0] * SUBCHUNK_WIDTH, self.subchunk_position[1] * SUBCHUNK_HEIGHT, self.subchunk_position[2] * S...
class Subchunk:
def __init__(self, parent, subchunk_position): self.parent = parent self.world = self.parent.world self.subchunk_position = subchunk_position self.local_position = ( self.subchunk_position[0] * SUBCHUNK_WIDTH, self.subchunk_position[1] * SUBCHUNK_HEIGHT, self.subchunk_position[2] * SUBCHUNK_LENGTH) ...
from util import * import glm from functools import lru_cache as cache SUBCHUNK_WIDTH = 4 SUBCHUNK_HEIGHT = 4 SUBCHUNK_LENGTH = 4 @cache(maxsize=None) def smooth(a, b, c, d): if not a or not b or not c or not d: l = (a, *(i for i in (b, c, d) if i)) min_val = min(l) a = max(a, min_val) b = max(b, min_val) ...
199
256
2,081
4
194
CrispyFlowe/python-minecraft-clone
community/subchunk.py
Python
Subchunk
Subchunk
26
233
26
26
fa036dac5fda36ae30c5698557bbdebd94966097
bigcode/the-stack
train
b2defb718739e441c2f39e8f
train
function
def five_crop(img, size): """Crop the given numpy ndarray into four corners and the central crop. .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output s...
def five_crop(img, size):
"""Crop the given numpy ndarray into four corners and the central crop. .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: size (sequence or int): Desired output size of the crop. If size i...
Returns: numpy ndarray: Vertically flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) if img.shape[2]==1: return cv2.flip(img, 0)[:,:,np.newaxis] else: return cv2.flip(img, 0) # img[::-1] is much fa...
103
103
344
7
96
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
five_crop
five_crop
284
312
284
284
dda09944324288d1b197890906e4f95176c05488
bigcode/the-stack
train
94e1900259f7c5aeb7978de2
train
function
def adjust_gamma(img, gamma, gain=1): """Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: .. math:: I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} See...
def adjust_gamma(img, gamma, gain=1):
"""Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: .. math:: I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} See `Gamma Correction`_ for more details....
.convert('HSV').split() np_h = np.array(h, dtype=np.uint8) # uint8 addition take cares of rotation across boundaries with np.errstate(over='ignore'): np_h += np.uint8(hue_factor * 255) h = Image.fromarray(np_h, 'L') img = Image.merge('HSV', (h, s, v)).convert(input_mode) return np.arra...
102
102
342
11
91
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
adjust_gamma
adjust_gamma
454
481
454
454
e4e056474206720ac9b7404fbe60a8a60a314435
bigcode/the-stack
train
11c6a10654a30ded53b719fa
train
function
def scale(*args, **kwargs): warnings.warn("The use of the transforms.Scale transform is deprecated, " + "please use transforms.Resize instead.") return resize(*args, **kwargs)
def scale(*args, **kwargs):
warnings.warn("The use of the transforms.Scale transform is deprecated, " + "please use transforms.Resize instead.") return resize(*args, **kwargs)
=(ow, oh), interpolation=interpolation) else: output = cv2.resize(img, dsize=size[::-1], interpolation=interpolation) if img.shape[2]==1: return(output[:,:,np.newaxis]) else: return(output) def scale(*args, **kwargs):
64
64
41
8
56
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
scale
scale
141
144
141
141
554e3b316354eb288d429f5dce816ec7e1b8e930
bigcode/the-stack
train
d40483ee7d5a89216240a515
train
function
def crop(img, i, j, h, w): """Crop the given PIL Image. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. Returns: numpy ndarray: Cropped image. ...
def crop(img, i, j, h, w):
"""Crop the given PIL Image. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. Returns: numpy ndarray: Cropped image. """ if not _is_numpy...
.newaxis]) else: return(cv2.copyMakeBorder(img, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right, borderType=_cv2_pad_to_str[padding_mode], value=fill)) def crop(img, i, j, h, w):
64
64
117
12
52
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
crop
crop
204
218
204
204
12a0665c5caf68d0982356fceecae982de4e163c
bigcode/the-stack
train
775c486639dba01a781c5b5f
train
function
def to_grayscale(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. Returns: numpy ndarray: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel ...
def to_grayscale(img, num_output_channels=1):
"""Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. Returns: numpy ndarray: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_output_channels = 3 : returned i...
interpolation, borderMode=mode, borderValue=fillcolor)[:,:,np.newaxis] else: return cv2.warpAffine(img, matrix, output_size[::-1],interpolation, borderMode=mode, borderValue=fillcolor) def to_grayscale(img, num_output_channels=1):
64
64
200
12
52
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
to_grayscale
to_grayscale
572
589
572
572
d030ecb6ef6a08d88cc793e786c85e83c080102c
bigcode/the-stack
train
81adcbb775f527fdb74ca74e
train
function
def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img):
64
64
27
7
56
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
_is_numpy_image
_is_numpy_image
56
57
56
56
b12fd4e0b49fc139af518b6ea0b0675fb916a33c
bigcode/the-stack
train
b97b7b1431a8583ac34754b9
train
function
def perspective(img, fov=45, anglex=0, angley=0, anglez=0, shear=0, translate=(0, 0), scale=(1, 1), resample='bilinear', fillcolor=(0, 0, 0)): """ This function is partly referred to https://blog.csdn.net/dcrmg/article/details/80273818 """ imgtype = img.dtype gray_scale = False ...
def perspective(img, fov=45, anglex=0, angley=0, anglez=0, shear=0, translate=(0, 0), scale=(1, 1), resample='bilinear', fillcolor=(0, 0, 0)):
""" This function is partly referred to https://blog.csdn.net/dcrmg/article/details/80273818 """ imgtype = img.dtype gray_scale = False if len(img.shape) == 2: gray_scale = True img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) h, w, _ = img.shape centery = h * 0.5 center...
(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. Returns: numpy ndarray: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_ou...
256
256
1,048
60
195
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
perspective
perspective
592
678
592
593
16d5c23b3dd4185e04c8713687f6ff5f46c9ca80
bigcode/the-stack
train
1c19eacfb1668368fd802a4a
train
function
def _get_affine_matrix(center, angle, translate, scale, shear): # Helper method to compute matrix for affine transformation # We need compute affine transformation matrix: M = T * C * RSS * C^-1 # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] # C is translation matrix to keep cent...
def _get_affine_matrix(center, angle, translate, scale, shear): # Helper method to compute matrix for affine transformation # We need compute affine transformation matrix: M = T * C * RSS * C^-1 # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] # C is translation matrix to keep cent...
angle = math.radians(angle) shear = math.radians(shear) # scale = 1.0 / scale T = np.array([[1, 0, translate[0]], [0, 1, translate[1]], [0,0,1]]) C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0,0,1]]) RSS = np.array([[math.cos(angle)*scale, -math.sin(angle+shear)*scale, 0], ...
def _get_affine_matrix(center, angle, translate, scale, shear): # Helper method to compute matrix for affine transformation # We need compute affine transformation matrix: M = T * C * RSS * C^-1 # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] # C is translation matrix to keep cent...
190
106
356
190
0
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
_get_affine_matrix
_get_affine_matrix
513
534
513
522
1d5aaaa5ba164a7af70f303fce1a4b76503817a6
bigcode/the-stack
train
90eebb05768c08c6f2b0f938
train
function
def resize(img, size, interpolation=cv2.INTER_LINEAR): r"""Resize the input numpy ndarray to the given size. Args: img (numpy ndarray): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (w, h), the output size will be matched to this. If siz...
def resize(img, size, interpolation=cv2.INTER_LINEAR):
r"""Resize the input numpy ndarray to the given size. Args: img (numpy ndarray): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (w, h), the output size will be matched to this. If size is an int, the smaller edge of the image ...
, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') ...
127
127
424
12
114
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
resize
resize
101
138
101
101
89c31f7fb70e0c71831d0a3c74fdf49ee42d197b
bigcode/the-stack
train
34bdce1275fb1174485afb27
train
function
def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_numpy_image(pic)): raise TypeError('...
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_numpy_image(pic)): raise TypeError('pic should be ndarra...
: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic):
64
64
145
5
59
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
to_tensor
to_tensor
60
77
60
60
c95402410f3fc910639c22ee028093cdfe974d36
bigcode/the-stack
train
37201635b0cb029d02930d38
train
function
def adjust_contrast(img, contrast_factor): """Adjust contrast of an mage. Args: img (numpy ndarray): numpy ndarray to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original im...
def adjust_contrast(img, contrast_factor):
"""Adjust contrast of an mage. Args: img (numpy ndarray): numpy ndarray to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a fac...
# same thing but a bit slower # cv2.convertScaleAbs(img, alpha=brightness_factor, beta=0) if img.shape[2] == 1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table) def adjust_contrast(img, contrast_factor):
74
74
248
9
65
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
adjust_contrast
adjust_contrast
368
388
368
368
cea21faff5398c875b5b54db874ac7d05fd5e740
bigcode/the-stack
train
3b07e6486f218196c2bf8215
train
function
def vflip(img): """Vertically flip the given numpy ndarray. Args: img (numpy ndarray): Image to be flipped. Returns: numpy ndarray: Vertically flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) if img.sh...
def vflip(img):
"""Vertically flip the given numpy ndarray. Args: img (numpy ndarray): Image to be flipped. Returns: numpy ndarray: Vertically flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) if img.shape[2]==1: ...
(type(img))) # img[:,::-1] is much faster, but doesn't work with torch.from_numpy()! if img.shape[2]==1: return cv2.flip(img,1)[:,:,np.newaxis] else: return cv2.flip(img, 1) def vflip(img):
64
64
107
5
59
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
vflip
vflip
268
280
268
268
ab7cb27b61359f586a541bfb73ad462acb4aedd6
bigcode/the-stack
train
ba6c1c77a5ae246e16668207
train
function
def rotate(img, angle, resample=False, expand=False, center=None): """Rotate the image by angle. Args: img (numpy ndarray): numpy ndarray to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Im...
def rotate(img, angle, resample=False, expand=False, center=None):
"""Rotate the image by angle. Args: img (numpy ndarray): numpy ndarray to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional): An optional resampling filter...
88/how-to-change-image-illumination-in-opencv-python/41061351 table = np.array([((i / 255.0) ** gamma) * 255 * gain for i in np.arange(0, 256)]).astype('uint8') if img.shape[2]==1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table) def rotate(im...
111
111
373
16
95
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
rotate
rotate
484
510
484
484
0183c2754ddfac3db68ce2780d7b2af1bdc6ef17
bigcode/the-stack
train
6fe11fa896009911a7f0f808
train
function
def resized_crop(img, i, j, h, w, size, interpolation=cv2.INTER_LINEAR): """Crop the given numpy ndarray and resize it to desired size. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Le...
def resized_crop(img, i, j, h, w, size, interpolation=cv2.INTER_LINEAR):
"""Crop the given numpy ndarray and resize it to desired size. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: W...
i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resized_crop(img, i, j, h, w, size, interpolation=cv2.INTER_LINEAR):
64
64
196
21
43
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
resized_crop
resized_crop
231
249
231
231
d5bbf1c7e17ef8be85af155f107a9d2ad327788f
bigcode/the-stack
train
29735cf2a4d9bab917661d6f
train
function
def adjust_saturation(img, saturation_factor): """Adjust color saturation of an image. Args: img (numpy ndarray): numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while ...
def adjust_saturation(img, saturation_factor):
"""Adjust color saturation of an image. Args: img (numpy ndarray): numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a fac...
.Contrast(img) # img = enhancer.enhance(contrast_factor) if img.shape[2] == 1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table) def adjust_saturation(img, saturation_factor):
64
64
165
9
55
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
adjust_saturation
adjust_saturation
391
407
391
391
f54a7a66a85b4b202672f01ddcad8c827d837fac
bigcode/the-stack
train
ae348b987ff9353f8ef0f963
train
function
def ten_crop(img, size, vertical_flip=False): r"""Crop the given numpy ndarray into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). .. Note:: This transform returns a tuple of images and there may be a mismatch in the number o...
def ten_crop(img, size, vertical_flip=False):
r"""Crop the given numpy ndarray into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns....
_w, 0, crop_h, w) bl = crop(img, 0, h - crop_h, crop_w, h) br = crop(img, w - crop_w, h - crop_h, h,w) center = center_crop(img, (crop_h, crop_w)) return (tl, tr, bl, br, center) def ten_crop(img, size, vertical_flip=False):
87
87
293
11
76
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
ten_crop
ten_crop
315
344
315
315
cedbf193e793d034996413606eb2c8fd61da25c2
bigcode/the-stack
train
39ce5259f1468425c1874cfe
train
function
def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. .. note:: This transform acts in-place, i.e., it mutates the input tensor. See :class:`~torchvision.transforms.Normalize` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W...
def normalize(tensor, mean, std):
"""Normalize a tensor image with mean and standard deviation. .. note:: This transform acts in-place, i.e., it mutates the input tensor. See :class:`~torchvision.transforms.Normalize` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (...
handle numpy array img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility if isinstance(img, torch.ByteTensor) or img.dtype==torch.uint8: return img.float() else: return img def normalize(tensor, mean, std):
64
64
186
9
54
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
normalize
normalize
80
98
80
80
d675cd16ad982e1f01aeb7411404920016c8e7ab
bigcode/the-stack
train
97fb60cbc7df99dcf6598032
train
function
def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3
def _is_tensor_image(img):
return torch.is_tensor(img) and img.ndimension() == 3
{v:k for k,v in _cv2_interpolation_to_str.items()} def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img):
64
64
23
7
57
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
_is_tensor_image
_is_tensor_image
52
53
52
52
c504553b529a62875f39ae341bd53e66ab54bd61
bigcode/the-stack
train
41dcbe0d82974fb4641a125d
train
function
def adjust_hue(img, hue_factor): """Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be i...
def adjust_hue(img, hue_factor):
"""Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be in the interval `[-0.5, 0.5]`....
numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: numpy ndarray: Saturation adjusted image. """ ...
147
147
492
9
138
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
adjust_hue
adjust_hue
410
451
410
410
de84f61b598d5ce09d71a3fe03386f93aeefb46f
bigcode/the-stack
train
49e3ad1319fdd92c33ece157
train
function
def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image)
def _is_pil_image(img):
if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image)
cv2.INTER_AREA, 'bicubic':cv2.INTER_CUBIC, 'lanczos':cv2.INTER_LANCZOS4} _cv2_interpolation_from_str= {v:k for k,v in _cv2_interpolation_to_str.items()} def _is_pil_image(img):
63
64
40
8
55
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
_is_pil_image
_is_pil_image
45
49
45
45
11ad931d9063ee269c56cdb2f9a7856d64722b08
bigcode/the-stack
train
0d7e43072a8b6d5bdfdd3b0d
train
function
def adjust_brightness(img, brightness_factor): """Adjust brightness of an Image. Args: img (numpy ndarray): numpy ndarray to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the orig...
def adjust_brightness(img, brightness_factor):
"""Adjust brightness of an Image. Args: img (numpy ndarray): numpy ndarray to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by ...
for size." first_five = five_crop(img, size) if vertical_flip: img = vflip(img) else: img = hflip(img) second_five = five_crop(img, size) return first_five + second_five def adjust_brightness(img, brightness_factor):
66
66
220
9
56
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
adjust_brightness
adjust_brightness
347
365
347
347
e4e6c0d3a4fc3e1604aeeb788a6087071b396390
bigcode/the-stack
train
2f2a890ce13fb7321b1b6340
train
function
def pad(img, padding, fill=0, padding_mode='constant'): r"""Pad the given numpy ndarray on all sides with specified padding mode and fill value. Args: img (numpy ndarray): image to be padded. padding (int or tuple): Padding on each border. If a single int is provided this is used to ...
def pad(img, padding, fill=0, padding_mode='constant'):
r"""Pad the given numpy ndarray on all sides with specified padding mode and fill value. Args: img (numpy ndarray): image to be padded. padding (int or tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this i...
Got inappropriate size arg: {}'.format(size)) w, h, = img.shape[1], img.shape[0] if isinstance(size, int): if (w <= h and w == size) or (h <= w and h == size): return img if w < h: ow = size oh = int(size * h / w) output = cv2.resize(img, dsize=...
239
239
799
15
224
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
pad
pad
147
201
147
147
181abdbdb8aacbbad7c1d9b5b1a060888a6e88c1
bigcode/the-stack
train
f696b54962e5225618cafef8
train
function
def affine(img, angle, translate, scale, shear, interpolation=cv2.INTER_LINEAR, mode=cv2.BORDER_CONSTANT, fillcolor=0): """Apply affine transformation on the image keeping image center invariant Args: img (numpy ndarray): numpy ndarray to be transformed. angle (float or int): rotation angle in d...
def affine(img, angle, translate, scale, shear, interpolation=cv2.INTER_LINEAR, mode=cv2.BORDER_CONSTANT, fillcolor=0):
"""Apply affine transformation on the image keeping image center invariant Args: img (numpy ndarray): numpy ndarray to be transformed. angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction. translate (list or tuple of integers): horizontal and vertical...
0]], [0, 1, translate[1]], [0,0,1]]) C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0,0,1]]) RSS = np.array([[math.cos(angle)*scale, -math.sin(angle+shear)*scale, 0], [math.sin(angle)*scale, math.cos(angle+shear)*scale, 0], [0,0,1]]) matrix = T @ C @ RSS @ np.lina...
155
155
518
30
125
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
affine
affine
537
569
537
537
061ce6a652bf884b1ddb75928132f2a5deac757a
bigcode/the-stack
train
b5e45eb247a50cba3137fb16
train
function
def hflip(img): """Horizontally flip the given numpy ndarray. Args: img (numpy ndarray): image to be flipped. Returns: numpy ndarray: Horizontally flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy image. Got {}'.format(type(img))) # img...
def hflip(img):
"""Horizontally flip the given numpy ndarray. Args: img (numpy ndarray): image to be flipped. Returns: numpy ndarray: Horizontally flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy image. Got {}'.format(type(img))) # img[:,::-1] is much...
Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be numpy image' img = crop(img, i, j, h, w) img = resize(img, size, interpolation=interpolation) return img def hflip(img):
64
64
128
5
58
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
hflip
hflip
252
265
252
252
4c0edad78885c8ef9173b9960e35f60a41235b9b
bigcode/the-stack
train
9804d2e7e8df38d274200148
train
function
def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) h,w = img.shape[0:2] th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw)
def center_crop(img, output_size):
if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) h,w = img.shape[0:2] th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw)
the cropped image. Returns: numpy ndarray: Cropped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy image. Got {}'.format(type(img))) return img[i:i+h, j:j+w, :] def center_crop(img, output_size):
63
64
92
8
55
yenchiah/deep-smoke-machine
back-end/www/opencv_functional.py
Python
center_crop
center_crop
221
228
221
221
9cec24d1c7b684b785899109f2a9fd8f979dbf6b
bigcode/the-stack
train
c2d43caec197b6eee5f0eecf
train
class
class ExPaginator(Paginator): """ Adds a ``softlimit`` option to the class. If True, querying a page number larger than max. will not fail, but instead return the last available page. This is useful when the data source can not provide an exact count at all times (like some search engines), mean...
class ExPaginator(Paginator):
""" Adds a ``softlimit`` option to the class. If True, querying a page number larger than max. will not fail, but instead return the last available page. This is useful when the data source can not provide an exact count at all times (like some search engines), meaning the user could possibl...
import functools import math from django.conf import settings from django.core.paginator import InvalidPage, Page, Paginator class ExPaginator(Paginator):
32
123
411
6
25
derseeger/aldryn-search
aldryn_search/paginators.py
Python
ExPaginator
ExPaginator
8
54
8
8
b55c5e9c05298bc13bfc38bc104b710bfc7e3990
bigcode/the-stack
train