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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5716597b02d908dad0564ac0 | train | function | @pytest.mark.asyncio
async def test_cog_palette(create_cog_reader):
infile = "https://async-cog-reader-test-data.s3.amazonaws.com/cog_cmap.tif"
async with create_cog_reader(infile) as cog:
with rasterio.open(infile) as ds:
cog_interp = cog.color_interp
rio_interp = ds.colorinterp... | @pytest.mark.asyncio
async def test_cog_palette(create_cog_reader):
| infile = "https://async-cog-reader-test-data.s3.amazonaws.com/cog_cmap.tif"
async with create_cog_reader(infile) as cog:
with rasterio.open(infile) as ds:
cog_interp = cog.color_interp
rio_interp = ds.colorinterp
assert cog_interp[0].value == rio_interp[0].value
... | prox(
(
max(tile_count, next_tile_count)
/ min(tile_count, next_tile_count)
),
3,
)
== 4.0
)
except IndexError:
... | 64 | 64 | 107 | 16 | 47 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_palette | test_cog_palette | 77 | 85 | 77 | 78 | ba859ab6b869634109a789d827c1372cabcada4e | bigcode/the-stack | train |
11e7df51accba01b9918fe5b | train | function | @pytest.mark.asyncio
async def test_cog_has_alpha_band(create_cog_reader):
async with create_cog_reader(
"https://async-cog-reader-test-data.s3.amazonaws.com/cog_alpha_band.tif"
) as cog:
assert cog.has_alpha
async with create_cog_reader(TEST_DATA[0]) as cog:
assert not cog.has_alph... | @pytest.mark.asyncio
async def test_cog_has_alpha_band(create_cog_reader):
| async with create_cog_reader(
"https://async-cog-reader-test-data.s3.amazonaws.com/cog_alpha_band.tif"
) as cog:
assert cog.has_alpha
async with create_cog_reader(TEST_DATA[0]) as cog:
assert not cog.has_alpha
| ),
)
async def test_cog_mask_flags(create_cog_reader, infile, expected):
async with create_cog_reader(infile) as cog:
mask_flags = cog.mask_flags
assert expected == mask_flags
@pytest.mark.asyncio
async def test_cog_has_alpha_band(create_cog_reader):
| 64 | 64 | 80 | 18 | 45 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_has_alpha_band | test_cog_has_alpha_band | 120 | 128 | 120 | 121 | 1e44eaaaa580e958c5367ea3053f74229fe07ced | bigcode/the-stack | train |
78379e76200df0b0d29a5b18 | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_metadata(infile, create_cog_reader):
async with create_cog_reader(infile) as cog:
with rasterio.open(infile) as ds:
rio_profile = ds.profile
cog_profile = cog.profile
# Don't compare ph... | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_metadata(infile, create_cog_reader):
| async with create_cog_reader(infile) as cog:
with rasterio.open(infile) as ds:
rio_profile = ds.profile
cog_profile = cog.profile
# Don't compare photometric, rasterio seems to not always report color interp
cog_profile.pop("photometric", None)
ri... | ogeo.errors import InvalidTiffError
from aiocogeo.ifd import IFD
from aiocogeo.tag import BaseTag
from .conftest import TEST_DATA
@pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_metadata(infile, create_cog_reader):
| 68 | 68 | 228 | 29 | 38 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_metadata | test_cog_metadata | 14 | 42 | 14 | 16 | 512134945ae090d680c482fdbd8a3aa65b7de127 | bigcode/the-stack | train |
b197d5267d54f69bb03dbf4a | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", [TEST_DATA[0]])
async def test_cog_metadata_iter(infile, create_cog_reader):
async with create_cog_reader(infile) as cog:
for ifd in cog:
assert isinstance(ifd, IFD)
for tag in ifd:
assert isinstance(tag, BaseTag... | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", [TEST_DATA[0]])
async def test_cog_metadata_iter(infile, create_cog_reader):
| async with create_cog_reader(infile) as cog:
for ifd in cog:
assert isinstance(ifd, IFD)
for tag in ifd:
assert isinstance(tag, BaseTag)
| with create_cog_reader(infile) as cog:
tile_matrix_set = cog.create_tile_matrix_set()
TileMatrixSet(**tile_matrix_set)
@pytest.mark.asyncio
@pytest.mark.parametrize("infile", [TEST_DATA[0]])
async def test_cog_metadata_iter(infile, create_cog_reader):
| 64 | 64 | 77 | 33 | 31 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_metadata_iter | test_cog_metadata_iter | 139 | 146 | 139 | 141 | 8036c961d9efaa96936eaba3dc596b00aec60001 | bigcode/the-stack | train |
aaa11cd73cf2c91032c3f247 | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_request_metadata(create_cog_reader, infile):
async with create_cog_reader(infile) as cog:
request_metadata = cog.requests
assert len(request_metadata["ranges"]) == request_metadata["count"]
assert (
sum([e... | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_request_metadata(create_cog_reader, infile):
| async with create_cog_reader(infile) as cog:
request_metadata = cog.requests
assert len(request_metadata["ranges"]) == request_metadata["count"]
assert (
sum([end - start + 1 for (start, end) in request_metadata["ranges"]])
== request_metadata["byte_count"]
)
| ) as cog:
for ifd in cog:
assert isinstance(ifd, IFD)
for tag in ifd:
assert isinstance(tag, BaseTag)
@pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_request_metadata(create_cog_reader, infile):
| 64 | 64 | 98 | 29 | 35 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_request_metadata | test_cog_request_metadata | 149 | 159 | 149 | 151 | 2d3e80fe5e90ccd082ce09dcbb6ae943b76ffdb3 | bigcode/the-stack | train |
c07ee26d594d5850345a4b91 | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_metadata_overviews(infile, create_cog_reader):
async with create_cog_reader(infile) as cog:
for idx, ifd in enumerate(cog.ifds):
width = ifd.ImageWidth.value
height = ifd.ImageHeight.value
... | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_metadata_overviews(infile, create_cog_reader):
| async with create_cog_reader(infile) as cog:
for idx, ifd in enumerate(cog.ifds):
width = ifd.ImageWidth.value
height = ifd.ImageHeight.value
try:
# Test decimation of 2
next_ifd = cog.ifds[idx + 1]
next_width = next_ifd.Ima... | if k in (
"TIFFTAG_XRESOLUTION",
"TIFFTAG_YRESOLUTION",
"TIFFTAG_RESOLUTIONUNIT",
):
continue
assert str(gdal_metadata[k]) == v
@pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def te... | 78 | 78 | 262 | 31 | 46 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_metadata_overviews | test_cog_metadata_overviews | 45 | 74 | 45 | 47 | 4e09a7d89fbb7b6e9d48d73e41cfe53c85ea5d68 | bigcode/the-stack | train |
083d4544e5f0ababeb092a6d | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize(
"chunk_size,request_count,header_size",
[[16384, 2, 32770], [4096, 4, 28769], [100, 14, 26776]],
)
async def test_chunk_size(
chunk_size, request_count, header_size, monkeypatch, create_cog_reader
):
monkeypatch.setattr(config, "HEADER_CHUNK_SIZE", chunk_si... | @pytest.mark.asyncio
@pytest.mark.parametrize(
"chunk_size,request_count,header_size",
[[16384, 2, 32770], [4096, 4, 28769], [100, 14, 26776]],
)
async def test_chunk_size(
chunk_size, request_count, header_size, monkeypatch, create_cog_reader
):
| monkeypatch.setattr(config, "HEADER_CHUNK_SIZE", chunk_size)
async with create_cog_reader(
"https://async-cog-reader-test-data.s3.amazonaws.com/webp_cog.tif"
) as cog:
requests = cog.requests
assert requests["count"] == request_count
assert requests["header_size"] == header_s... | @pytest.mark.asyncio
@pytest.mark.parametrize(
"chunk_size,request_count,header_size",
[[16384, 2, 32770], [4096, 4, 28769], [100, 14, 26776]],
)
async def test_chunk_size(
chunk_size, request_count, header_size, monkeypatch, create_cog_reader
):
| 79 | 64 | 156 | 79 | 0 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_chunk_size | test_chunk_size | 186 | 200 | 186 | 193 | 935eae92d426e6474c116d12447d3e145f4bf221 | bigcode/the-stack | train |
d7765fa57ee512c3aca18aaf | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_tile_matrix_set(infile, create_cog_reader):
async with create_cog_reader(infile) as cog:
tile_matrix_set = cog.create_tile_matrix_set()
TileMatrixSet(**tile_matrix_set)
| @pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_tile_matrix_set(infile, create_cog_reader):
| async with create_cog_reader(infile) as cog:
tile_matrix_set = cog.create_tile_matrix_set()
TileMatrixSet(**tile_matrix_set)
| ) as cog:
assert cog.has_alpha
async with create_cog_reader(TEST_DATA[0]) as cog:
assert not cog.has_alpha
@pytest.mark.asyncio
@pytest.mark.parametrize("infile", TEST_DATA)
async def test_cog_tile_matrix_set(infile, create_cog_reader):
| 64 | 64 | 64 | 31 | 32 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_tile_matrix_set | test_cog_tile_matrix_set | 131 | 136 | 131 | 133 | 6065a01583cc42c320daf7aeadab97138da14555 | bigcode/the-stack | train |
c7486ab6d98df86e806df77f | train | function | @pytest.mark.asyncio
async def test_cog_not_a_tiff(create_cog_reader):
infile = "https://async-cog-reader-test-data.s3.amazonaws.com/not_a_tiff.png"
with pytest.raises(InvalidTiffError):
async with create_cog_reader(infile):
...
| @pytest.mark.asyncio
async def test_cog_not_a_tiff(create_cog_reader):
| infile = "https://async-cog-reader-test-data.s3.amazonaws.com/not_a_tiff.png"
with pytest.raises(InvalidTiffError):
async with create_cog_reader(infile):
...
| _metadata["ranges"]) == request_metadata["count"]
assert (
sum([end - start + 1 for (start, end) in request_metadata["ranges"]])
== request_metadata["byte_count"]
)
@pytest.mark.asyncio
async def test_cog_not_a_tiff(create_cog_reader):
| 64 | 64 | 63 | 19 | 45 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_not_a_tiff | test_cog_not_a_tiff | 162 | 167 | 162 | 163 | 2be0d455c21f0645d9487dd5160039948ab1fc2d | bigcode/the-stack | train |
7f21c202997a927568c0d61a | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile,expected",
zip(
TEST_DATA,
[
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags... | @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile,expected",
zip(
TEST_DATA,
[
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags... | async with create_cog_reader(infile) as cog:
mask_flags = cog.mask_flags
assert expected == mask_flags
| @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile,expected",
zip(
TEST_DATA,
[
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags.all_valid], [MaskFlags.all_valid]],
[[MaskFlags.all_valid], [MaskFlags... | 287 | 94 | 315 | 287 | 0 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_cog_mask_flags | test_cog_mask_flags | 88 | 117 | 88 | 114 | f72595d347ddfd54e98cc4a724ccbaf71fd63a9f | bigcode/the-stack | train |
544c28b7309e076c720ebca5 | train | function | @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile",
[
"/local/file/does/not/exist",
"https://cogsarecool.com/cog.tif", # Invalid host
"https://async-cog-reader-test-data.s3.amazonaws.com/file-does-not-exist.tif", # valid host invalid path
"s3://nobucket/badkey.tif",
],... | @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile",
[
"/local/file/does/not/exist",
"https://cogsarecool.com/cog.tif", # Invalid host
"https://async-cog-reader-test-data.s3.amazonaws.com/file-does-not-exist.tif", # valid host invalid path
"s3://nobucket/badkey.tif",
],... | with pytest.raises(FileNotFoundError):
async with create_cog_reader(infile):
...
| @pytest.mark.asyncio
@pytest.mark.parametrize(
"infile",
[
"/local/file/does/not/exist",
"https://cogsarecool.com/cog.tif", # Invalid host
"https://async-cog-reader-test-data.s3.amazonaws.com/file-does-not-exist.tif", # valid host invalid path
"s3://nobucket/badkey.tif",
],... | 105 | 64 | 126 | 105 | 0 | jferencik/aiocogeo | tests/test_metadata.py | Python | test_file_not_found | test_file_not_found | 170 | 183 | 170 | 180 | aeb9a61aeddff544e13d61f15f37ff3d4776bf0c | bigcode/the-stack | train |
ef7f679328216d9de85a4f51 | train | class | class LoginFlow():
# ログイン
def login(self, driver, username, password, capture):
login_page = LoginPage()
login_page.set_driver(driver)
if capture:
# ログイン前のキャプチャ取得
login_page.save_screenshot('1_login')
# ユーザ名とパスワードに「test」を入力
login_page.set_user_... | class LoginFlow():
# ログイン
| def login(self, driver, username, password, capture):
login_page = LoginPage()
login_page.set_driver(driver)
if capture:
# ログイン前のキャプチャ取得
login_page.save_screenshot('1_login')
# ユーザ名とパスワードに「test」を入力
login_page.set_user_name(username)
login_pa... | #!/usr/local/bin/python3
from pages import PageObject, LoginPage
# ログイン画面
class LoginFlow():
# ログイン
| 33 | 64 | 182 | 10 | 22 | ybkuroki/selenium-e2e-sample | script/testflows/login_flow.py | Python | LoginFlow | LoginFlow | 5 | 30 | 5 | 7 | 3b1397a82ef159761fad60319af49c7d9cedd3d1 | bigcode/the-stack | train |
8207da54068453b324b65646 | train | function | def test(header, **more_options):
assert isinstance(header, six.string_types)
with open("temp.h", "w") as fd:
fd.write(header)
options = ctypesgencore.options.get_default_options()
options.headers = ["temp.h"]
for opt in more_options:
setattr(options, opt, more_options[opt])
i... | def test(header, **more_options):
| assert isinstance(header, six.string_types)
with open("temp.h", "w") as fd:
fd.write(header)
options = ctypesgencore.options.get_default_options()
options.headers = ["temp.h"]
for opt in more_options:
setattr(options, opt, more_options[opt])
if redirect_stdout:
# Redire... | takes a string that represents a C header file, along with some
keyword arguments representing options. It processes the header using ctypesgen and returns a tuple
containing the resulting module object and the output that ctypesgen produced."""
# set redirect_stdout to False if using console based debugger like pdb
... | 72 | 72 | 243 | 8 | 63 | borgified/ctypesgen | ctypesgencore/test/ctypesgentest.py | Python | test | test | 30 | 69 | 30 | 31 | 331822c977c1f35bd9d3d006de1bf83e84685152 | bigcode/the-stack | train |
e85cffa7e81eabc3f517f59a | train | function | def cleanup(filepattern="temp.*"):
fnames = glob.glob(filepattern)
for fname in fnames:
os.unlink(fname)
| def cleanup(filepattern="temp.*"):
| fnames = glob.glob(filepattern)
for fname in fnames:
os.unlink(fname)
| __
else:
output = ""
if six.PY2:
# Load the module we have just produced
module = __import__("temp")
else:
module = importlib.import_module("temp")
reload(module)
return module, output
def cleanup(filepattern="temp.*"):
| 64 | 64 | 29 | 8 | 55 | borgified/ctypesgen | ctypesgencore/test/ctypesgentest.py | Python | cleanup | cleanup | 72 | 75 | 72 | 72 | 5e2d5add87a21c6574504c65da4dc93c95aba014 | bigcode/the-stack | train |
abab6d346a7637a2ddec9cdd | train | function | @pytest.mark.parametrize('call_init_kwargs, call_kwargs', [
({'init_foo': b'init_bar'}, {'foo': b'bar', 'stdout': b'42baz42', 'stderr': b'42QUX42'})
])
@pytest.mark.parametrize('call, dec_kwargs, exp', [
(mock_always_fail_call, {}, fuzzinator.call.NonIssue),
(mock_always_fail_call, {'stdout': '["(?P<xyz>[a-... | @pytest.mark.parametrize('call_init_kwargs, call_kwargs', [
({'init_foo': b'init_bar'}, {'foo': b'bar', 'stdout': b'42baz42', 'stderr': b'42QUX42'})
])
@pytest.mark.parametrize('call, dec_kwargs, exp', [
(mock_always_fail_call, {}, fuzzinator.call.NonIssue),
(mock_always_fail_call, {'stdout': '["(?P<xyz>[a-... | call = fuzzinator.call.RegexFilter(**dec_kwargs)(call)
if inspect.isclass(call):
call = call(**call_init_kwargs)
issue = call(**call_kwargs)
if exp is None:
assert issue is None
elif exp == fuzzinator.call.NonIssue:
assert not issue
else:
assert issue == exp
| @pytest.mark.parametrize('call_init_kwargs, call_kwargs', [
({'init_foo': b'init_bar'}, {'foo': b'bar', 'stdout': b'42baz42', 'stderr': b'42QUX42'})
])
@pytest.mark.parametrize('call, dec_kwargs, exp', [
(mock_always_fail_call, {}, fuzzinator.call.NonIssue),
(mock_always_fail_call, {'stdout': '["(?P<xyz>[a-... | 1,063 | 256 | 1,137 | 1,063 | 0 | elecro/fuzzinator | tests/call/test_regex_filter.py | Python | test_regex_filter | test_regex_filter | 16 | 53 | 16 | 42 | b5aa826dc81d24de7e709722b15306303fb10f75 | bigcode/the-stack | train |
77eaf775fb967d82ca701275 | train | function | def main():
# input
N, K = map(int, input().split())
ls = [*map(int, input().split())]
# compute
ls.sort()
ans = 0
for i in range(K):
ans += ls[-i-1]
# output
print(ans)
| def main():
# input
| N, K = map(int, input().split())
ls = [*map(int, input().split())]
# compute
ls.sort()
ans = 0
for i in range(K):
ans += ls[-i-1]
# output
print(ans)
| def main():
# input
| 7 | 64 | 70 | 7 | 0 | fumiyanll23/AtCoder | ABC/067/b.py | Python | main | main | 1 | 13 | 1 | 2 | 12c24f4569b031c0d98ac5765c633cbadec563ab | bigcode/the-stack | train |
4a5fa54e9a24cc354f519ee2 | train | class | class Authorization(AuthorizationUpdateRequest):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value i... | class Authorization(AuthorizationUpdateRequest):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The... | # coding: utf-8
"""
Influx API Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from influxd... | 102 | 256 | 2,259 | 7 | 94 | kelseiv/influxdb-client-python | influxdb_client/domain/authorization.py | Python | Authorization | Authorization | 20 | 364 | 20 | 20 | a17c07d3a27d1c8e71094a73470487cdb7945e37 | bigcode/the-stack | train |
781ebeade61953ead19edfc4 | train | class | class Account(metaclass=ConvertMeta):
id = int
name = str
amount = Money
def __init__(self, id, name, amount):
self.id = id
self.name = name
self.amount = amount
def __str__(self):
return "[{0}] {1}: {2}".format(self.id, self.name, self.amount)
| class Account(metaclass=ConvertMeta):
| id = int
name = str
amount = Money
def __init__(self, id, name, amount):
self.id = id
self.name = name
self.amount = amount
def __str__(self):
return "[{0}] {1}: {2}".format(self.id, self.name, self.amount)
| float__(self):
return self.amount / self.cents_qty
def __int__(self):
return self.amount // self.cents_qty
def __str__(self):
return "{:.2f}".format(float(self.amount / self.cents_qty))
class Account(metaclass=ConvertMeta):
| 64 | 64 | 84 | 9 | 55 | art-solopov/challenges | metaclasses_python/main.py | Python | Account | Account | 20 | 31 | 20 | 20 | e2531f2f07c802b18850630e4a599c2b1bb26017 | bigcode/the-stack | train |
ebe539ff16bd51c570c1d558 | train | class | class Money:
"""A small currency class
"""
def __init__(self, amount, cents_qty=100):
self.cents_qty = cents_qty
self.amount = int(float(amount) * cents_qty) # Convert to integer cents
def __float__(self):
return self.amount / self.cents_qty
def __int__(self):
retu... | class Money:
| """A small currency class
"""
def __init__(self, amount, cents_qty=100):
self.cents_qty = cents_qty
self.amount = int(float(amount) * cents_qty) # Convert to integer cents
def __float__(self):
return self.amount / self.cents_qty
def __int__(self):
return self.amoun... | from converter import ConvertMeta
class Money:
| 9 | 64 | 111 | 3 | 5 | art-solopov/challenges | metaclasses_python/main.py | Python | Money | Money | 3 | 18 | 3 | 3 | afd05a409f359e4d6f85016e50eac3e40e9ecd58 | bigcode/the-stack | train |
9be8e536aa152ebfa5e7f3df | train | class | class AppsV1beta1DeploymentStatus(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute ty... | class AppsV1beta1DeploymentStatus(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is ... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteri... | 86 | 256 | 2,348 | 10 | 75 | splunkenizer/splunk_as_a_service_app | lib/kubernetes/client/models/apps_v1beta1_deployment_status.py | Python | AppsV1beta1DeploymentStatus | AppsV1beta1DeploymentStatus | 19 | 322 | 19 | 19 | 0c1b7cb36ebd27f846a1b77f046f75a867b16783 | bigcode/the-stack | train |
b76388a2f493055d0326c356 | train | class | class Test(unittest.TestCase):
def setUp(self):
import Exercise8_02
self.exercise = Exercise8_02
self.classifier=VGG16()
self.new_image = image.load_img('../Data/Prediction/stick_insect.jpg', target_size=(224, 224))
self.transformed_image = image.img_to... | class Test(unittest.TestCase):
| def setUp(self):
import Exercise8_02
self.exercise = Exercise8_02
self.classifier=VGG16()
self.new_image = image.load_img('../Data/Prediction/stick_insect.jpg', target_size=(224, 224))
self.transformed_image = image.img_to_array(self.new_image)
self.... | np
import pandas as pd
import numpy.testing as np_testing
import pandas.testing as pd_testing
import os
import import_ipynb
from tensorflow import random
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
from keras.preprocessing import image
class Test(unittest.TestCase):
| 66 | 66 | 220 | 7 | 58 | PacktWorkshops/Applied-Deep-Learning-with-Keras | Chapter08/Exercise8.02/Exercise8.02_Unit_test.py | Python | Test | Test | 12 | 35 | 12 | 13 | 69fb51b902d6bb348c4a8979ad502b2843d5700b | bigcode/the-stack | train |
1204f84e0dc409251a2e9bd4 | train | function | def obj() -> OpenSCADObject:
"""
Retrieve part object when importing it into assemblies or similar.
"""
return solid
| def obj() -> OpenSCADObject:
| """
Retrieve part object when importing it into assemblies or similar.
"""
return solid
| 2
BY = 2
BZ = FZ
solid -= combine(
cube([BX, BY, BZ]),
translate([(X - BX) / 2, Y - BY * 2, (Z - FZ) / 2]),
)
def obj() -> OpenSCADObject:
| 64 | 64 | 29 | 9 | 55 | nicklasfrahm/hardware | mcad/src/netstack_v0_switch_chassis.py | Python | obj | obj | 57 | 61 | 57 | 57 | f578f47b2b8d44b5f59e3d97bb81a14cb6ed93d8 | bigcode/the-stack | train |
8d378364b593bb1aa8304f21 | train | function | @annotate("BINARY_OP", color="orange", domain="cudf_python")
def _string_column_binop(
lhs: "column.ColumnBase",
rhs: "column.ColumnBase",
op: str,
out_dtype: Dtype,
) -> "column.ColumnBase":
out = libcudf.binaryop.binaryop(lhs=lhs, rhs=rhs, op=op, dtype=out_dtype)
return out
| @annotate("BINARY_OP", color="orange", domain="cudf_python")
def _string_column_binop(
lhs: "column.ColumnBase",
rhs: "column.ColumnBase",
op: str,
out_dtype: Dtype,
) -> "column.ColumnBase":
| out = libcudf.binaryop.binaryop(lhs=lhs, rhs=rhs, op=op, dtype=out_dtype)
return out
| .view(dtype)
@annotate("BINARY_OP", color="orange", domain="cudf_python")
def _string_column_binop(
lhs: "column.ColumnBase",
rhs: "column.ColumnBase",
op: str,
out_dtype: Dtype,
) -> "column.ColumnBase":
| 64 | 64 | 92 | 61 | 3 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | _string_column_binop | _string_column_binop | 5,154 | 5,162 | 5,154 | 5,160 | 1a37b0b61b1d66121f51e311e5dd143f8a73ce11 | bigcode/the-stack | train |
0b74eb7d9aa04fb875557231 | train | function | def _expected_types_format(types):
if len(types) == 1:
return types[0]
return ", ".join(types[:-1]) + ", or " + types[-1]
| def _expected_types_format(types):
| if len(types) == 1:
return types[0]
return ", ".join(types[:-1]) + ", or " + types[-1]
| isinstance(value, Column) and is_string_dtype(value.dtype):
return value
allowed_types.append("Column")
raise ValueError(
f"Expected {_expected_types_format(allowed_types)} "
f"for {name} but got {type(value)}"
)
def _expected_types_format(types):
| 64 | 64 | 40 | 7 | 57 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | _expected_types_format | _expected_types_format | 4,635 | 4,639 | 4,635 | 4,635 | 6b35962cec276c9dabd0c58b78e8d170f053cd70 | bigcode/the-stack | train |
daa8f5a3cc2ae7034a8565e7 | train | class | class StringMethods(ColumnMethodsMixin):
def __init__(self, column, parent=None):
"""
Vectorized string functions for Series and Index.
This mimics pandas ``df.str`` interface. nulls stay null
unless handled otherwise by a particular method.
Patterned after Python’s string m... | class StringMethods(ColumnMethodsMixin):
| def __init__(self, column, parent=None):
"""
Vectorized string functions for Series and Index.
This mimics pandas ``df.str`` interface. nulls stay null
unless handled otherwise by a particular method.
Patterned after Python’s string methods, with some
inspiration fro... | "): str_cast.ultos,
np.dtype("float32"): str_cast.ftos,
np.dtype("float64"): str_cast.dtos,
np.dtype("bool"): str_cast.from_booleans,
}
_datetime_to_str_typecast_functions = {
# TODO: support Date32 UNIX days
# np.dtype("datetime64[D]"): str_cast.int2timestamp,
np.dtype("datetime64[s]"): str_ca... | 255 | 256 | 29,970 | 7 | 248 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | StringMethods | StringMethods | 215 | 4,611 | 215 | 215 | ed7092e686a3ddf8fa8aea8839ec85c5de6dc1fe | bigcode/the-stack | train |
a63bf4867574042f76fdc741 | train | class | class StringColumn(column.ColumnBase):
"""Implements operations for Columns of String type
"""
_start_offset: Optional[int]
_end_offset: Optional[int]
_cached_sizeof: Optional[int]
def __init__(
self,
mask: Buffer = None,
size: int = None, # TODO: make non-optional
... | class StringColumn(column.ColumnBase):
| """Implements operations for Columns of String type
"""
_start_offset: Optional[int]
_end_offset: Optional[int]
_cached_sizeof: Optional[int]
def __init__(
self,
mask: Buffer = None,
size: int = None, # TODO: make non-optional
offset: int = 0,
null_coun... | ):
targets_column = column.as_column([targets])
elif can_convert_to_column(targets):
targets_column = column.as_column(targets)
else:
raise TypeError(
f"targets should be an str, array-like or Series object, "
f"found {type(targets)}"
... | 256 | 256 | 3,683 | 7 | 249 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | StringColumn | StringColumn | 4,642 | 5,151 | 4,642 | 4,642 | d08f91c552ae09a496e2897be7096010d9beeeee | bigcode/the-stack | train |
2e897b5e8c6e784bc8d0d3df | train | function | def _get_cols_list(parent_obj, others):
parent_index = (
parent_obj.index if isinstance(parent_obj, cudf.Series) else parent_obj
)
if (
can_convert_to_column(others)
and len(others) > 0
and (
can_convert_to_column(
others.iloc[0]
... | def _get_cols_list(parent_obj, others):
| parent_index = (
parent_obj.index if isinstance(parent_obj, cudf.Series) else parent_obj
)
if (
can_convert_to_column(others)
and len(others) > 0
and (
can_convert_to_column(
others.iloc[0]
if isinstance(others, cudf.Series)
... | BINARY_OP", color="orange", domain="cudf_python")
def _string_column_binop(
lhs: "column.ColumnBase",
rhs: "column.ColumnBase",
op: str,
out_dtype: Dtype,
) -> "column.ColumnBase":
out = libcudf.binaryop.binaryop(lhs=lhs, rhs=rhs, op=op, dtype=out_dtype)
return out
def _get_cols_list(parent_obj,... | 98 | 98 | 328 | 10 | 87 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | _get_cols_list | _get_cols_list | 5,165 | 5,213 | 5,165 | 5,166 | 1afac1057b8e4e9e746080adfb92cb63ac08229e | bigcode/the-stack | train |
e634227f46e365270c393667 | train | function | def _massage_string_arg(value, name, allow_col=False):
if isinstance(value, str):
return cudf.Scalar(value, dtype="str")
allowed_types = ["Scalar"]
if allow_col:
if isinstance(value, list):
return column.as_column(value, dtype="str")
if isinstance(value, Column) and is... | def _massage_string_arg(value, name, allow_col=False):
| if isinstance(value, str):
return cudf.Scalar(value, dtype="str")
allowed_types = ["Scalar"]
if allow_col:
if isinstance(value, list):
return column.as_column(value, dtype="str")
if isinstance(value, Column) and is_string_dtype(value.dtype):
return value
... | (
f"targets should be an str, array-like or Series object, "
f"found {type(targets)}"
)
return self._return_or_inplace(
cpp_edit_distance(self._column, targets_column)
)
def _massage_string_arg(value, name, allow_col=False):
| 64 | 64 | 121 | 13 | 51 | ayushdg/cudf | python/cudf/cudf/core/column/string.py | Python | _massage_string_arg | _massage_string_arg | 4,614 | 4,632 | 4,614 | 4,614 | de9fcd9d60934a3eebf6ffa89cd0d64e5d0754e8 | bigcode/the-stack | train |
3adf0bc9865769c3f4df0f59 | train | function | @pytest.fixture(scope="session")
def fpe_map_pwl():
dataset_1 = simulate_map_dataset(name="test-map-pwl")
dataset_2 = dataset_1.copy(name="test-map-pwl-2")
dataset_2.models = dataset_1.models
dataset_2.mask_safe = RegionNDMap.from_geom(dataset_2.counts.geom, dtype=bool)
energy_edges = [0.1, 1, 10,... | @pytest.fixture(scope="session")
def fpe_map_pwl():
| dataset_1 = simulate_map_dataset(name="test-map-pwl")
dataset_2 = dataset_1.copy(name="test-map-pwl-2")
dataset_2.models = dataset_1.models
dataset_2.mask_safe = RegionNDMap.from_geom(dataset_2.counts.geom, dtype=bool)
energy_edges = [0.1, 1, 10, 100] * u.TeV
datasets = [dataset_1, dataset_2]
... | isp"])
dataset = maker.run(empty, obs)
bkg_model = FoVBackgroundModel(dataset_name=dataset.name)
dataset.models = [bkg_model, skymodel]
dataset.fake(random_state=random_state)
return dataset
@pytest.fixture(scope="session")
def fpe_map_pwl():
| 64 | 64 | 157 | 13 | 50 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | fpe_map_pwl | fpe_map_pwl | 132 | 148 | 132 | 133 | 8a18967140d8ac104acefa5c3ae733c43611f71a | bigcode/the-stack | train |
bed95ba45d52cdef9ded51e9 | train | function | def simulate_spectrum_dataset(model, random_state=0):
energy_edges = np.logspace(-0.5, 1.5, 21) * u.TeV
energy_axis = MapAxis.from_edges(energy_edges, interp="log", name="energy")
energy_axis_true = energy_axis.copy(name="energy_true")
aeff = EffectiveAreaTable2D.from_parametrization(energy_axis_true=e... | def simulate_spectrum_dataset(model, random_state=0):
| energy_edges = np.logspace(-0.5, 1.5, 21) * u.TeV
energy_axis = MapAxis.from_edges(energy_edges, interp="log", name="energy")
energy_axis_true = energy_axis.copy(name="energy_true")
aeff = EffectiveAreaTable2D.from_parametrization(energy_axis_true=energy_axis_true)
bkg_model = SkyModel(
sp... | Table2D, load_cta_irfs
from gammapy.makers import MapDatasetMaker
from gammapy.makers.utils import make_map_exposure_true_energy
from gammapy.maps import MapAxis, RegionGeom, RegionNDMap, WcsGeom
from gammapy.modeling import Fit
from gammapy.modeling.models import (
ExpCutoffPowerLawSpectralModel,
FoVBackground... | 141 | 141 | 473 | 12 | 128 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | simulate_spectrum_dataset | simulate_spectrum_dataset | 26 | 77 | 26 | 26 | 47f77e4152b2487c3a55a7fa58c47a16c996e9a8 | bigcode/the-stack | train |
3eacda1006133800950c2e32 | train | function | @requires_dependency("iminuit")
def test_run_pwl_parameter_range(fpe_pwl):
pl = PowerLawSpectralModel(amplitude="1e-16 cm-2s-1TeV-1")
datasets, fpe = create_fpe(pl)
fp = fpe.run(datasets)
table_no_bounds = fp.to_table()
pl.amplitude.min = 0
pl.amplitude.max = 1e-12
fp = fpe.run(datasets)... | @requires_dependency("iminuit")
def test_run_pwl_parameter_range(fpe_pwl):
| pl = PowerLawSpectralModel(amplitude="1e-16 cm-2s-1TeV-1")
datasets, fpe = create_fpe(pl)
fp = fpe.run(datasets)
table_no_bounds = fp.to_table()
pl.amplitude.min = 0
pl.amplitude.max = 1e-12
fp = fpe.run(datasets)
table_with_bounds = fp.to_table()
actual = table_with_bounds["nor... | isp = None
dataset_2.edisp = None
model = SkyModel(
spectral_model=PowerLawSpectralModel(),
spatial_model=GaussianSpatialModel(),
name="source",
)
dataset_1.models = model
dataset_2.models = model
fpe = FluxPointsEstimator(energy_edges=[1, 10] * u.TeV, source="source")... | 137 | 137 | 458 | 19 | 118 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_run_pwl_parameter_range | test_run_pwl_parameter_range | 447 | 484 | 447 | 448 | 14da5943f28ad90773a33f1ecb2922757f9e1b39 | bigcode/the-stack | train |
b258f6c9f25f4132122e3d84 | train | function | @pytest.fixture(scope="session")
def fpe_ecpl():
return create_fpe(ExpCutoffPowerLawSpectralModel(lambda_="1 TeV-1"))
| @pytest.fixture(scope="session")
def fpe_ecpl():
| return create_fpe(ExpCutoffPowerLawSpectralModel(lambda_="1 TeV-1"))
| 1, 1.2],
reoptimize=True,
source="source",
)
return datasets, fpe
@pytest.fixture(scope="session")
def fpe_pwl():
return create_fpe(PowerLawSpectralModel())
@pytest.fixture(scope="session")
def fpe_ecpl():
| 64 | 64 | 35 | 12 | 52 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | fpe_ecpl | fpe_ecpl | 173 | 175 | 173 | 174 | 11c86e6183e45096b359b3c9ef8dcc6044f0d43b | bigcode/the-stack | train |
ba8ac4b7a98c4663d1a2486b | train | function | @requires_dependency("iminuit")
def test_run_ecpl(fpe_ecpl, tmpdir):
datasets, fpe = fpe_ecpl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["ref_flux"].quantity
desired = [9.024362e-13, 1.781341e-13, 1.260298e-18] * u.Unit("1 / (cm2 s)")
assert_allclose(actual, desired, rtol=1e-... | @requires_dependency("iminuit")
def test_run_ecpl(fpe_ecpl, tmpdir):
| datasets, fpe = fpe_ecpl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["ref_flux"].quantity
desired = [9.024362e-13, 1.781341e-13, 1.260298e-18] * u.Unit("1 / (cm2 s)")
assert_allclose(actual, desired, rtol=1e-3)
actual = table["ref_dnde"].quantity
desired = [1.351382e-... | _errn = fp.npred_excess_errn.data.squeeze()
assert_allclose(npred_excess_errn, [40.247313, 27.932033, 6.378465], rtol=1e-3)
npred_excess_ul = fp.npred_excess_ul.data.squeeze()
assert_allclose(npred_excess_ul, [742.87486, 479.169719, 49.019125], rtol=1e-3)
# test GADF I/O
fp.write(tmpdir / "test.fi... | 178 | 178 | 595 | 20 | 158 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_run_ecpl | test_run_ecpl | 265 | 306 | 265 | 266 | 452f73ddb55d3e5c07e6ae891a5437e347b96217 | bigcode/the-stack | train |
ba5c651980e700d33e2ddc25 | train | function | @requires_dependency("iminuit")
def test_flux_points_estimator_small_edges():
pl = PowerLawSpectralModel(amplitude="1e-11 cm-2s-1TeV-1")
datasets, fpe = create_fpe(pl)
fpe.energy_edges = datasets[0].counts.geom.axes["energy"].upsample(3).edges[1:4]
fpe.selection_optional = []
fp = fpe.run(dataset... | @requires_dependency("iminuit")
def test_flux_points_estimator_small_edges():
| pl = PowerLawSpectralModel(amplitude="1e-11 cm-2s-1TeV-1")
datasets, fpe = create_fpe(pl)
fpe.energy_edges = datasets[0].counts.geom.axes["energy"].upsample(3).edges[1:4]
fpe.selection_optional = []
fp = fpe.run(datasets)
assert_allclose(fp.ts.data[0, 0, 0], 2156.96959291)
assert np.isna... | e-2)
actual = table_no_bounds["sqrt_ts"].data
assert_allclose(actual, [-1.006081, -0.364848, -0.927819], rtol=1e-2)
@requires_dependency("iminuit")
def test_flux_points_estimator_small_edges():
| 64 | 64 | 153 | 16 | 48 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_flux_points_estimator_small_edges | test_flux_points_estimator_small_edges | 487 | 500 | 487 | 488 | 61cd70c5d591a124aa95ea5cc56caa92de9189df | bigcode/the-stack | train |
69a56928b6ec676b5b650d8f | train | function | @pytest.fixture(scope="session")
def fpe_pwl():
return create_fpe(PowerLawSpectralModel())
| @pytest.fixture(scope="session")
def fpe_pwl():
| return create_fpe(PowerLawSpectralModel())
| ]
fpe = FluxPointsEstimator(
energy_edges=energy_edges,
norm_values=[0.8, 1, 1.2],
reoptimize=True,
source="source",
)
return datasets, fpe
@pytest.fixture(scope="session")
def fpe_pwl():
| 64 | 64 | 24 | 12 | 51 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | fpe_pwl | fpe_pwl | 168 | 170 | 168 | 169 | 706bd0a556ddd4d003dc0211b7a1980130c90ea1 | bigcode/the-stack | train |
2320475b49269d4871091ac8 | train | function | @pytest.fixture(scope="session")
def fpe_map_pwl_reoptimize():
dataset = simulate_map_dataset()
energy_edges = [1, 10] * u.TeV
dataset.models.parameters["lon_0"].frozen = True
dataset.models.parameters["lat_0"].frozen = True
dataset.models.parameters["sigma"].frozen = True
datasets = [dataset]
... | @pytest.fixture(scope="session")
def fpe_map_pwl_reoptimize():
| dataset = simulate_map_dataset()
energy_edges = [1, 10] * u.TeV
dataset.models.parameters["lon_0"].frozen = True
dataset.models.parameters["lat_0"].frozen = True
dataset.models.parameters["sigma"].frozen = True
datasets = [dataset]
fpe = FluxPointsEstimator(
energy_edges=energy_edges... | 1, dataset_2]
fpe = FluxPointsEstimator(
energy_edges=energy_edges,
norm_n_values=3,
source="source",
selection_optional="all",
)
return datasets, fpe
@pytest.fixture(scope="session")
def fpe_map_pwl_reoptimize():
| 64 | 64 | 135 | 16 | 47 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | fpe_map_pwl_reoptimize | fpe_map_pwl_reoptimize | 151 | 165 | 151 | 152 | 20114d5a737d1bd1fe7add514fe44b364991869a | bigcode/the-stack | train |
76f518336820b61eeac83ac9 | train | function | @requires_dependency("iminuit")
@requires_data()
def test_run_map_pwl_reoptimize(fpe_map_pwl_reoptimize):
datasets, fpe = fpe_map_pwl_reoptimize
fpe = fpe.copy()
fpe.selection_optional = ["scan"]
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["norm"].data
assert_allclose(actua... | @requires_dependency("iminuit")
@requires_data()
def test_run_map_pwl_reoptimize(fpe_map_pwl_reoptimize):
| datasets, fpe = fpe_map_pwl_reoptimize
fpe = fpe.copy()
fpe.selection_optional = ["scan"]
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["norm"].data
assert_allclose(actual, 0.962368, rtol=1e-2)
actual = table["norm_err"].data
assert_allclose(actual, 0.053878, rtol=1e... | dir / "test.fits", format="gadf-sed")
fp_new = FluxPoints.read(tmpdir / "test.fits")
assert fp_new.meta["sed_type_init"] == "likelihood"
@requires_dependency("iminuit")
@requires_data()
def test_run_map_pwl_reoptimize(fpe_map_pwl_reoptimize):
| 73 | 73 | 244 | 29 | 44 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_run_map_pwl_reoptimize | test_run_map_pwl_reoptimize | 353 | 376 | 353 | 355 | 2de61a8bd97d31255d337f1fafeab23948f447e0 | bigcode/the-stack | train |
f7974a7a68bdbe0c77c6a2df | train | function | def test_str(fpe_pwl):
datasets, fpe = fpe_pwl
assert "FluxPointsEstimator" in str(fpe)
| def test_str(fpe_pwl):
| datasets, fpe = fpe_pwl
assert "FluxPointsEstimator" in str(fpe)
| session")
def fpe_pwl():
return create_fpe(PowerLawSpectralModel())
@pytest.fixture(scope="session")
def fpe_ecpl():
return create_fpe(ExpCutoffPowerLawSpectralModel(lambda_="1 TeV-1"))
def test_str(fpe_pwl):
| 63 | 64 | 31 | 8 | 55 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_str | test_str | 178 | 180 | 178 | 178 | 38052720960765d897eb11b808c8df6dde7b4cb6 | bigcode/the-stack | train |
7eee97aee9bc3d8cc6915713 | train | function | @requires_dependency("iminuit")
@requires_data()
def test_flux_points_estimator_no_norm_scan(fpe_pwl, tmpdir):
datasets, fpe = fpe_pwl
fpe.selection_optional = None
fp = fpe.run(datasets)
assert_allclose(fpe.fit.optimize_opts["tol"], 0.2)
assert_allclose(fpe.fit.minuit.tol, 0.2)
assert fp.sed... | @requires_dependency("iminuit")
@requires_data()
def test_flux_points_estimator_no_norm_scan(fpe_pwl, tmpdir):
| datasets, fpe = fpe_pwl
fpe.selection_optional = None
fp = fpe.run(datasets)
assert_allclose(fpe.fit.optimize_opts["tol"], 0.2)
assert_allclose(fpe.fit.minuit.tol, 0.2)
assert fp.sed_type_init == "likelihood"
assert "stat_scan" not in fp._data
# test GADF I/O
fp.write(tmpdir / "t... | stat"][0]
assert_allclose(actual, [9.788123, 0.486066, 17.603708], rtol=1e-2)
@requires_dependency("iminuit")
@requires_data()
def test_flux_points_estimator_no_norm_scan(fpe_pwl, tmpdir):
| 64 | 64 | 170 | 28 | 36 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_flux_points_estimator_no_norm_scan | test_flux_points_estimator_no_norm_scan | 379 | 396 | 379 | 381 | 8a668f6b3b941743201e9a4282b86a153712e427 | bigcode/the-stack | train |
c4aabbe7729e2428e5e4ca97 | train | function | def test_no_likelihood_contribution():
dataset = simulate_spectrum_dataset(
SkyModel(spectral_model=PowerLawSpectralModel(), name="source")
)
dataset_2 = dataset.slice_by_idx(slices={"energy": slice(0, 5)})
dataset.mask_safe = RegionNDMap.from_geom(dataset.counts.geom, dtype=bool)
fpe = F... | def test_no_likelihood_contribution():
| dataset = simulate_spectrum_dataset(
SkyModel(spectral_model=PowerLawSpectralModel(), name="source")
)
dataset_2 = dataset.slice_by_idx(slices={"energy": slice(0, 5)})
dataset.mask_safe = RegionNDMap.from_geom(dataset.counts.geom, dtype=bool)
fpe = FluxPointsEstimator(energy_edges=[1.0, 3... | # test GADF I/O
fp.write(tmpdir / "test.fits", format="gadf-sed")
fp_new = FluxPoints.read(tmpdir / "test.fits")
assert fp_new.meta["sed_type_init"] == "likelihood"
def test_no_likelihood_contribution():
| 64 | 64 | 158 | 8 | 56 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_no_likelihood_contribution | test_no_likelihood_contribution | 399 | 413 | 399 | 399 | 84eedfd34439dedd9f206e8d901a5146aa2d62ca | bigcode/the-stack | train |
a9e234cacd66256dda5a1cf9 | train | function | def simulate_map_dataset(random_state=0, name=None):
irfs = load_cta_irfs(
"$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
)
skydir = SkyCoord("0 deg", "0 deg", frame="galactic")
energy_edges = np.logspace(-1, 2, 15) * u.TeV
energy_axis = MapAxis.from_edges(edges=... | def simulate_map_dataset(random_state=0, name=None):
| irfs = load_cta_irfs(
"$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
)
skydir = SkyCoord("0 deg", "0 deg", frame="galactic")
energy_edges = np.logspace(-1, 2, 15) * u.TeV
energy_axis = MapAxis.from_edges(edges=energy_edges, name="energy", interp="log")
geom ... | = simulate_spectrum_dataset(model)
energy_edges = [0.1, 1, 10, 100] * u.TeV
dataset.models = model
fpe = FluxPointsEstimator(
energy_edges=energy_edges,
norm_n_values=11,
source="source",
selection_optional="all",
fit=Fit(backend="minuit", optimize_opts=dict(tol=0.2,... | 120 | 120 | 400 | 12 | 107 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | simulate_map_dataset | simulate_map_dataset | 96 | 129 | 96 | 96 | 1b97f71b2f269868b63d68e6844f5848d54a3ac1 | bigcode/the-stack | train |
781c43cc3b4ce67aba9d8831 | train | function | def test_mask_shape():
axis = MapAxis.from_edges([1.0, 3.0, 10.0], unit="TeV", interp="log", name="energy")
geom_1 = WcsGeom.create(binsz=1, width=3, axes=[axis])
geom_2 = WcsGeom.create(binsz=1, width=5, axes=[axis])
dataset_1 = MapDataset.create(geom_1)
dataset_2 = MapDataset.create(geom_2)
d... | def test_mask_shape():
| axis = MapAxis.from_edges([1.0, 3.0, 10.0], unit="TeV", interp="log", name="energy")
geom_1 = WcsGeom.create(binsz=1, width=3, axes=[axis])
geom_2 = WcsGeom.create(binsz=1, width=5, axes=[axis])
dataset_1 = MapDataset.create(geom_1)
dataset_2 = MapDataset.create(geom_2)
dataset_1.gti = None
... | Estimator(energy_edges=[1.0, 3.0, 10.0] * u.TeV, source="source")
table = fpe.run([dataset, dataset_2]).to_table()
assert np.isnan(table["norm"]).all()
assert np.isnan(table["norm_err"]).all()
assert_allclose(table["counts"], 0)
def test_mask_shape():
| 81 | 81 | 271 | 5 | 76 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_mask_shape | test_mask_shape | 416 | 444 | 416 | 416 | fc6c822aa8980b68195f6c53e2e3396797a940b4 | bigcode/the-stack | train |
8281c43314e01bef67e8934a | train | function | def create_fpe(model):
model = SkyModel(spectral_model=model, name="source")
dataset = simulate_spectrum_dataset(model)
energy_edges = [0.1, 1, 10, 100] * u.TeV
dataset.models = model
fpe = FluxPointsEstimator(
energy_edges=energy_edges,
norm_n_values=11,
source="source",
... | def create_fpe(model):
| model = SkyModel(spectral_model=model, name="source")
dataset = simulate_spectrum_dataset(model)
energy_edges = [0.1, 1, 10, 100] * u.TeV
dataset.models = model
fpe = FluxPointsEstimator(
energy_edges=energy_edges,
norm_n_values=11,
source="source",
selection_optional... | mask_safe=mask_safe,
)
dataset.models = bkg_model
bkg_npred = dataset.npred_signal()
dataset.models = model
dataset.fake(
random_state=random_state,
npred_background=bkg_npred,
)
return dataset
def create_fpe(model):
| 64 | 64 | 130 | 6 | 57 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | create_fpe | create_fpe | 80 | 93 | 80 | 80 | c931816a5c6ee1e555232f8f741781498ef1802e | bigcode/the-stack | train |
4a899e60aa413946fc3b01a8 | train | function | @requires_dependency("iminuit")
def test_run_pwl(fpe_pwl, tmpdir):
datasets, fpe = fpe_pwl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["e_min"].data
assert_allclose(actual, [0.316228, 1.0, 10.0], rtol=1e-5)
actual = table["e_max"].data
assert_allclose(actual, [1.0, 10.0, 3... | @requires_dependency("iminuit")
def test_run_pwl(fpe_pwl, tmpdir):
| datasets, fpe = fpe_pwl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["e_min"].data
assert_allclose(actual, [0.316228, 1.0, 10.0], rtol=1e-5)
actual = table["e_max"].data
assert_allclose(actual, [1.0, 10.0, 31.622777], rtol=1e-5)
actual = table["e_ref"].data
assert_... | ",
)
return datasets, fpe
@pytest.fixture(scope="session")
def fpe_map_pwl_reoptimize():
dataset = simulate_map_dataset()
energy_edges = [1, 10] * u.TeV
dataset.models.parameters["lon_0"].frozen = True
dataset.models.parameters["lat_0"].frozen = True
dataset.models.parameters["sigma"].froz... | 256 | 256 | 1,120 | 20 | 236 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_run_pwl | test_run_pwl | 183 | 262 | 183 | 184 | a7b6b25a785c210aec1def1ba19e4fd4bf915f60 | bigcode/the-stack | train |
3777ebffafd31a71c07fd32f | train | function | @requires_dependency("iminuit")
@requires_data()
def test_run_map_pwl(fpe_map_pwl, tmpdir):
datasets, fpe = fpe_map_pwl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["e_min"].data
assert_allclose(actual, [0.1, 1.178769, 8.48342], rtol=1e-5)
actual = table["e_max"].data
asser... | @requires_dependency("iminuit")
@requires_data()
def test_run_map_pwl(fpe_map_pwl, tmpdir):
| datasets, fpe = fpe_map_pwl
fp = fpe.run(datasets)
table = fp.to_table()
actual = table["e_min"].data
assert_allclose(actual, [0.1, 1.178769, 8.48342], rtol=1e-5)
actual = table["e_max"].data
assert_allclose(actual, [1.178769, 8.483429, 100.0], rtol=1e-5)
actual = table["e_ref"].data... | [1.283433e00, 1.555117e00, 9.698645e03], rtol=1e-2)
actual = table["sqrt_ts"].data
assert_allclose(actual, [7.678454, 4.735691, 0.399243], rtol=1e-2)
# test GADF I/O
fp.write(tmpdir / "test.fits", format="gadf-sed")
fp_new = FluxPoints.read(tmpdir / "test.fits")
assert fp_new.meta["sed_type_i... | 156 | 156 | 521 | 26 | 130 | isu-veritas/gammapy | gammapy/estimators/points/tests/test_sed.py | Python | test_run_map_pwl | test_run_map_pwl | 309 | 350 | 309 | 311 | abf0aaae26e8e9bb8afe5c64106275d169c2cb67 | bigcode/the-stack | train |
481d2443adfe2937f9fd36c6 | train | function | def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
| def ssh_interface(vm_):
| '''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
| )
if cidr != '' and all_matching_cidrs(ip, [cidr]):
log.warning(
'IP {0!r} found within {1!r}; ignoring it.'.format(ip, cidr)
)
return True
return False
def ssh_interface(vm_):
| 64 | 64 | 64 | 6 | 57 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | ssh_interface | ssh_interface | 350 | 358 | 350 | 350 | e315ed56421a5727e1da65bc8f64c52817057f80 | bigcode/the-stack | train |
f0d3598aafaf5c18b1747b8a | train | function | def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on Openstack
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways to... | def request_instance(vm_=None, call=None):
| '''
Put together all of the information necessary to request an instance on Openstack
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be ca... | != '' and all_matching_cidrs(ip, [cidr]):
log.warning(
'IP {0!r} found within {1!r}; ignoring it.'.format(ip, cidr)
)
return True
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
... | 256 | 256 | 1,436 | 10 | 246 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | request_instance | request_instance | 383 | 565 | 383 | 383 | 974b09147f16e1cc880fd8afd088a46f2881ec27 | bigcode/the-stack | train |
fc6123b0dd4c87a0e9925a35 | train | function | def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.... | def preferred_ip(vm_, ips):
| '''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
... | info['ex_force_auth_version'] = '2.0_apikey'
log.debug('OpenStack authenticating using apikey')
return driver(
user,
config.get_cloud_config_value('apikey', vm_, __opts__,
search_global=False), **authinfo)
def preferred_ip(vm_, ips):
| 64 | 64 | 118 | 7 | 57 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | preferred_ip | preferred_ip | 308 | 326 | 308 | 308 | 28414f9cf749edaeabb563526332af709968a2d8 | bigcode/the-stack | train |
2ea648b49c9bf118a3c6f4a8 | train | function | def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filen... | def create(vm_):
| '''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.exp... | _['name']),
{'kwargs': {'name': kwargs['name'],
'image': kwargs['image'].name,
'size': kwargs['size'].name,
'profile': vm_['profile']}},
transport=__opts__['transport']
)
default_profile = {}
if 'profile' in vm_ and vm_['profile'] ... | 255 | 256 | 1,784 | 5 | 250 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | create | create | 568 | 800 | 568 | 568 | 25c143628387d793727db0b95704e00414d27dac | bigcode/the-stack | train |
9cb8210a344413f8769852f7 | train | function | def rackconnect(vm_):
'''
Determine if we should wait for rackconnect automation before running.
Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'rackconnect', vm_, __opts__, default='False',
search_global=False
)
| def rackconnect(vm_):
| '''
Determine if we should wait for rackconnect automation before running.
Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'rackconnect', vm_, __opts__, default='False',
search_global=False
)
| '''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
def rackconnect(vm_):
| 64 | 64 | 64 | 6 | 58 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | rackconnect | rackconnect | 361 | 369 | 361 | 361 | db65f1669b8d0dc0d694147395a3b4d3e3f62506 | bigcode/the-stack | train |
456373435254009069ef5cd9 | train | function | def __virtual__():
'''
Set up the libcloud functions and check for OPENSTACK configurations
'''
if not HAS_LIBCLOUD:
return False
if get_configured_provider() is False:
return False
return True
| def __virtual__():
| '''
Set up the libcloud functions and check for OPENSTACK configurations
'''
if not HAS_LIBCLOUD:
return False
if get_configured_provider() is False:
return False
return True
| namespaced_function(list_nodes_full, globals())
list_nodes_select = namespaced_function(list_nodes_select, globals())
show_instance = namespaced_function(show_instance, globals())
get_node = namespaced_function(get_node, globals())
# Only load in this module is the OPENSTACK configurations are in place
def __virtual... | 64 | 64 | 53 | 5 | 58 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | __virtual__ | __virtual__ | 191 | 201 | 191 | 191 | 8f2981bf45a2945f3799e8d1b9cadd8432b95fa2 | bigcode/the-stack | train |
a0e53ff411a3b325d2ecacb7 | train | function | def managedcloud(vm_):
'''
Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'managedcloud', vm_, __opts__, default='False',
search_global=False
)
| def managedcloud(vm_):
| '''
Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'managedcloud', vm_, __opts__, default='False',
search_global=False
)
| '''
Determine if we should wait for rackconnect automation before running.
Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'rackconnect', vm_, __opts__, default='False',
search_global=False
)
def managedcloud(vm_):
| 64 | 64 | 66 | 6 | 58 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | managedcloud | managedcloud | 372 | 380 | 372 | 372 | 4b7239341dfbc4f97e0a0e2cbe59e5ee26fbd163 | bigcode/the-stack | train |
0dc6552d30b903d5782abd1c | train | function | def get_conn():
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
driver = get_driver(Provider.OPENSTACK)
authinfo = {
'ex_force_auth_url': config.get_cloud_config_value(
'identity_url', vm_, __opts__, search_global=False
),
'... | def get_conn():
| '''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
driver = get_driver(Provider.OPENSTACK)
authinfo = {
'ex_force_auth_url': config.get_cloud_config_value(
'identity_url', vm_, __opts__, search_global=False
),
'ex_force_service... | estroy, globals())
reboot = namespaced_function(reboot, globals())
list_nodes = namespaced_function(list_nodes, globals())
list_nodes_full = namespaced_function(list_nodes_full, globals())
list_nodes_select = namespaced_function(list_nodes_select, globals())
show_instance = namespaced_function(show_instance, globals())... | 193 | 193 | 645 | 4 | 189 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | get_conn | get_conn | 215 | 305 | 215 | 215 | 50e78ca18f4ad904e096b05651003c21fb35501b | bigcode/the-stack | train |
d24abbc2acb2d096363642e6 | train | function | def ignore_cidr(vm_, ip):
'''
Return True if we are to ignore the specified IP. Compatible with IPv4.
'''
if HAS_NETADDR is False:
log.error('Error: netaddr is not installed')
# If we cannot check, assume all is ok
return False
cidr = config.get_cloud_config_value(
'... | def ignore_cidr(vm_, ip):
| '''
Return True if we are to ignore the specified IP. Compatible with IPv4.
'''
if HAS_NETADDR is False:
log.error('Error: netaddr is not installed')
# If we cannot check, assume all is ok
return False
cidr = config.get_cloud_config_value(
'ignore_cidr', vm_, __opts_... | = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ignore_cidr(vm_, ip):
| 64 | 64 | 150 | 8 | 55 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | ignore_cidr | ignore_cidr | 329 | 347 | 329 | 329 | 580d8fe209f519ff6449bf780e9457a9464285d3 | bigcode/the-stack | train |
8c602f55da18a4d170b0d0fb | train | function | def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or 'openstack',
('user',)
)
| def get_configured_provider():
| '''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or 'openstack',
('user',)
)
| configurations are in place
def __virtual__():
'''
Set up the libcloud functions and check for OPENSTACK configurations
'''
if not HAS_LIBCLOUD:
return False
if get_configured_provider() is False:
return False
return True
def get_configured_provider():
| 64 | 64 | 47 | 6 | 57 | jhenry82/salt | salt/cloud/clouds/openstack.py | Python | get_configured_provider | get_configured_provider | 204 | 212 | 204 | 204 | a19f9ccfe968c8e3920df3ee67ba25ba27ae7f59 | bigcode/the-stack | train |
20c8ab6de5809e4847e61b4c | train | function | def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authent... | def _get_backends(return_tuples=False):
| backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does... | _logged_out, user_login_failed
SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
HASH_SESSION_KEY = '_auth_user_hash'
REDIRECT_FIELD_NAME = 'next'
def load_backend(path):
return import_string(path)()
def _get_backends(return_tuples=False):
| 64 | 64 | 96 | 10 | 54 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | _get_backends | _get_backends | 23 | 33 | 23 | 23 | e7e550a0795260cca148ed5f8135a320dcdff342 | bigcode/the-stack | train |
42b24c777e15220a416a3f10 | train | function | def _clean_credentials(credentials):
"""
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
"""
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
... | def _clean_credentials(credentials):
| """
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
"""
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
CLEANSED_SUBSTITUTE = '*************... | if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does '
'AUTHENTICATION_BACKENDS contain anything?'
)
return backends
def get_backends():
return _get_backends(return_tuples=False)
def _clean_credentials(credentials):
| 64 | 64 | 105 | 6 | 58 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | _clean_credentials | _clean_credentials | 40 | 52 | 40 | 40 | a6029c278bd00f9a8c0b10d0965f0041a3605359 | bigcode/the-stack | train |
781ebbcc000f759a87fd2b43 | train | function | def get_permission_codename(action, opts):
"""
Return the codename of the permission for the specified action.
"""
return '%s_%s' % (action, opts.model_name)
| def get_permission_codename(action, opts):
| """
Return the codename of the permission for the specified action.
"""
return '%s_%s' % (action, opts.model_name)
| if not (
session_hash and
hasattr(user, '_legacy_get_session_auth_hash') and
constant_time_compare(session_hash, user._legacy_get_session_auth_hash())
):
request.session.flush()
u... | 64 | 64 | 41 | 9 | 55 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | get_permission_codename | get_permission_codename | 201 | 205 | 201 | 201 | a87e302734ff56b97c7f77d917a5ca16b91fea5c | bigcode/the-stack | train |
a6d15823637804348bdff79e | train | function | def get_user(request):
"""
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = ... | def get_user(request):
| """
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = request.session[BACKEND... | =False)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
)
def get_user(req... | 70 | 70 | 234 | 5 | 65 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | get_user | get_user | 166 | 198 | 166 | 166 | ab785c875f35811e9b5a955a9316503342b1e666 | bigcode/the-stack | train |
60c48fd1207abf8206f308c3 | train | function | def _get_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
| def _get_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
| return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
| :
if SENSITIVE_CREDENTIALS.search(key):
credentials[key] = CLEANSED_SUBSTITUTE
return credentials
def _get_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
| 64 | 64 | 56 | 39 | 24 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | _get_user_session_key | _get_user_session_key | 55 | 58 | 55 | 57 | 84f41ad67a694242c9ea421224845e87f01c53ad | bigcode/the-stack | train |
db792472e5dda93b498ae9b4 | train | function | def load_backend(path):
return import_string(path)()
| def load_backend(path):
| return import_string(path)()
| django.utils.module_loading import import_string
from .signals import user_logged_in, user_logged_out, user_login_failed
SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
HASH_SESSION_KEY = '_auth_user_hash'
REDIRECT_FIELD_NAME = 'next'
def load_backend(path):
| 64 | 64 | 12 | 5 | 59 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | load_backend | load_backend | 19 | 20 | 19 | 19 | 876de8da6626b98b0d63483499e4e450a5b795d3 | bigcode/the-stack | train |
f557caef09c98eb0d1a2771f | train | function | def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
... | def login(request, user, backend=None):
| """
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user,... | try:
user = backend.authenticate(request, **credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
break
if user is None:
continue
# Annotate the user object with the path of th... | 118 | 118 | 396 | 9 | 109 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | login | login | 87 | 132 | 87 | 87 | c09bcf5474c5fa5208a73761e80aeece1cad24b6 | bigcode/the-stack | train |
259a46432dbe489cfeb025e2 | train | function | def get_backends():
return _get_backends(return_tuples=False)
| def get_backends():
| return _get_backends(return_tuples=False)
| backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does '
'AUTHENTICATION_BACKENDS contain anything?'
)
return backends
def get_backends():
| 64 | 64 | 16 | 5 | 58 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | get_backends | get_backends | 36 | 37 | 36 | 36 | 7e32483e94e87900cc4c8728d582d33078235276 | bigcode/the-stack | train |
5809ff1c46bc48ec38a97a28 | train | function | def update_session_auth_hash(request, user):
"""
Updating a user's password logs out all sessions for the user.
Take the current request and the updated user object from which the new
session hash will be derived and update the session hash appropriately to
prevent a password change from logging ou... | def update_session_auth_hash(request, user):
| """
Updating a user's password logs out all sessions for the user.
Take the current request and the updated user object from which the new
session hash will be derived and update the session hash appropriately to
prevent a password change from logging out the session from which the
password was... | .flush()
user = None
return user or AnonymousUser()
def get_permission_codename(action, opts):
"""
Return the codename of the permission for the specified action.
"""
return '%s_%s' % (action, opts.model_name)
def update_session_auth_hash(request, user):
| 64 | 64 | 113 | 9 | 55 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | update_session_auth_hash | update_session_auth_hash | 208 | 219 | 208 | 208 | bcef8281cfa0e61e433e31fe8686b5810bc20124 | bigcode/the-stack | train |
724e66f328e6f1c62432db05 | train | function | def logout(request):
"""
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if not getattr(user, 'is... | def logout(request):
| """
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if not getattr(user, 'is_authenticated', True... | request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
def logout(request):
| 64 | 64 | 128 | 4 | 60 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | logout | logout | 135 | 149 | 135 | 135 | 967549a85f8e439bf213a1ae17d31b1c278a39bc | bigcode/the-stack | train |
1e41e9c0ff3615e157d0e4c0 | train | function | def get_user_model():
"""
Return the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except ... | def get_user_model():
| """
Return the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except LookupError:
r... | (user, 'is_authenticated', True):
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user)
request.session.flush()
if hasattr(request, 'user'):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()
def get_user_model():
| 64 | 64 | 102 | 5 | 59 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | get_user_model | get_user_model | 152 | 163 | 152 | 152 | 491d9555c979ac26b831bc75590315883d9a0a7c | bigcode/the-stack | train |
0d1caca7af93623d24f331e0 | train | function | def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
backend_signature = inspect.signature(backend.authenticate)
try:
backend_signature.bind(request, **... | def authenticate(request=None, **credentials):
| """
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
backend_signature = inspect.signature(backend.authenticate)
try:
backend_signature.bind(request, **credentials)
except TypeError:
... | def _get_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
def authenticate(request=None, **credentials):
| 64 | 64 | 197 | 8 | 56 | DemarcusL/django_wiki_lab | djangox/lib/python3.8/site-packages/django/contrib/auth/__init__.py | Python | authenticate | authenticate | 61 | 84 | 61 | 61 | 5479c2ac78dc815d4e62a3de8747b1193d3d9ddd | bigcode/the-stack | train |
1aaf3c27815f51e6f2167f99 | train | class | class Person:
name: str | class Person:
| name: str | class Person:
| 3 | 64 | 7 | 3 | 0 | rfrezino/hexagonal-sanity-check | tests/integration_tests/utils/sample_projects/wrong_clean_arch_project/domain/person.py | Python | Person | Person | 1 | 2 | 1 | 1 | 12b297301cba2e1929e418ab5d8cef784cfe95d1 | bigcode/the-stack | train |
599bd4792c27c0c80bb78a6b | train | class | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt'):
"""
Args:
patience (int): How long to wait after last time validation loss improved.
... | class EarlyStopping:
| """Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt'):
"""
Args:
patience (int): How long to wait after last time validation loss improved.
De... | import numpy as np
import torch
class EarlyStopping:
| 12 | 120 | 400 | 4 | 7 | joycenerd/rsna-pneumonia-detection | efficientnet/early_stop.py | Python | EarlyStopping | EarlyStopping | 5 | 53 | 5 | 5 | 4ffbf06227a74405024e8a0a9938ead4b01b6b90 | bigcode/the-stack | train |
59afb7aaf99941dfaecf62ef | train | function | def comp(params):
v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if v1 != v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1
else:
if globl.mode == globl.modes.bootloader:
globl.bootl += 7
... | def comp(params):
| v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if v1 != v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1
else:
if globl.mode == globl.modes.bootloader:
globl.bootl += 7
elif globl.mode =... | import shareddata as globl
import encodedecode as ed
# Compare
def comp(params):
| 20 | 64 | 134 | 4 | 15 | Ewpratten/dirobium | src/compare.py | Python | comp | comp | 5 | 18 | 5 | 5 | dfa8b53d7ed56a01e4f183dd8a5781403252ac49 | bigcode/the-stack | train |
4fd51ee045fc10ce5bda89bb | train | function | def lte(params):
v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if not v1 <= v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1
| def lte(params):
| v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if not v1 <= v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1
| globl.roml +=1
else:
if globl.mode == globl.modes.bootloader:
globl.bootl += 7
elif globl.mode == globl.modes.rom:
globl.roml +=7
# Less or equal
def lte(params):
| 64 | 64 | 90 | 5 | 58 | Ewpratten/dirobium | src/compare.py | Python | lte | lte | 21 | 29 | 21 | 21 | 7f5b6e51eb54d3ae8b8723c74f720ecdf7218b29 | bigcode/the-stack | train |
1dfceb7c3240935e67dcc2ed | train | function | def gte(params):
v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if not v1 >= v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1 | def gte(params):
| v1 = ed.decode([params[1], params[2], params])
v2 = ed.decode([params[3], params[4], params])
if not v1 >= v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1 | ])
if not v1 <= v2:
if globl.mode == globl.modes.bootloader:
globl.bootl += 1
elif globl.mode == globl.modes.rom:
globl.roml +=1
# Greater or equal
def gte(params):
| 64 | 64 | 89 | 5 | 58 | Ewpratten/dirobium | src/compare.py | Python | gte | gte | 32 | 40 | 32 | 32 | dcb55b5281ad48bcff054ba081de63f1f64c5b49 | bigcode/the-stack | train |
a7f7d222dd3ddaf3d05b1973 | train | function | @router.get("/statuses", response_model=List[ProcessStatus])
def statuses() -> List[str]:
return [status.value for status in ProcessStatus]
| @router.get("/statuses", response_model=List[ProcessStatus])
def statuses() -> List[str]:
| return [status.value for status in ProcessStatus]
| Unable to interact with processes at this time. Engine StatusEnum is locked")
raise_status(
HTTPStatus.SERVICE_UNAVAILABLE, detail="Engine is locked cannot accept changes on processes at this time"
)
@router.get("/statuses", response_model=List[ProcessStatus])
def statuses() -> List[str]:
| 64 | 64 | 32 | 21 | 43 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | statuses | statuses | 196 | 198 | 196 | 197 | cc20534d3578a7a9dcfadb2b16b62e337e9a7723 | bigcode/the-stack | train |
f8099192f14335b36dbd2f3a | train | function | @router.get("/process-subscriptions-by-pid/{pid}", response_model=List[ProcessSubscriptionBaseSchema])
def process_subscriptions_by_process_pid(pid: UUID) -> List[ProcessSubscriptionTable]:
return ProcessSubscriptionTable.query.filter_by(pid=pid).all()
| @router.get("/process-subscriptions-by-pid/{pid}", response_model=List[ProcessSubscriptionBaseSchema])
def process_subscriptions_by_process_pid(pid: UUID) -> List[ProcessSubscriptionTable]:
| return ProcessSubscriptionTable.query.filter_by(pid=pid).all()
| .subscription_id == subscription_id)
.order_by(ProcessTable.started_at.asc())
)
return query.all()
@router.get("/process-subscriptions-by-pid/{pid}", response_model=List[ProcessSubscriptionBaseSchema])
def process_subscriptions_by_process_pid(pid: UUID) -> List[ProcessSubscriptionTable]:
| 64 | 64 | 55 | 41 | 23 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | process_subscriptions_by_process_pid | process_subscriptions_by_process_pid | 175 | 177 | 175 | 176 | 623db4fbff10b90349c4da95e9b34c5645aa8a3a | bigcode/the-stack | train |
708f30a52a2ea7f653c88f64 | train | function | @router.post("/{workflow_key}", response_model=ProcessIdSchema, status_code=HTTPStatus.CREATED)
def new_process(
workflow_key: str,
json_data: Optional[List[Dict[str, Any]]] = Body(...),
user: Optional[OIDCUserModel] = Depends(oidc_user),
) -> Dict[str, UUID]:
check_global_lock()
user_name = user.u... | @router.post("/{workflow_key}", response_model=ProcessIdSchema, status_code=HTTPStatus.CREATED)
def new_process(
workflow_key: str,
json_data: Optional[List[Dict[str, Any]]] = Body(...),
user: Optional[OIDCUserModel] = Depends(oidc_user),
) -> Dict[str, UUID]:
| check_global_lock()
user_name = user.user_name if user else SYSTEM_USER
pid = start_process(workflow_key, user_inputs=json_data, user=user_name)[0]
return {"id": pid}
| @router.post("/{workflow_key}", response_model=ProcessIdSchema, status_code=HTTPStatus.CREATED)
def new_process(
workflow_key: str,
json_data: Optional[List[Dict[str, Any]]] = Body(...),
user: Optional[OIDCUserModel] = Depends(oidc_user),
) -> Dict[str, UUID]:
| 71 | 64 | 116 | 71 | 0 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | new_process | new_process | 84 | 95 | 84 | 89 | f52f2a48997b698aa27415b3fefd0dbc1b2936fc | bigcode/the-stack | train |
88f56ce4723b61a571aed838 | train | function | def check_global_lock() -> None:
"""
Check the global lock of the engine.
Returns:
None or raises an exception
"""
engine_settings = EngineSettingsTable.query.one()
if engine_settings.global_lock:
logger.info("Unable to interact with processes at this time. Engine StatusEnum is... | def check_global_lock() -> None:
| """
Check the global lock of the engine.
Returns:
None or raises an exception
"""
engine_settings = EngineSettingsTable.query.one()
if engine_settings.global_lock:
logger.info("Unable to interact with processes at this time. Engine StatusEnum is locked")
raise_status(
... | ()
@router.get("/process-subscriptions-by-pid/{pid}", response_model=List[ProcessSubscriptionBaseSchema])
def process_subscriptions_by_process_pid(pid: UUID) -> List[ProcessSubscriptionTable]:
return ProcessSubscriptionTable.query.filter_by(pid=pid).all()
def check_global_lock() -> None:
| 64 | 64 | 95 | 8 | 56 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | check_global_lock | check_global_lock | 180 | 193 | 180 | 180 | 01aebe0341bc272c4321b9539de011fc9be9536a | bigcode/the-stack | train |
87ac3c082214152232aac5bb | train | function | @router.get(
"/process-subscriptions-by-subscription-id/{subscription_id}", response_model=List[ProcessSubscriptionSchema]
)
def process_subscriptions_by_subscription_id(subscription_id: UUID) -> List[ProcessSubscriptionSchema]:
query = (
ProcessSubscriptionTable.query.options(contains_eager(ProcessSubs... | @router.get(
"/process-subscriptions-by-subscription-id/{subscription_id}", response_model=List[ProcessSubscriptionSchema]
)
def process_subscriptions_by_subscription_id(subscription_id: UUID) -> List[ProcessSubscriptionSchema]:
| query = (
ProcessSubscriptionTable.query.options(contains_eager(ProcessSubscriptionTable.process))
.join(ProcessTable)
.filter(ProcessSubscriptionTable.subscription_id == subscription_id)
.order_by(ProcessTable.started_at.asc())
)
return query.all()
| except Exception as e:
raise_status(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
@router.get(
"/process-subscriptions-by-subscription-id/{subscription_id}", response_model=List[ProcessSubscriptionSchema]
)
def process_subscriptions_by_subscription_id(subscription_id: UUID) -> List[ProcessSubscriptionSchema]:
| 64 | 64 | 100 | 46 | 18 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | process_subscriptions_by_subscription_id | process_subscriptions_by_subscription_id | 162 | 172 | 162 | 165 | 352b246a0a5209e54d0576ab3fde0058aad832de | bigcode/the-stack | train |
ef4734ff688a9104684f79ac | train | function | @router.websocket("/all/")
@websocket_enabled
async def websocket_process_list(websocket: WebSocket, token: str = Query(...)) -> None:
error = await websocket_manager.authorize(websocket, token)
await websocket.accept()
if error:
await websocket_manager.disconnect(websocket, reason=error)
r... | @router.websocket("/all/")
@websocket_enabled
async def websocket_process_list(websocket: WebSocket, token: str = Query(...)) -> None:
| error = await websocket_manager.authorize(websocket, token)
await websocket.accept()
if error:
await websocket_manager.disconnect(websocket, reason=error)
return
channel = WS_CHANNELS.ALL_PROCESSES
await websocket_manager.connect(websocket, channel)
| :
raise CacheHit(HTTPStatus.NOT_MODIFIED, headers=dict(response.headers))
return [asdict(enrich_process(p)) for p in results]
@router.websocket("/all/")
@websocket_enabled
async def websocket_process_list(websocket: WebSocket, token: str = Query(...)) -> None:
| 64 | 64 | 90 | 32 | 32 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | websocket_process_list | websocket_process_list | 355 | 366 | 355 | 357 | 6eaa8d4eac9b43bd7a128dc07646ed902d289780 | bigcode/the-stack | train |
3c4f92b3ec704b88f0e4f365 | train | function | @router.delete("/{pid}", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def delete(pid: UUID) -> None:
count = ProcessTable.query.filter_by(pid=pid).delete()
db.session.commit()
if count > 0:
return None
else:
raise_status(HTTPStatus.NOT_FOUND)
| @router.delete("/{pid}", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def delete(pid: UUID) -> None:
| count = ProcessTable.query.filter_by(pid=pid).delete()
db.session.commit()
if count > 0:
return None
else:
raise_status(HTTPStatus.NOT_FOUND)
| orchestrator.websocket import WS_CHANNELS, websocket_enabled, websocket_manager
from orchestrator.workflow import ProcessStatus
router = APIRouter()
logger = structlog.get_logger(__name__)
@router.delete("/{pid}", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def delete(pid: UUID) -> None:
| 64 | 64 | 69 | 27 | 37 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | delete | delete | 74 | 81 | 74 | 75 | f0cabf2f9760cddceff6db2ea26707699776f8a3 | bigcode/the-stack | train |
9cd30e6e79e040c83984e62d | train | function | @router.get("/{pid}", response_model=ProcessSchema)
def show(pid: UUID) -> Dict[str, Any]:
process = _get_process(pid)
p = load_process(process)
data = show_process(process, p)
return data
| @router.get("/{pid}", response_model=ProcessSchema)
def show(pid: UUID) -> Dict[str, Any]:
| process = _get_process(pid)
p = load_process(process)
data = show_process(process, p)
return data
| Status]
@router.get("/assignees", response_model=List[Assignee])
def assignees() -> List[str]:
return [assignee.value for assignee in Assignee]
@router.get("/{pid}", response_model=ProcessSchema)
def show(pid: UUID) -> Dict[str, Any]:
| 64 | 64 | 52 | 24 | 40 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | show | show | 206 | 212 | 206 | 207 | ad4268141066599a33c500031084ee4a1eb9f6c7 | bigcode/the-stack | train |
de74b8d351ffa343e4c65f0c | train | function | @router.put("/{pid}/resume", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def resume_process_endpoint(
pid: UUID, json_data: JSON = Body(...), user: Optional[OIDCUserModel] = Depends(oidc_user)
) -> None:
check_global_lock()
process = _get_process(pid)
if process.last_status == ProcessStatu... | @router.put("/{pid}/resume", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def resume_process_endpoint(
pid: UUID, json_data: JSON = Body(...), user: Optional[OIDCUserModel] = Depends(oidc_user)
) -> None:
| check_global_lock()
process = _get_process(pid)
if process.last_status == ProcessStatus.RUNNING:
raise_status(HTTPStatus.CONFLICT, "Resuming a running workflow is not possible")
user_name = user.user_name if user else SYSTEM_USER
resume_process(process, user=user_name, user_inputs=json_d... | return {"id": pid}
@router.put("/{pid}/resume", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def resume_process_endpoint(
pid: UUID, json_data: JSON = Body(...), user: Optional[OIDCUserModel] = Depends(oidc_user)
) -> None:
| 64 | 64 | 128 | 58 | 6 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | resume_process_endpoint | resume_process_endpoint | 98 | 111 | 98 | 101 | 191f38b3716cad989d0d2f5f53ba17424d739bf8 | bigcode/the-stack | train |
7261e4ad0146231ecab170d8 | train | function | @router.get("/assignees", response_model=List[Assignee])
def assignees() -> List[str]:
return [assignee.value for assignee in Assignee]
| @router.get("/assignees", response_model=List[Assignee])
def assignees() -> List[str]:
| return [assignee.value for assignee in Assignee]
| processes at this time"
)
@router.get("/statuses", response_model=List[ProcessStatus])
def statuses() -> List[str]:
return [status.value for status in ProcessStatus]
@router.get("/assignees", response_model=List[Assignee])
def assignees() -> List[str]:
| 64 | 64 | 38 | 25 | 39 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | assignees | assignees | 201 | 203 | 201 | 202 | 0c9555c76d565fcf498d4494deb93ab9c5e3b8e2 | bigcode/the-stack | train |
cad389df9bac4e07c21929ce | train | function | @router.put("/{pid}/abort", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def abort_process_endpoint(pid: UUID, user: Optional[OIDCUserModel] = Depends(oidc_user)) -> None:
process = _get_process(pid)
user_name = user.user_name if user else SYSTEM_USER
try:
abort_process(process, user_na... | @router.put("/{pid}/abort", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def abort_process_endpoint(pid: UUID, user: Optional[OIDCUserModel] = Depends(oidc_user)) -> None:
| process = _get_process(pid)
user_name = user.user_name if user else SYSTEM_USER
try:
abort_process(process, user_name)
return None
except Exception as e:
raise_status(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
| (processes_to_resume))
return {"count": len(processes_to_resume)}
@router.put("/{pid}/abort", response_model=None, status_code=HTTPStatus.NO_CONTENT)
def abort_process_endpoint(pid: UUID, user: Optional[OIDCUserModel] = Depends(oidc_user)) -> None:
| 63 | 64 | 102 | 47 | 16 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | abort_process_endpoint | abort_process_endpoint | 149 | 159 | 149 | 150 | 146fc63933689b3116a72fa15196b6d378494659 | bigcode/the-stack | train |
4ae46cd96fa3a1ec935dd292 | train | function | @router.get("/", response_model=List[ProcessListItemSchema])
def processes_filterable(
response: Response,
range: Optional[str] = None,
sort: Optional[str] = None,
filter: Optional[str] = None,
if_none_match: Optional[str] = Header(None),
) -> List[Dict[str, Any]]:
_range: Union[List[int], None]... | @router.get("/", response_model=List[ProcessListItemSchema])
def processes_filterable(
response: Response,
range: Optional[str] = None,
sort: Optional[str] = None,
filter: Optional[str] = None,
if_none_match: Optional[str] = Header(None),
) -> List[Dict[str, Any]]:
| _range: Union[List[int], None] = list(map(int, range.split(","))) if range else None
_sort: Union[List[str], None] = sort.split(",") if sort else None
_filter: Union[List[str], None] = filter.split(",") if filter else None
logger.info("processes_filterable() called", range=_range, sort=_sort, filter=_fi... | _settings = EngineSettingsTable.query.one()
if engine_settings.global_lock:
logger.info("Unable to interact with processes at this time. Engine StatusEnum is locked")
raise_status(
HTTPStatus.SERVICE_UNAVAILABLE, detail="Engine is locked cannot accept changes on processes at this time"
... | 256 | 256 | 1,374 | 72 | 183 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | processes_filterable | processes_filterable | 215 | 352 | 215 | 222 | 02d560f8b28dc0b64f831505a3ca4aa515111cd9 | bigcode/the-stack | train |
7754cab751d97496256a9182 | train | function | @router.put("/resume-all", response_model=ProcessResumeAllSchema)
async def resume_all_processess_endpoint(user: Optional[OIDCUserModel] = Depends(oidc_user)) -> Dict[str, int]:
"""Retry all task processes in status Failed, Waiting, API Unavailable or Inconsistent Data.
The retry is started in the background, ... | @router.put("/resume-all", response_model=ProcessResumeAllSchema)
async def resume_all_processess_endpoint(user: Optional[OIDCUserModel] = Depends(oidc_user)) -> Dict[str, int]:
| """Retry all task processes in status Failed, Waiting, API Unavailable or Inconsistent Data.
The retry is started in the background, returning status 200 and number of processes in message.
When it is already running, refuse and return status 409 instead.
"""
check_global_lock()
user_name = us... | Resuming a running workflow is not possible")
user_name = user.user_name if user else SYSTEM_USER
resume_process(process, user=user_name, user_inputs=json_data)
@router.put("/resume-all", response_model=ProcessResumeAllSchema)
async def resume_all_processess_endpoint(user: Optional[OIDCUserModel] = Depends(oi... | 80 | 80 | 267 | 44 | 36 | florisie/orchestrator-core | orchestrator/api/api_v1/endpoints/processes.py | Python | resume_all_processess_endpoint | resume_all_processess_endpoint | 114 | 146 | 114 | 115 | a01232363b8efa27a47440e94683a9077c2d2225 | bigcode/the-stack | train |
aa3ec5ddf1818bfb31a42954 | train | function | def swap_values(args):
args[0], args[1] = args[1], args[0]
| def swap_values(args):
| args[0], args[1] = args[1], args[0]
| # [8 kyu] Swap Values
#
# Author: Hsins
# Date: 2019/12/17
def swap_values(args):
| 34 | 64 | 23 | 5 | 28 | Hsins/CodeWars | Python/8 kyu/Swap Values/solution.py | Python | swap_values | swap_values | 7 | 8 | 7 | 7 | 16c6f37733175967a7f2e045f739ffb8aceedef1 | bigcode/the-stack | train |
dd7d69f44b5e1606e296b356 | train | function | def main():
if True: #Later-Check to see what operating system the user is using. Add Mac Support.
print("Avaiable Options:\n • 'New': Roblox's new cursors\n • 'Old': Roblox's old cursors\n • 'Classic': Roblox's classic cursors\n • 'Custom': Your own preset\nOr enter an directory.")
startdir = in... | def main():
| if True: #Later-Check to see what operating system the user is using. Add Mac Support.
print("Avaiable Options:\n • 'New': Roblox's new cursors\n • 'Old': Roblox's old cursors\n • 'Classic': Roblox's classic cursors\n • 'Custom': Your own preset\nOr enter an directory.")
startdir = input("> ")
... | Roblox\Versions"
new_cursor_file = "\content\\textures\Cursors\KeyboardMouse"
custom_cursors = ".\Cursors"
Options = {
"Old": ".\OldCursors",
"New": ".\\NewCursors",
"Classic": ".\Classic",
"Custom": ".\Custom",
}
def main():
| 72 | 72 | 243 | 3 | 69 | RealZ9R/RobloxAutoCursorChanger | Autochange.py | Python | main | main | 16 | 35 | 16 | 16 | de6f8763a8786e90601e5722a32dbe32c91ad25d | bigcode/the-stack | train |
0a78b202fb49359194f26c1c | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0002_auto_20210411_2009'),
]
operations = [
migrations.AlterModelOptions(
name='bookinstance',
options={'ordering': ['status', 'du... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0002_auto_20210411_2009'),
]
operations = [
migrations.AlterModelOptions(
name='bookinstance',
options={'ordering': ['status', 'due_back']},
),
migrations... | # Generated by Django 3.2 on 2021-04-21 17:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 49 | 64 | 120 | 7 | 41 | pjgg92/django_local_library | catalog/migrations/0003_auto_20210421_1926.py | Python | Migration | Migration | 8 | 25 | 8 | 9 | ba8355dacb7bc539919958ac2aa25571d6a7626e | bigcode/the-stack | train |
868ecec8c7de2fe9db53c15d | train | class | class FileForLammps:
def __init__(self, name: str, material: dict, charges: dict, atom_masses: dict, subfolder_path: str, atom_id: dict):
self.path = f'{subfolder_path}\\{name}'
self.name = name
if len(charges) != len(atom_masses):
raise Exception('length of charges dict != len... | class FileForLammps:
| def __init__(self, name: str, material: dict, charges: dict, atom_masses: dict, subfolder_path: str, atom_id: dict):
self.path = f'{subfolder_path}\\{name}'
self.name = name
if len(charges) != len(atom_masses):
raise Exception('length of charges dict != length of atom masses di... | _masses: dict, charges: dict):
self.File_for_lammps = File_for_lammps
self.prefix_sub_folder = prefix_sub_folder
self.subfolders_paths = subfolders_paths
self.materials_list = materials_list
self.charges = charges
self.atoms_masses = atoms_masses
self.Fil... | 232 | 232 | 775 | 7 | 224 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | FileForLammps | FileForLammps | 117 | 205 | 117 | 117 | 2ff29ed117c1572d7bea9408c40e525a79efeb3f | bigcode/the-stack | train |
2dd328ea4e29e27a78e27628 | train | class | class EquationOfMaterial:
def __init__(self, equation: str, many_glasses: bool = False, x_value: float = 0):
self.equation = equation
self.many_glasses = many_glasses
self.x_value = x_value
def get_proportion_of_atoms(self) -> dict:
proportions_of_oxides = self.get_proportion... | class EquationOfMaterial:
| def __init__(self, equation: str, many_glasses: bool = False, x_value: float = 0):
self.equation = equation
self.many_glasses = many_glasses
self.x_value = x_value
def get_proportion_of_atoms(self) -> dict:
proportions_of_oxides = self.get_proportions_of_oxides()
propor... | _json = atom[0:2]
atom_masses_dict.update({atom : json_file_content[atom_in_json]})
return atom_masses_dict
class Folder:
def __init__(self, path: str ='', name: str = '', prefix: str = '', nr_of_folders: int = 0):
'''Folder class creates directory for input simulations files'''
... | 256 | 256 | 1,794 | 6 | 249 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | EquationOfMaterial | EquationOfMaterial | 325 | 534 | 325 | 326 | 7df5eb067514bf763f3fa748fe5df3aa16495b3e | bigcode/the-stack | train |
2d6f34f1b79296634bd1ca7a | train | class | class NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect(Exception):
pass
| class NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect(Exception):
| pass
| = int(ratio * number) + atoms_in_system[anion]
else:
atoms_in_system[anion] = int(ratio * number)
return atoms_in_system
class IncorectFilePath(Exception):
pass
class NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect(Exception):
| 64 | 64 | 19 | 16 | 47 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect | NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect | 564 | 565 | 564 | 564 | 202c62981ea547fbc008bbd6f4ec11dab804e6e2 | bigcode/the-stack | train |
d2c14a5c0caf77e429371d03 | train | class | class FilesForLammps:
def __init__(self, File_for_lammps: type, subfolders_paths: list, prefix_sub_folder: str, materials_list: list,
atoms_masses: dict, charges: dict):
self.File_for_lammps = File_for_lammps
self.prefix_sub_folder = prefix_sub_folder
self.subfolders_paths ... | class FilesForLammps:
| def __init__(self, File_for_lammps: type, subfolders_paths: list, prefix_sub_folder: str, materials_list: list,
atoms_masses: dict, charges: dict):
self.File_for_lammps = File_for_lammps
self.prefix_sub_folder = prefix_sub_folder
self.subfolders_paths = subfolders_paths
... | atoms_id: dict):
self.path = path
self.atoms_id = atoms_id
def create_file(self):
path = self.path + '/atoms_id.txt'
with open(path, 'w') as file:
for name, id in self.atoms_id.items():
file.write(f'{name}: {id}\n')
class FilesForLammps:
| 79 | 79 | 266 | 7 | 72 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | FilesForLammps | FilesForLammps | 85 | 114 | 85 | 85 | a7f3e987470b42eaf5c7b7eaec23ea5d3dfacdcd | bigcode/the-stack | train |
fd7465f9bcf060c35ab33792 | train | class | class Constants:
avogadro_constant = 6.02214076 * (10 ** 23) | class Constants:
| avogadro_constant = 6.02214076 * (10 ** 23) | + atoms_in_system[anion]
else:
atoms_in_system[anion] = int(ratio * number)
return atoms_in_system
class IncorectFilePath(Exception):
pass
class NumberOfItemsOnTheListOfOxidesAndCoefficientsIncorrect(Exception):
pass
class Constants:
| 64 | 64 | 24 | 4 | 59 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | Constants | Constants | 568 | 569 | 568 | 568 | 0a7acee29588036e8fae1f8f0b98558880579c13 | bigcode/the-stack | train |
69eaed553cc0d6ed55403593 | train | class | class MaterialsList:
"""
In this class objects input data are process to obtain materials list.
one element in list contain important data:
atom types, quantity of given atom type, quantity of all atoms in system, volume of system.
For better understanding find test: Get list of ma... | class MaterialsList:
| """
In this class objects input data are process to obtain materials list.
one element in list contain important data:
atom types, quantity of given atom type, quantity of all atoms in system, volume of system.
For better understanding find test: Get list of materials in test/test_... | _atoms_positions(self):
with open(f'{self.path}.txt', 'a') as file:
file.write('Atoms\n\n')
random_cord = lambda: round(random() * self.length_of_simulation_box_edge, 6)
number = 0
i = 1
while i < self.quantity + 1:
... | 256 | 256 | 922 | 4 | 252 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | MaterialsList | MaterialsList | 208 | 297 | 208 | 208 | 531228f390ca5db78eb1aab4a9df8c8bf98ab107 | bigcode/the-stack | train |
0241d1f760df8e1b266d07f4 | train | class | class IncorectFilePath(Exception):
pass
| class IncorectFilePath(Exception):
| pass
| number})
if (anion in atoms_in_system.keys()):
atoms_in_system[anion] = int(ratio * number) + atoms_in_system[anion]
else:
atoms_in_system[anion] = int(ratio * number)
return atoms_in_system
class IncorectFilePath(Exception):
| 64 | 64 | 11 | 8 | 55 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | IncorectFilePath | IncorectFilePath | 560 | 561 | 560 | 560 | b62f11d5fa663582425eb9856943db355ee09e13 | bigcode/the-stack | train |
86a9d64e6a3f3a0cb3d7dca2 | train | class | class FileWithAtomsId():
def __init__(self, path: str, atoms_id: dict):
self.path = path
self.atoms_id = atoms_id
def create_file(self):
path = self.path + '/atoms_id.txt'
with open(path, 'w') as file:
for name, id in self.atoms_id.items():
file.write... | class FileWithAtomsId():
| def __init__(self, path: str, atoms_id: dict):
self.path = path
self.atoms_id = atoms_id
def create_file(self):
path = self.path + '/atoms_id.txt'
with open(path, 'w') as file:
for name, id in self.atoms_id.items():
file.write(f'{name}: {id}\n')
| name_of_folder
file_with_atoms_id = FileWithAtomsId(directory, atoms_id)
file_with_atoms_id.create_file()
if progress_bar != None and application_gui != None:
progress_bar['value'] = 100
application_gui.update_idletasks()
class FileWithAtomsId():
| 64 | 64 | 89 | 6 | 58 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | FileWithAtomsId | FileWithAtomsId | 73 | 82 | 73 | 73 | f41469ff477c36ceb3bd918802cc33334bd497c1 | bigcode/the-stack | train |
a4935b217ab2b9cef02b60fa | train | class | class App:
def __init__(self):
self.directory = ''
def set_directory(self, directory):
self.directory = directory
def make_folders_with_data_for_lammps(self, name_of_folder: str, prefix_sub_folder: str, equation: str, many_glasses: bool,
atoms_in_single_material: int, str_density_l... | class App:
| def __init__(self):
self.directory = ''
def set_directory(self, directory):
self.directory = directory
def make_folders_with_data_for_lammps(self, name_of_folder: str, prefix_sub_folder: str, equation: str, many_glasses: bool,
atoms_in_single_material: int, str_density_list: str, s... | """
@author: Pawel Goj
"""
import os
import re
from fractions import Fraction
from random import random
from typing import Optional
from tkinter.ttk import Progressbar
try:
from program.config import Config
except:
from main.program.config import Config
import json
PATH = Config.PATH_TO_JSON_FILE_WITH_MASS... | 76 | 147 | 492 | 3 | 72 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | App | App | 20 | 70 | 20 | 20 | a424944d76b90ad60a77cc4ab07734fbeb1ef1ea | bigcode/the-stack | train |
0881f16772d36237f5721989 | train | class | class CompositionOfMaterial:
def __init__(self, proportions_of_atoms: dict, number_of_atoms_in_system: int):
self.proportions_of_atoms= proportions_of_atoms
self.number_of_atoms_in_system = number_of_atoms_in_system
def get_atoms_in_system(self) -> dict:
atoms_in_system = {}
... | class CompositionOfMaterial:
| def __init__(self, proportions_of_atoms: dict, number_of_atoms_in_system: int):
self.proportions_of_atoms= proportions_of_atoms
self.number_of_atoms_in_system = number_of_atoms_in_system
def get_atoms_in_system(self) -> dict:
atoms_in_system = {}
for key in self.proportio... | ][0] / sum)
return dictionary
@staticmethod
def remove_empty_list_elements(list: list) -> list:
return [item for item in list if item != '']
@staticmethod
def round_math_part(number) -> float:
return round(float(number), 6)
class CompositionOfMaterial:
| 68 | 68 | 228 | 5 | 63 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | CompositionOfMaterial | CompositionOfMaterial | 537 | 557 | 537 | 537 | 26da8f4667ffd9009468d882a3b3dc3b93ded3e2 | bigcode/the-stack | train |
b622cb3d4989211866801a66 | train | class | class Folder:
def __init__(self, path: str ='', name: str = '', prefix: str = '', nr_of_folders: int = 0):
'''Folder class creates directory for input simulations files'''
if path == '' or name == '' or prefix == '' or nr_of_folders == 0:
raise IncorectFilePath('No path to directory!!!'... | class Folder:
| def __init__(self, path: str ='', name: str = '', prefix: str = '', nr_of_folders: int = 0):
'''Folder class creates directory for input simulations files'''
if path == '' or name == '' or prefix == '' or nr_of_folders == 0:
raise IncorectFilePath('No path to directory!!!')
else:... | :
json_file_content = json.load(fileJ)
atom_masses_dict = {}
for atom in composition.keys():
atom_in_json = atom[0:2]
atom_masses_dict.update({atom : json_file_content[atom_in_json]})
return atom_masses_dict
class Folder:
| 65 | 65 | 217 | 4 | 60 | pawelgoj/CDFFL-Create-data-files-for-lammps-amorphous-simulations | main/program/cord_rand.py | Python | Folder | Folder | 300 | 322 | 300 | 300 | 4cc5d21bf497ef70f7e2177f668efc75337972e0 | bigcode/the-stack | train |
d370058b553e97211f9ea6f5 | train | function | @websocket_api.async_response
@websocket_api.websocket_command({vol.Required("type"): "hacs/repositories"})
async def hacs_repositories(_hass, connection, msg):
"""Handle get media player cover command."""
hacs = get_hacs()
repositories = hacs.repositories
content = []
for repo in repositories:
... | @websocket_api.async_response
@websocket_api.websocket_command({vol.Required("type"): "hacs/repositories"})
async def hacs_repositories(_hass, connection, msg):
| """Handle get media player cover command."""
hacs = get_hacs()
repositories = hacs.repositories
content = []
for repo in repositories:
if repo.data.category in hacs.comperson2.categories:
data = {
"additional_info": repo.information.additional_info,
... | """API Handler for hacs_repositories"""
import voluptuous as vol
from homeassistant.components import websocket_api
from custom_components.hacs.share import get_hacs
@websocket_api.async_response
@websocket_api.websocket_command({vol.Required("type"): "hacs/repositories"})
async def hacs_repositories(_hass, connection... | 73 | 146 | 488 | 39 | 33 | sjabby/home-assistant-conf | custom_components/hacs/api/hacs_repositories.py | Python | hacs_repositories | hacs_repositories | 8 | 62 | 8 | 10 | 59b7596774d69c50152bcf7d0aeb18ab6ff5cc34 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.