language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 173897,
"end": 207238
} | class ____:
def test_sign_invalid_hash_algorithm(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([])
)
with pytest.raises(TypeError):
builder.sign(
private_key,
"NotAHash", # type: ignore[arg-type]
backend,
)
@pytest.mark.supported(
only_if=lambda backend: backend.ed25519_supported(),
skip_message="Requires OpenSSL with Ed25519 support",
)
def test_request_with_unsupported_hash_ed25519(self, backend):
private_key = ed25519.Ed25519PrivateKey.generate()
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
@pytest.mark.supported(
only_if=lambda backend: backend.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_request_with_unsupported_hash_ed448(self, backend):
private_key = ed448.Ed448PrivateKey.generate()
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_no_subject_name(self, rsa_key_2048: rsa.RSAPrivateKey, backend):
private_key = rsa_key_2048
builder = x509.CertificateSigningRequestBuilder()
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_build_ca_request_with_rsa(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA")]
)
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, hashes.SHA256(), backend)
)
assert isinstance(request.signature_hash_algorithm, hashes.SHA256)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert isinstance(basic_constraints.value, x509.BasicConstraints)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
def test_build_ca_request_with_unicode(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
NameOID.ORGANIZATION_NAME, "PyCA\U0001f37a"
),
]
)
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, hashes.SHA256(), backend)
)
loaded_request = x509.load_pem_x509_csr(
request.public_bytes(encoding=serialization.Encoding.PEM), backend
)
subject = loaded_request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA\U0001f37a"),
]
def test_subject_dn_asn1_types(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(NameOID.COMMON_NAME, "mysite.com"),
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "value"),
x509.NameAttribute(
NameOID.STATE_OR_PROVINCE_NAME, "value"
),
x509.NameAttribute(NameOID.STREET_ADDRESS, "value"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "value"),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME, "value"
),
x509.NameAttribute(NameOID.SERIAL_NUMBER, "value"),
x509.NameAttribute(NameOID.SURNAME, "value"),
x509.NameAttribute(NameOID.GIVEN_NAME, "value"),
x509.NameAttribute(NameOID.TITLE, "value"),
x509.NameAttribute(
NameOID.GENERATION_QUALIFIER, "value"
),
x509.NameAttribute(
NameOID.X500_UNIQUE_IDENTIFIER, "value"
),
x509.NameAttribute(NameOID.DN_QUALIFIER, "value"),
x509.NameAttribute(NameOID.PSEUDONYM, "value"),
x509.NameAttribute(NameOID.USER_ID, "value"),
x509.NameAttribute(NameOID.DOMAIN_COMPONENT, "value"),
x509.NameAttribute(NameOID.EMAIL_ADDRESS, "value"),
x509.NameAttribute(
NameOID.JURISDICTION_COUNTRY_NAME, "US"
),
x509.NameAttribute(
NameOID.JURISDICTION_LOCALITY_NAME, "value"
),
x509.NameAttribute(
NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME,
"value",
),
x509.NameAttribute(NameOID.BUSINESS_CATEGORY, "value"),
x509.NameAttribute(NameOID.POSTAL_ADDRESS, "value"),
x509.NameAttribute(NameOID.POSTAL_CODE, "value"),
]
)
)
.sign(private_key, hashes.SHA256(), backend)
)
for oid, asn1_type in TestNameAttribute.EXPECTED_TYPES:
assert (
request.subject.get_attributes_for_oid(oid)[0]._type
== asn1_type
)
def test_build_ca_request_with_multivalue_rdns(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
subject = x509.Name(
[
x509.RelativeDistinguishedName(
[
x509.NameAttribute(NameOID.TITLE, "Test"),
x509.NameAttribute(NameOID.COMMON_NAME, "Multivalue"),
x509.NameAttribute(NameOID.SURNAME, "RDNs"),
]
),
x509.RelativeDistinguishedName(
[x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA")]
),
]
)
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.sign(private_key, hashes.SHA256(), backend)
)
loaded_request = x509.load_pem_x509_csr(
request.public_bytes(encoding=serialization.Encoding.PEM), backend
)
assert isinstance(loaded_request.subject, x509.Name)
assert loaded_request.subject == subject
def test_build_nonca_request_with_rsa(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None),
critical=True,
)
.sign(private_key, hashes.SHA256(), backend)
)
assert isinstance(request.signature_hash_algorithm, hashes.SHA256)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert isinstance(basic_constraints.value, x509.BasicConstraints)
assert basic_constraints.value.ca is False
assert basic_constraints.value.path_length is None
def test_build_ca_request_with_ec(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
NameOID.STATE_OR_PROVINCE_NAME, "Texas"
),
]
)
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, hashes.SHA256(), backend)
)
assert isinstance(request.signature_hash_algorithm, hashes.SHA256)
public_key = request.public_key()
assert isinstance(public_key, ec.EllipticCurvePublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert isinstance(basic_constraints.value, x509.BasicConstraints)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
def test_build_ca_request_with_deterministic_ec(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
_skip_deterministic_ecdsa_unsupported(backend)
private_key = ec.generate_private_key(ec.SECP256R1())
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([])
)
csr1 = builder.sign(
private_key,
hashes.SHA256(),
backend,
ecdsa_deterministic=True,
)
csr2 = builder.sign(
private_key,
hashes.SHA256(),
backend,
ecdsa_deterministic=True,
)
csr_nondet = builder.sign(
private_key,
hashes.SHA256(),
backend,
)
csr_nondet2 = builder.sign(
private_key,
hashes.SHA256(),
backend,
)
assert csr1.signature == csr2.signature
assert csr1.signature != csr_nondet.signature
assert csr_nondet.signature != csr_nondet2.signature
private_key.public_key().verify(
csr1.signature,
csr1.tbs_certrequest_bytes,
ec.ECDSA(hashes.SHA256()),
)
def test_csr_deterministic_wrong_key_type(self, rsa_key_2048, backend):
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([])
)
with pytest.raises(TypeError):
builder.sign(
rsa_key_2048,
hashes.SHA256(),
backend,
ecdsa_deterministic=True,
)
@pytest.mark.supported(
only_if=lambda backend: backend.ed25519_supported(),
skip_message="Requires OpenSSL with Ed25519 support",
)
def test_build_ca_request_with_ed25519(self, backend):
private_key = ed25519.Ed25519PrivateKey.generate()
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
NameOID.STATE_OR_PROVINCE_NAME, "Texas"
),
]
)
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, None, backend)
)
assert request.signature_hash_algorithm is None
public_key = request.public_key()
assert isinstance(public_key, ed25519.Ed25519PublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"),
]
basic_constraints = request.extensions.get_extension_for_class(
x509.BasicConstraints
)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
@pytest.mark.supported(
only_if=lambda backend: backend.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
)
def test_build_ca_request_with_ed448(self, backend):
private_key = ed448.Ed448PrivateKey.generate()
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
NameOID.STATE_OR_PROVINCE_NAME, "Texas"
),
]
)
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, None, backend)
)
assert request.signature_hash_algorithm is None
public_key = request.public_key()
assert isinstance(public_key, ed448.Ed448PublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"),
]
basic_constraints = request.extensions.get_extension_for_class(
x509.BasicConstraints
)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
@pytest.mark.supported(
only_if=lambda backend: backend.dsa_supported(),
skip_message="Does not support DSA.",
)
def test_build_ca_request_with_dsa(self, backend):
private_key = DSA_KEY_2048.private_key(backend)
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, hashes.SHA256(), backend)
)
assert isinstance(request.signature_hash_algorithm, hashes.SHA256)
public_key = request.public_key()
assert isinstance(public_key, dsa.DSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert isinstance(basic_constraints.value, x509.BasicConstraints)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
def test_add_duplicate_extension(self):
builder = x509.CertificateSigningRequestBuilder().add_extension(
x509.BasicConstraints(True, 2),
critical=True,
)
with pytest.raises(ValueError):
builder.add_extension(
x509.BasicConstraints(True, 2),
critical=True,
)
def test_set_invalid_subject(self):
builder = x509.CertificateSigningRequestBuilder()
with pytest.raises(TypeError):
builder.subject_name("NotAName") # type:ignore[arg-type]
def test_add_invalid_extension_type(self):
builder = x509.CertificateSigningRequestBuilder()
with pytest.raises(TypeError):
builder.add_extension(
object(), # type:ignore[arg-type]
False,
)
def test_add_unsupported_extension(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
builder = x509.CertificateSigningRequestBuilder()
builder = (
builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
.add_extension(
x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]),
critical=False,
)
.add_extension(DummyExtension(), False)
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_add_two_extensions(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
builder = x509.CertificateSigningRequestBuilder()
request = (
builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
.add_extension(
x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]),
critical=False,
)
.add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
)
.sign(private_key, hashes.SHA256(), backend)
)
assert isinstance(request.signature_hash_algorithm, hashes.SHA256)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert isinstance(basic_constraints.value, x509.BasicConstraints)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
ext = request.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
assert isinstance(ext.value, x509.SubjectAlternativeName)
assert list(ext.value) == [x509.DNSName("cryptography.io")]
def test_add_attributes(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
challenge_password = b"challenge me!"
unstructured_name = b"no structure, for shame"
locality = b"this shouldn't even be an X509 attribute"
request = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
x509.NameAttribute(
NameOID.STATE_OR_PROVINCE_NAME, "Texas"
),
]
)
)
.add_attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD, challenge_password
)
.add_attribute(
x509.oid.AttributeOID.UNSTRUCTURED_NAME, unstructured_name
)
.add_attribute(x509.oid.NameOID.LOCALITY_NAME, locality)
.add_extension(
x509.ExtendedKeyUsage(
[
ExtendedKeyUsageOID.CLIENT_AUTH,
ExtendedKeyUsageOID.SERVER_AUTH,
ExtendedKeyUsageOID.CODE_SIGNING,
]
),
False,
)
.sign(private_key, hashes.SHA256(), backend)
)
assert (
request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.CHALLENGE_PASSWORD
).value
== challenge_password
)
assert (
request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.UNSTRUCTURED_NAME
).value
== unstructured_name
)
assert (
request.attributes.get_attribute_for_oid(
x509.oid.NameOID.LOCALITY_NAME
).value
== locality
)
assert len(request.attributes) == 4
def test_add_attributes_non_utf8(self, backend):
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
builder = (
x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([]))
.add_attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD,
b"\xbb\xad\x16\x9a\xac\xc9\x03i\xec\xcc\xdd6\xcbh\xfc\xf3",
)
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_add_attribute_bad_types(self, backend):
request = x509.CertificateSigningRequestBuilder()
with pytest.raises(TypeError):
request.add_attribute(
b"not an oid", # type:ignore[arg-type]
b"val",
)
with pytest.raises(TypeError):
request.add_attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD,
383, # type:ignore[arg-type]
)
def test_duplicate_attribute(self, backend):
request = x509.CertificateSigningRequestBuilder().add_attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD, b"val"
)
with pytest.raises(ValueError):
request.add_attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD, b"val2"
)
def test_add_attribute_tag(self, backend):
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
builder = (
x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([]))
.add_attribute(
x509.ObjectIdentifier("1.2.3.4"),
b"\x00\x00",
_tag=_ASN1Type.GeneralizedTime,
)
)
request = builder.sign(private_key, hashes.SHA256(), backend)
attr = request.attributes.get_attribute_for_oid(
x509.ObjectIdentifier("1.2.3.4")
)
assert attr.value == b"\x00\x00"
assert attr._type == _ASN1Type.GeneralizedTime.value
def test_add_attribute_tag_non_int(self, backend):
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([])
)
with pytest.raises(TypeError):
builder.add_attribute(
x509.ObjectIdentifier("1.2.3.4"),
b"",
_tag=object(), # type:ignore[arg-type]
)
def test_set_subject_twice(self):
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
with pytest.raises(ValueError):
builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
@pytest.mark.parametrize(
"add_ext",
[
x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=True,
),
x509.SubjectAlternativeName(
[
x509.DNSName("example.com"),
x509.DNSName("*.example.com"),
x509.RegisteredID(x509.ObjectIdentifier("1.2.3.4.5.6.7")),
x509.DirectoryName(
x509.Name(
[
x509.NameAttribute(
NameOID.COMMON_NAME, "PyCA"
),
x509.NameAttribute(
NameOID.ORGANIZATION_NAME,
"We heart UTF8!\u2122",
),
]
)
),
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
x509.IPAddress(ipaddress.ip_address("ff::")),
x509.OtherName(
type_id=x509.ObjectIdentifier("1.2.3.3.3.3"),
value=b"0\x03\x02\x01\x05",
),
x509.RFC822Name("test@example.com"),
x509.RFC822Name("email"),
x509.RFC822Name("email@xn--eml-vla4c.com"),
x509.UniformResourceIdentifier(
"https://xn--80ato2c.cryptography"
),
x509.UniformResourceIdentifier(
"gopher://cryptography:70/some/path"
),
]
),
x509.ExtendedKeyUsage(
[
ExtendedKeyUsageOID.CLIENT_AUTH,
ExtendedKeyUsageOID.SERVER_AUTH,
ExtendedKeyUsageOID.CODE_SIGNING,
]
),
],
)
def test_extensions(
self, rsa_key_2048: rsa.RSAPrivateKey, add_ext, backend
):
private_key = rsa_key_2048
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "SAN")])
)
.add_extension(
add_ext,
critical=False,
)
.sign(private_key, hashes.SHA256(), backend)
)
assert len(csr.extensions) == 1
ext = csr.extensions.get_extension_for_class(type(add_ext))
assert not ext.critical
assert ext.value == add_ext
def test_invalid_asn1_othername(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
builder = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "SAN")])
)
.add_extension(
x509.SubjectAlternativeName(
[
x509.OtherName(
type_id=x509.ObjectIdentifier("1.2.3.3.3.3"),
# Invalid length
value=b"\x01\x05\x01\x05",
),
]
),
critical=False,
)
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_subject_alt_name_unsupported_general_name(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
builder = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "SAN")])
)
.add_extension(
x509.SubjectAlternativeName([FakeGeneralName("")]),
critical=False,
)
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
def test_rsa_key_too_small(self, rsa_key_512: rsa.RSAPrivateKey, backend):
private_key = rsa_key_512
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA512(), backend)
@pytest.mark.parametrize(
("alg", "mgf_alg"),
[
(hashes.SHA512(), hashes.SHA256()),
(hashes.SHA3_512(), hashes.SHA3_256()),
],
)
def test_sign_pss(
self, rsa_key_2048: rsa.RSAPrivateKey, alg, mgf_alg, backend
):
if not backend.signature_hash_supported(alg):
pytest.skip(f"{alg} signature not supported")
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
pss = padding.PSS(
mgf=padding.MGF1(mgf_alg), salt_length=alg.digest_size
)
csr = builder.sign(rsa_key_2048, alg, rsa_padding=pss)
pk = csr.public_key()
assert isinstance(pk, rsa.RSAPublicKey)
assert isinstance(csr.signature_hash_algorithm, type(alg))
cert_params = csr.signature_algorithm_parameters
assert isinstance(cert_params, padding.PSS)
assert cert_params._salt_length == pss._salt_length
assert isinstance(cert_params._mgf, padding.MGF1)
assert isinstance(cert_params._mgf._algorithm, type(mgf_alg))
pk.verify(
csr.signature,
csr.tbs_certrequest_bytes,
cert_params,
alg,
)
@pytest.mark.parametrize(
("padding_len", "computed_len"),
[
(padding.PSS.MAX_LENGTH, 222),
(padding.PSS.DIGEST_LENGTH, 32),
],
)
def test_sign_pss_length_options(
self,
rsa_key_2048: rsa.RSAPrivateKey,
padding_len,
computed_len,
backend,
):
pss = padding.PSS(
mgf=padding.MGF1(hashes.SHA256()), salt_length=padding_len
)
if not backend.rsa_padding_supported(pss):
pytest.skip("PSS padding with these parameters not supported")
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
pss = padding.PSS(
mgf=padding.MGF1(hashes.SHA256()), salt_length=padding_len
)
csr = builder.sign(rsa_key_2048, hashes.SHA256(), rsa_padding=pss)
assert isinstance(csr.signature_algorithm_parameters, padding.PSS)
assert csr.signature_algorithm_parameters._salt_length == computed_len
def test_sign_pss_auto_unsupported(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
pss = padding.PSS(
mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.AUTO
)
with pytest.raises(TypeError):
builder.sign(rsa_key_2048, hashes.SHA256(), rsa_padding=pss)
def test_sign_invalid_padding(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
with pytest.raises(TypeError):
builder.sign(
rsa_key_2048,
hashes.SHA256(),
rsa_padding=b"notapadding", # type: ignore[arg-type]
)
eckey = ec.generate_private_key(ec.SECP256R1())
with pytest.raises(TypeError):
builder.sign(
eckey, hashes.SHA256(), rsa_padding=padding.PKCS1v15()
)
def test_sign_pss_hash_none(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, "US")])
)
pss = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32)
with pytest.raises(TypeError):
builder.sign(rsa_key_2048, None, rsa_padding=pss)
@pytest.mark.supported(
only_if=lambda backend: backend.dsa_supported(),
skip_message="Does not support DSA.",
)
| TestCertificateSigningRequestBuilder |
python | pytorch__pytorch | test/test_testing.py | {
"start": 1408,
"end": 11585
} | class ____(TestCase):
# Ensure that assertEqual handles numpy arrays properly
@dtypes(*all_types_and_complex_and(torch.bool, torch.half))
def test_assertEqual_numpy(self, device, dtype):
S = 10
test_sizes = [
(),
(0,),
(S,),
(S, S),
(0, S),
(S, 0)]
for test_size in test_sizes:
a = make_tensor(test_size, dtype=dtype, device=device, low=-5, high=5)
a_n = a.cpu().numpy()
msg = f'size: {test_size}'
self.assertEqual(a_n, a, rtol=0, atol=0, msg=msg)
self.assertEqual(a, a_n, rtol=0, atol=0, msg=msg)
self.assertEqual(a_n, a_n, rtol=0, atol=0, msg=msg)
def test_assertEqual_longMessage(self):
actual = "actual"
expected = "expected"
long_message = self.longMessage
try:
# Capture the default error message by forcing TestCase.longMessage = False
self.longMessage = False
try:
self.assertEqual(actual, expected)
except AssertionError as error:
default_msg = str(error)
else:
raise AssertionError("AssertionError not raised")
self.longMessage = True
extra_msg = "sentinel"
with self.assertRaisesRegex(AssertionError, re.escape(f"{default_msg}\n{extra_msg}")):
self.assertEqual(actual, expected, msg=extra_msg)
finally:
self.longMessage = long_message
def _isclose_helper(self, tests, device, dtype, equal_nan, atol=1e-08, rtol=1e-05):
for test in tests:
a = torch.tensor((test[0],), device=device, dtype=dtype)
b = torch.tensor((test[1],), device=device, dtype=dtype)
actual = torch.isclose(a, b, equal_nan=equal_nan, atol=atol, rtol=rtol)
expected = test[2]
self.assertEqual(actual.item(), expected)
def test_isclose_bool(self, device):
tests = (
(True, True, True),
(False, False, True),
(True, False, False),
(False, True, False),
)
self._isclose_helper(tests, device, torch.bool, False)
@dtypes(torch.uint8,
torch.int8, torch.int16, torch.int32, torch.int64)
def test_isclose_integer(self, device, dtype):
tests = (
(0, 0, True),
(0, 1, False),
(1, 0, False),
)
self._isclose_helper(tests, device, dtype, False)
# atol and rtol tests
tests = [
(0, 1, True),
(1, 0, False),
(1, 3, True),
]
self._isclose_helper(tests, device, dtype, False, atol=.5, rtol=.5)
if dtype is torch.uint8:
tests = [
(-1, 1, False),
(1, -1, False)
]
else:
tests = [
(-1, 1, True),
(1, -1, True)
]
self._isclose_helper(tests, device, dtype, False, atol=1.5, rtol=.5)
@onlyNativeDeviceTypes
@dtypes(torch.float16, torch.float32, torch.float64)
def test_isclose_float(self, device, dtype):
tests = (
(0, 0, True),
(0, -1, False),
(float('inf'), float('inf'), True),
(-float('inf'), float('inf'), False),
(float('inf'), float('nan'), False),
(float('nan'), float('nan'), False),
(0, float('nan'), False),
(1, 1, True),
)
self._isclose_helper(tests, device, dtype, False)
# atol and rtol tests
eps = 1e-2 if dtype is torch.half else 1e-6
tests = (
(0, 1, True),
(0, 1 + eps, False),
(1, 0, False),
(1, 3, True),
(1 - eps, 3, False),
(-.25, .5, True),
(-.25 - eps, .5, False),
(.25, -.5, True),
(.25 + eps, -.5, False),
)
self._isclose_helper(tests, device, dtype, False, atol=.5, rtol=.5)
# equal_nan = True tests
tests = (
(0, float('nan'), False),
(float('inf'), float('nan'), False),
(float('nan'), float('nan'), True),
)
self._isclose_helper(tests, device, dtype, True)
@unittest.skipIf(IS_SANDCASTLE, "Skipping because doesn't work on sandcastle")
@dtypes(torch.complex64, torch.complex128)
def test_isclose_complex(self, device, dtype):
tests = (
(complex(1, 1), complex(1, 1 + 1e-8), True),
(complex(0, 1), complex(1, 1), False),
(complex(1, 1), complex(1, 0), False),
(complex(1, 1), complex(1, float('nan')), False),
(complex(1, float('nan')), complex(1, float('nan')), False),
(complex(1, 1), complex(1, float('inf')), False),
(complex(float('inf'), 1), complex(1, float('inf')), False),
(complex(-float('inf'), 1), complex(1, float('inf')), False),
(complex(-float('inf'), 1), complex(float('inf'), 1), False),
(complex(float('inf'), 1), complex(float('inf'), 1), True),
(complex(float('inf'), 1), complex(float('inf'), 1 + 1e-4), False),
)
self._isclose_helper(tests, device, dtype, False)
# atol and rtol tests
# atol and rtol tests
eps = 1e-6
tests = (
# Complex versions of float tests (real part)
(complex(0, 0), complex(1, 0), True),
(complex(0, 0), complex(1 + eps, 0), False),
(complex(1, 0), complex(0, 0), False),
(complex(1, 0), complex(3, 0), True),
(complex(1 - eps, 0), complex(3, 0), False),
(complex(-.25, 0), complex(.5, 0), True),
(complex(-.25 - eps, 0), complex(.5, 0), False),
(complex(.25, 0), complex(-.5, 0), True),
(complex(.25 + eps, 0), complex(-.5, 0), False),
# Complex versions of float tests (imaginary part)
(complex(0, 0), complex(0, 1), True),
(complex(0, 0), complex(0, 1 + eps), False),
(complex(0, 1), complex(0, 0), False),
(complex(0, 1), complex(0, 3), True),
(complex(0, 1 - eps), complex(0, 3), False),
(complex(0, -.25), complex(0, .5), True),
(complex(0, -.25 - eps), complex(0, .5), False),
(complex(0, .25), complex(0, -.5), True),
(complex(0, .25 + eps), complex(0, -.5), False),
)
self._isclose_helper(tests, device, dtype, False, atol=.5, rtol=.5)
# atol and rtol tests for isclose
tests = (
# Complex-specific tests
(complex(1, -1), complex(-1, 1), False),
(complex(1, -1), complex(2, -2), True),
(complex(-math.sqrt(2), math.sqrt(2)),
complex(-math.sqrt(.5), math.sqrt(.5)), True),
(complex(-math.sqrt(2), math.sqrt(2)),
complex(-math.sqrt(.501), math.sqrt(.499)), False),
(complex(2, 4), complex(1., 8.8523607), True),
(complex(2, 4), complex(1., 8.8523607 + eps), False),
(complex(1, 99), complex(4, 100), True),
)
self._isclose_helper(tests, device, dtype, False, atol=.5, rtol=.5)
# equal_nan = True tests
tests = (
(complex(1, 1), complex(1, float('nan')), False),
(complex(1, 1), complex(float('nan'), 1), False),
(complex(float('nan'), 1), complex(float('nan'), 1), True),
(complex(float('nan'), 1), complex(1, float('nan')), True),
(complex(float('nan'), float('nan')), complex(float('nan'), float('nan')), True),
)
self._isclose_helper(tests, device, dtype, True)
# Tests that isclose with rtol or atol values less than zero throws a
# RuntimeError
@dtypes(torch.bool, torch.uint8,
torch.int8, torch.int16, torch.int32, torch.int64,
torch.float16, torch.float32, torch.float64)
def test_isclose_atol_rtol_greater_than_zero(self, device, dtype):
t = torch.tensor((1,), device=device, dtype=dtype)
with self.assertRaises(RuntimeError):
torch.isclose(t, t, atol=-1, rtol=1)
with self.assertRaises(RuntimeError):
torch.isclose(t, t, atol=1, rtol=-1)
with self.assertRaises(RuntimeError):
torch.isclose(t, t, atol=-1, rtol=-1)
def test_isclose_equality_shortcut(self):
# For values >= 2**53, integers differing by 1 can no longer differentiated by torch.float64 or lower precision
# floating point dtypes. Thus, even with rtol == 0 and atol == 0, these tensors would be considered close if
# they were not compared as integers.
a = torch.tensor(2 ** 53, dtype=torch.int64)
b = a + 1
self.assertFalse(torch.isclose(a, b, rtol=0, atol=0))
@dtypes(torch.float16, torch.float32, torch.float64, torch.complex64, torch.complex128)
def test_isclose_nan_equality_shortcut(self, device, dtype):
if dtype.is_floating_point:
a = b = torch.nan
else:
a = complex(torch.nan, 0)
b = complex(0, torch.nan)
expected = True
tests = [(a, b, expected)]
self._isclose_helper(tests, device, dtype, equal_nan=True, rtol=0, atol=0)
# The following tests (test_cuda_assert_*) are added to ensure test suite terminates early
# when CUDA assert was thrown. Because all subsequent test will fail if that happens.
# These tests are slow because it spawn another process to run test suite.
# See: https://github.com/pytorch/pytorch/issues/49019
@unittest.skipIf(TEST_WITH_ROCM, "ROCm doesn't support device side asserts")
@onlyCUDA
@slowTest
def test_cuda_assert_should_stop_common_utils_test_suite(self, device):
# test to ensure common_utils.py override has early termination for CUDA.
stderr = TestCase.runWithPytorchAPIUsageStderr("""\
#!/usr/bin/env python3
import torch
from torch.testing._internal.common_utils import (TestCase, run_tests, slowTest)
| TestTesting |
python | Lightning-AI__lightning | examples/fabric/tensor_parallel/model.py | {
"start": 5639,
"end": 8624
} | class ____(nn.Module):
"""Multi-head attention module.
Args:
model_args (ModelArgs): Model configuration arguments.
Attributes:
n_kv_heads (int): Number of key and value heads.
n_heads (int): Number of query heads.
n_rep (int): Number of repetitions for local heads.
head_dim (int): Dimension size of each attention head.
wq (Linear): Linear transformation for queries.
wk (Linear): Linear transformation for keys.
wv (Linear): Linear transformation for values.
wo (Linear): Linear transformation for output.
"""
def __init__(self, model_args: ModelArgs):
super().__init__()
self.n_heads = model_args.n_heads
self.n_kv_heads = model_args.n_heads if model_args.n_kv_heads is None else model_args.n_kv_heads
self.n_rep = self.n_heads // self.n_kv_heads
self.head_dim = model_args.dim // model_args.n_heads
self.wq = nn.Linear(model_args.dim, model_args.n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(model_args.dim, self.n_kv_heads * self.head_dim, bias=False)
self.wv = nn.Linear(model_args.dim, self.n_kv_heads * self.head_dim, bias=False)
self.wo = nn.Linear(model_args.n_heads * self.head_dim, model_args.dim, bias=False)
def init_weights(self, init_std: float):
for linear in (self.wq, self.wk, self.wv):
nn.init.trunc_normal_(linear.weight, mean=0.0, std=0.02)
nn.init.trunc_normal_(self.wo.weight, mean=0.0, std=init_std)
def forward(
self,
x: torch.Tensor,
freqs_cis: torch.Tensor,
):
"""Forward pass of the attention module.
Args:
x (torch.Tensor): Input tensor.
freqs_cis (torch.Tensor): Precomputed frequency tensor.
Returns:
torch.Tensor: Output tensor after attention.
"""
bs, seqlen, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
xq = xq.view(bs, seqlen, self.n_heads, self.head_dim)
xk = xk.view(bs, seqlen, self.n_kv_heads, self.head_dim)
xv = xv.view(bs, seqlen, self.n_kv_heads, self.head_dim)
xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
# repeat k/v heads if n_kv_heads < n_heads
keys = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
values = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
xq = xq.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
xk = keys.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
xv = values.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
# we use casual mask for training
output = F.scaled_dot_product_attention(xq, xk, xv, is_causal=True)
output = output.transpose(1, 2).contiguous() # (bs, seqlen, n_local_heads, head_dim)
output = output.view(bs, seqlen, -1)
return self.wo(output)
| Attention |
python | coleifer__peewee | playhouse/postgres_ext.py | {
"start": 7094,
"end": 7165
} | class ____(DateTimeField):
field_type = 'TIMESTAMPTZ'
| DateTimeTZField |
python | keras-team__keras | keras/src/layers/activations/leaky_relu.py | {
"start": 180,
"end": 1912
} | class ____(Layer):
"""Leaky version of a Rectified Linear Unit activation layer.
This layer allows a small gradient when the unit is not active.
Formula:
``` python
f(x) = alpha * x if x < 0
f(x) = x if x >= 0
```
Example:
``` python
leaky_relu_layer = LeakyReLU(negative_slope=0.5)
input = np.array([-10, -5, 0.0, 5, 10])
result = leaky_relu_layer(input)
# result = [-5. , -2.5, 0. , 5. , 10.]
```
Args:
negative_slope: Float >= 0.0. Negative slope coefficient.
Defaults to `0.3`.
**kwargs: Base layer keyword arguments, such as
`name` and `dtype`.
"""
def __init__(self, negative_slope=0.3, **kwargs):
if "alpha" in kwargs:
negative_slope = kwargs.pop("alpha")
warnings.warn(
"Argument `alpha` is deprecated. Use `negative_slope` instead."
)
super().__init__(**kwargs)
if negative_slope is None or negative_slope < 0:
raise ValueError(
"The negative_slope value of a Leaky ReLU layer "
"cannot be None or negative value. Expected a float."
f" Received: negative_slope={negative_slope}"
)
self.negative_slope = negative_slope
self.supports_masking = True
self._build_at_init()
def call(self, inputs):
return activations.leaky_relu(
inputs, negative_slope=self.negative_slope
)
def get_config(self):
config = super().get_config()
config.update({"negative_slope": self.negative_slope})
return config
def compute_output_shape(self, input_shape):
return input_shape
| LeakyReLU |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-okta/source_okta/components.py | {
"start": 877,
"end": 2018
} | class ____(DeclarativeOauth2Authenticator):
@property
def auth_header(self) -> str:
return "Authorization"
@property
def token(self) -> str:
return f"SSWS {self.get_access_token()}"
def get_auth_header(self) -> Mapping[str, Any]:
return {"Authorization": f"SSWS {self.get_access_token()}"}
def get_refresh_request_body(self) -> Mapping[str, Any]:
return {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
}
def refresh_access_token(self) -> Tuple[str, int]:
try:
response = requests.request(
method="POST",
url=self.token_refresh_endpoint,
data=self.get_refresh_request_body(),
auth=(self.client_id, self.client_secret),
)
response.raise_for_status()
response_json = response.json()
return response_json["access_token"], response_json["expires_in"]
except Exception as e:
raise Exception(f"Error while refreshing access token: {e}") from e
@dataclass
| CustomOauth2Authenticator |
python | rapidsai__cudf | python/dask_cudf/dask_cudf/io/parquet.py | {
"start": 14650,
"end": 15557
} | class ____(FusedIO):
def _task(self, name, index: int):
expr = self.operand("_expr")
bucket = self._fusion_buckets[index]
io_func = expr._filtered_task(name, 0).func
if not isinstance(
io_func, ParquetFunctionWrapper
) or io_func.common_kwargs.get("partitions", None):
# Just use "simple" fusion if we have an unexpected
# callable, or we are dealing with hive partitioning.
return Task(
name,
cudf.concat,
TaskList(*(expr._filtered_task(name, i) for i in bucket)),
)
pieces = []
for i in bucket:
piece = expr._filtered_task(name, i).args[0]
if isinstance(piece, list):
pieces.extend(piece)
else:
pieces.append(piece)
return Task(name, io_func, pieces)
| CudfFusedIO |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 66579,
"end": 68793
} | class ____(Response):
"""
Response of projects.get_model_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if
'include_system' is set to 'true' in the request
:type system_tags: Sequence[str]
"""
_service = "projects"
_action = "get_model_tags"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"system_tags": {
"description": "The list of unique system tag values. Returned only if 'include_system' is set to 'true' in the request",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "The list of unique tag values",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, **kwargs: Any
) -> None:
super(GetModelTagsResponse, self).__init__(**kwargs)
self.tags = tags
self.system_tags = system_tags
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
| GetModelTagsResponse |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 35184,
"end": 40831
} | class ____(Handler, StringFormatterHandlerMixin):
"""Like a stream handler but keeps the values in memory. This
logger provides some ways to test for the records in memory.
Example usage::
def my_test():
with logbook.TestHandler() as handler:
logger.warning("A warning")
assert logger.has_warning("A warning")
...
"""
default_format_string = TEST_FORMAT_STRING
def __init__(
self,
level=NOTSET,
format_string=None,
filter=None,
bubble=False,
force_heavy_init=False,
):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
#: captures the :class:`LogRecord`\s as instances
self.records = []
self._formatted_records = []
self._formatted_record_cache = []
self._force_heavy_init = force_heavy_init
def close(self):
"""Close all records down when the handler is closed."""
for record in self.records:
record.close()
def emit(self, record):
# keep records open because we will want to examine them after the
# call to the emit function. If we don't do that, the traceback
# attribute and other things will already be removed.
record.keep_open = True
if self._force_heavy_init:
record.heavy_init()
self.records.append(record)
@property
def formatted_records(self):
"""Captures the formatted log records as unicode strings."""
if len(self._formatted_record_cache) != len(self.records) or any(
r1 != r2 for r1, r2 in zip(self.records, self._formatted_record_cache)
):
self._formatted_records = [self.format(r) for r in self.records]
self._formatted_record_cache = list(self.records)
return self._formatted_records
@property
def has_criticals(self):
"""`True` if any :data:`CRITICAL` records were found."""
return any(r.level == CRITICAL for r in self.records)
@property
def has_errors(self):
"""`True` if any :data:`ERROR` records were found."""
return any(r.level == ERROR for r in self.records)
@property
def has_warnings(self):
"""`True` if any :data:`WARNING` records were found."""
return any(r.level == WARNING for r in self.records)
@property
def has_notices(self):
"""`True` if any :data:`NOTICE` records were found."""
return any(r.level == NOTICE for r in self.records)
@property
def has_infos(self):
"""`True` if any :data:`INFO` records were found."""
return any(r.level == INFO for r in self.records)
@property
def has_debugs(self):
"""`True` if any :data:`DEBUG` records were found."""
return any(r.level == DEBUG for r in self.records)
@property
def has_traces(self):
"""`True` if any :data:`TRACE` records were found."""
return any(r.level == TRACE for r in self.records)
def has_critical(self, *args, **kwargs):
"""`True` if a specific :data:`CRITICAL` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = CRITICAL
return self._test_for(*args, **kwargs)
def has_error(self, *args, **kwargs):
"""`True` if a specific :data:`ERROR` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = ERROR
return self._test_for(*args, **kwargs)
def has_warning(self, *args, **kwargs):
"""`True` if a specific :data:`WARNING` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = WARNING
return self._test_for(*args, **kwargs)
def has_notice(self, *args, **kwargs):
"""`True` if a specific :data:`NOTICE` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = NOTICE
return self._test_for(*args, **kwargs)
def has_info(self, *args, **kwargs):
"""`True` if a specific :data:`INFO` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = INFO
return self._test_for(*args, **kwargs)
def has_debug(self, *args, **kwargs):
"""`True` if a specific :data:`DEBUG` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = DEBUG
return self._test_for(*args, **kwargs)
def has_trace(self, *args, **kwargs):
"""`True` if a specific :data:`TRACE` log record exists.
See :ref:`probe-log-records` for more information.
"""
kwargs["level"] = TRACE
return self._test_for(*args, **kwargs)
def _test_for(self, message=None, channel=None, level=None):
def _match(needle, haystack):
"""Matches both compiled regular expressions and strings"""
if isinstance(needle, REGTYPE) and needle.search(haystack):
return True
if needle == haystack:
return True
return False
for record in self.records:
if level is not None and record.level != level:
continue
if channel is not None and record.channel != channel:
continue
if message is not None and not _match(message, record.message):
continue
return True
return False
| TestHandler |
python | Pylons__pyramid | tests/test_predicates.py | {
"start": 11692,
"end": 13537
} | class ____(unittest.TestCase):
def _makeOne(self, val, config):
from pyramid.predicates import PhysicalPathPredicate
return PhysicalPathPredicate(val, config)
def test_text(self):
inst = self._makeOne('/', None)
self.assertEqual(inst.text(), "physical_path = ('',)")
def test_phash(self):
inst = self._makeOne('/', None)
self.assertEqual(inst.phash(), "physical_path = ('',)")
def test_it_call_val_tuple_True(self):
inst = self._makeOne(('', 'abc'), None)
root = Dummy()
root.__name__ = ''
root.__parent__ = None
context = Dummy()
context.__name__ = 'abc'
context.__parent__ = root
self.assertTrue(inst(context, None))
def test_it_call_val_list_True(self):
inst = self._makeOne(['', 'abc'], None)
root = Dummy()
root.__name__ = ''
root.__parent__ = None
context = Dummy()
context.__name__ = 'abc'
context.__parent__ = root
self.assertTrue(inst(context, None))
def test_it_call_val_str_True(self):
inst = self._makeOne('/abc', None)
root = Dummy()
root.__name__ = ''
root.__parent__ = None
context = Dummy()
context.__name__ = 'abc'
context.__parent__ = root
self.assertTrue(inst(context, None))
def test_it_call_False(self):
inst = self._makeOne('/', None)
root = Dummy()
root.__name__ = ''
root.__parent__ = None
context = Dummy()
context.__name__ = 'abc'
context.__parent__ = root
self.assertFalse(inst(context, None))
def test_it_call_context_has_no_name(self):
inst = self._makeOne('/', None)
context = Dummy()
self.assertFalse(inst(context, None))
| Test_PhysicalPathPredicate |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/pagination_strategies/count_based_pagination_strategy.py | {
"start": 171,
"end": 583
} | class ____(PaginationStrategy):
@staticmethod
def update(response: List[Dict[str, Any]]) -> None:
if len(response) < 100:
response.extend([response.pop()] * (100 - len(response)))
elif len(response) > 100:
response_page = response[:100]
response.clear()
response.extend(response_page)
else:
pass
| CountBasedPaginationStrategy |
python | run-llama__llama_index | llama-index-core/llama_index/core/extractors/metadata_extractors.py | {
"start": 11947,
"end": 16047
} | class ____(BaseExtractor):
"""
Summary extractor. Node-level extractor with adjacent sharing.
Extracts `section_summary`, `prev_section_summary`, `next_section_summary`
metadata fields.
Args:
llm (Optional[LLM]): LLM
summaries (List[str]): list of summaries to extract: 'self', 'prev', 'next'
prompt_template (str): template for summary extraction
"""
llm: SerializeAsAny[LLM] = Field(description="The LLM to use for generation.")
summaries: List[str] = Field(
description="List of summaries to extract: 'self', 'prev', 'next'"
)
prompt_template: str = Field(
default=DEFAULT_SUMMARY_EXTRACT_TEMPLATE,
description="Template to use when generating summaries.",
)
_self_summary: bool = PrivateAttr()
_prev_summary: bool = PrivateAttr()
_next_summary: bool = PrivateAttr()
def __init__(
self,
llm: Optional[LLM] = None,
# TODO: llm_predictor arg is deprecated
llm_predictor: Optional[LLM] = None,
summaries: List[str] = ["self"],
prompt_template: str = DEFAULT_SUMMARY_EXTRACT_TEMPLATE,
num_workers: int = DEFAULT_NUM_WORKERS,
**kwargs: Any,
):
# validation
if not all(s in ["self", "prev", "next"] for s in summaries):
raise ValueError("summaries must be one of ['self', 'prev', 'next']")
super().__init__(
llm=llm or llm_predictor or Settings.llm,
summaries=summaries,
prompt_template=prompt_template,
num_workers=num_workers,
**kwargs,
)
self._self_summary = "self" in summaries
self._prev_summary = "prev" in summaries
self._next_summary = "next" in summaries
@classmethod
def class_name(cls) -> str:
return "SummaryExtractor"
async def _agenerate_node_summary(self, node: BaseNode) -> str:
"""Generate a summary for a node."""
if self.is_text_node_only and not isinstance(node, TextNode):
return ""
context_str = node.get_content(metadata_mode=self.metadata_mode)
summary = await self.llm.apredict(
PromptTemplate(template=self.prompt_template), context_str=context_str
)
return summary.strip()
async def aextract(self, nodes: Sequence[BaseNode]) -> List[Dict]:
if not all(isinstance(node, TextNode) for node in nodes):
raise ValueError("Only `TextNode` is allowed for `Summary` extractor")
node_summaries_jobs = []
for node in nodes:
node_summaries_jobs.append(self._agenerate_node_summary(node))
node_summaries = await run_jobs(
node_summaries_jobs,
show_progress=self.show_progress,
workers=self.num_workers,
)
# Extract node-level summary metadata
metadata_list: List[Dict] = [{} for _ in nodes]
for i, metadata in enumerate(metadata_list):
if i > 0 and self._prev_summary and node_summaries[i - 1]:
metadata["prev_section_summary"] = node_summaries[i - 1]
if i < len(nodes) - 1 and self._next_summary and node_summaries[i + 1]:
metadata["next_section_summary"] = node_summaries[i + 1]
if self._self_summary and node_summaries[i]:
metadata["section_summary"] = node_summaries[i]
return metadata_list
DEFAULT_ENTITY_MAP = {
"PER": "persons",
"ORG": "organizations",
"LOC": "locations",
"ANIM": "animals",
"BIO": "biological",
"CEL": "celestial",
"DIS": "diseases",
"EVE": "events",
"FOOD": "foods",
"INST": "instruments",
"MEDIA": "media",
"PLANT": "plants",
"MYTH": "mythological",
"TIME": "times",
"VEHI": "vehicles",
}
DEFAULT_ENTITY_MODEL = "tomaarsen/span-marker-mbert-base-multinerd"
DEFAULT_EXTRACT_TEMPLATE_STR = """\
Here is the content of the section:
----------------
{context_str}
----------------
Given the contextual information, extract out a {class_name} object.\
"""
| SummaryExtractor |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_utils.py | {
"start": 2918,
"end": 6724
} | class ____:
@pytest.mark.asyncio
async def test_invalid_type(self):
with pytest.raises(TypeError, match="path must be a string"):
await anext(file_tail_iterator(1))
@pytest.mark.asyncio
async def test_file_not_created(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
f.write("hi\n")
f.flush()
assert await anext(it) is not None
@pytest.mark.asyncio
async def test_wait_for_newline(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
f.write("no_newline_yet")
assert await anext(it) is None
f.write("\n")
f.flush()
assert await anext(it) == ["no_newline_yet\n"]
@pytest.mark.asyncio
async def test_multiple_lines(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
num_lines = 10
for i in range(num_lines):
s = f"{i}\n"
f.write(s)
f.flush()
assert await anext(it) == [s]
assert await anext(it) is None
@pytest.mark.asyncio
async def test_batching(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
# Write lines in batches of 10, check that we get them back in batches.
for _ in range(100):
num_lines = 10
for i in range(num_lines):
f.write(f"{i}\n")
f.flush()
assert await anext(it) == [f"{i}\n" for i in range(10)]
assert await anext(it) is None
@pytest.mark.asyncio
async def test_max_line_batching(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
# Write lines in batches of 50, check that we get them back in batches of 10.
for _ in range(100):
num_lines = 50
for i in range(num_lines):
f.write(f"{i}\n")
f.flush()
assert await anext(it) == [f"{i}\n" for i in range(10)]
assert await anext(it) == [f"{i}\n" for i in range(10, 20)]
assert await anext(it) == [f"{i}\n" for i in range(20, 30)]
assert await anext(it) == [f"{i}\n" for i in range(30, 40)]
assert await anext(it) == [f"{i}\n" for i in range(40, 50)]
assert await anext(it) is None
@pytest.mark.asyncio
async def test_max_char_batching(self, tmp):
it = file_tail_iterator(tmp)
assert await anext(it) is None
f = open(tmp, "w")
# Write a single line that is 60k characters
f.write(f"{'1234567890' * 6000}\n")
# Write a 4 lines that are 10k characters each
for _ in range(4):
f.write(f"{'1234567890' * 500}\n")
f.flush()
# First line will come in a batch of its own
assert await anext(it) == [f"{'1234567890' * 6000}\n"]
# Other 4 lines will be batched together
assert (
await anext(it)
== [
f"{'1234567890' * 500}\n",
]
* 4
)
assert await anext(it) is None
@pytest.mark.asyncio
async def test_delete_file(self):
with NamedTemporaryFile() as tmp:
it = file_tail_iterator(tmp.name)
f = open(tmp.name, "w")
assert await anext(it) is None
f.write("hi\n")
f.flush()
assert await anext(it) == ["hi\n"]
# Calls should continue returning None after file deleted.
assert await anext(it) is None
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
| TestIterLine |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format24.py | {
"start": 315,
"end": 1672
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format24.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [115374720, 115389568]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
chart.set_chartarea({"fill": {"color": "yellow", "transparency": 75}})
chart.set_plotarea({"fill": {"color": "red", "transparency": 25}})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 10638,
"end": 11556
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self, name: str, access_token: str, wrike_instance: str, start_date: Optional[str] = None
):
"""Airbyte Source for Wrike.
Args:
name (str): The name of the destination.
access_token (str): Permanent access token. You can find documentation on how to acquire a permanent access token here
wrike_instance (str): Wrike's instance such as `app-us2.wrike.com`
start_date (Optional[str]): UTC date and time in the format 2017-01-25T00:00:00Z. Only comments after this date will be replicated.
"""
self.access_token = check.str_param(access_token, "access_token")
self.wrike_instance = check.str_param(wrike_instance, "wrike_instance")
self.start_date = check.opt_str_param(start_date, "start_date")
super().__init__("Wrike", name)
| WrikeSource |
python | PyCQA__pylint | tests/functional/p/postponed/postponed_evaluation_pep585.py | {
"start": 1594,
"end": 2259
} | class ____:
my_var: list[int]
var1: set[int]
var2: collections.OrderedDict[str, int]
var3: dict[str, list[int]]
var4: Dict[str, list[int]]
var5: dict[tuple[int, int], str]
var6: Dict[tuple[int, int], str]
var7: list[list[int]]
var8: tuple[list[int]]
var9: int | list[str | int]
var10: Union[list[str], None]
var11: Union[Union[list[int], int]]
def func(arg: list[int]):
pass
def func2() -> list[int]:
pass
Alias2 = Union[list[str], None]
Alias3 = Union[Union[list[int], int]]
Alias4 = Tuple[list[int]]
Alias5 = Dict[str, list[int]]
Alias6 = int | list[int]
Alias7 = list[list[int]]
import collections.abc
import contextlib
import re
| CustomDataClass4 |
python | huggingface__transformers | tests/models/donut/test_modeling_donut_swin.py | {
"start": 5829,
"end": 14039
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (DonutSwinModel, DonutSwinForImageClassification) if is_torch_available() else ()
pipeline_model_mapping = (
{"image-feature-extraction": DonutSwinModel, "image-classification": DonutSwinForImageClassification}
if is_torch_available()
else {}
)
test_resize_embeddings = False
def setUp(self):
self.model_tester = DonutSwinModelTester(self)
self.config_tester = ConfigTester(
self,
config_class=DonutSwinConfig,
has_text_modality=False,
embed_dim=37,
common_properties=["image_size", "patch_size", "num_channels"],
)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_for_image_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
@unittest.skip(reason="DonutSwin does not use inputs_embeds")
def test_inputs_embeds(self):
pass
def test_model_get_set_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
def test_attention_outputs(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.return_dict = True
for model_class in self.all_model_classes:
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = False
config.return_dict = True
model = model_class._from_config(config, attn_implementation="eager")
config = model.config
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.attentions
expected_num_attentions = len(self.model_tester.depths)
self.assertEqual(len(attentions), expected_num_attentions)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
config.output_attentions = True
window_size_squared = config.window_size**2
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.attentions
self.assertEqual(len(attentions), expected_num_attentions)
self.assertListEqual(
list(attentions[0].shape[-3:]),
[self.model_tester.num_heads[0], window_size_squared, window_size_squared],
)
out_len = len(outputs)
# Check attention is always last and order is fine
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
if hasattr(self.model_tester, "num_hidden_states_types"):
added_hidden_states = self.model_tester.num_hidden_states_types
else:
# also another +1 for reshaped_hidden_states
added_hidden_states = 2
self.assertEqual(out_len + added_hidden_states, len(outputs))
self_attentions = outputs.attentions
self.assertEqual(len(self_attentions), expected_num_attentions)
self.assertListEqual(
list(self_attentions[0].shape[-3:]),
[self.model_tester.num_heads[0], window_size_squared, window_size_squared],
)
def check_hidden_states_output(self, inputs_dict, config, model_class, image_size):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.hidden_states
expected_num_layers = getattr(
self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1
)
self.assertEqual(len(hidden_states), expected_num_layers)
# DonutSwin has a different seq_length
patch_size = (
config.patch_size
if isinstance(config.patch_size, collections.abc.Iterable)
else (config.patch_size, config.patch_size)
)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.assertListEqual(
list(hidden_states[0].shape[-2:]),
[num_patches, self.model_tester.embed_dim],
)
reshaped_hidden_states = outputs.reshaped_hidden_states
self.assertEqual(len(reshaped_hidden_states), expected_num_layers)
batch_size, num_channels, height, width = reshaped_hidden_states[0].shape
reshaped_hidden_states = (
reshaped_hidden_states[0].view(batch_size, num_channels, height * width).permute(0, 2, 1)
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:]),
[num_patches, self.model_tester.embed_dim],
)
def test_hidden_states_output(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
image_size = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
else (self.model_tester.image_size, self.model_tester.image_size)
)
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
def test_hidden_states_output_with_padding(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.patch_size = 3
image_size = (
self.model_tester.image_size
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
else (self.model_tester.image_size, self.model_tester.image_size)
)
patch_size = (
config.patch_size
if isinstance(config.patch_size, collections.abc.Iterable)
else (config.patch_size, config.patch_size)
)
padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
@slow
def test_model_from_pretrained(self):
model_name = "naver-clova-ix/donut-base"
model = DonutSwinModel.from_pretrained(model_name)
self.assertIsNotNone(model)
| DonutSwinModelTest |
python | gevent__gevent | src/gevent/_tblib.py | {
"start": 3251,
"end": 12808
} | class ____:
"""
Class that wraps builtin Traceback objects.
"""
tb_next = None
def __init__(self, tb):
self.tb_frame = Frame(tb.tb_frame)
# noinspection SpellCheckingInspection
self.tb_lineno = int(tb.tb_lineno)
# Build in place to avoid exceeding the recursion limit
tb = tb.tb_next
prev_traceback = self
cls = type(self)
while tb is not None:
traceback = object.__new__(cls)
traceback.tb_frame = Frame(tb.tb_frame)
traceback.tb_lineno = int(tb.tb_lineno)
prev_traceback.tb_next = traceback
prev_traceback = traceback
tb = tb.tb_next
def as_traceback(self):
"""
Convert to a builtin Traceback object that is usable for raising or rendering a stacktrace.
"""
current = self
top_tb = None
tb = None
while current:
f_code = current.tb_frame.f_code
code = compile('\n' * (current.tb_lineno - 1) + 'raise __traceback_maker', current.tb_frame.f_code.co_filename, 'exec')
if hasattr(code, 'replace'):
# Python 3.8 and newer
code = code.replace(co_argcount=0, co_filename=f_code.co_filename, co_name=f_code.co_name, co_freevars=(), co_cellvars=())
else:
code = CodeType(
0,
code.co_kwonlyargcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co_names,
code.co_varnames,
f_code.co_filename,
f_code.co_name,
code.co_firstlineno,
code.co_lnotab,
(),
(),
)
# noinspection PyBroadException
try:
exec(code, dict(current.tb_frame.f_globals), {}) # noqa: S102
except Exception:
next_tb = sys.exc_info()[2].tb_next
if top_tb is None:
top_tb = next_tb
if tb is not None:
tb.tb_next = next_tb
tb = next_tb
del next_tb
current = current.tb_next
try:
return top_tb
finally:
del top_tb
del tb
to_traceback = as_traceback
def as_dict(self):
"""
Converts to a dictionary representation. You can serialize the result to JSON as it only has
builtin objects like dicts, lists, ints or strings.
"""
if self.tb_next is None:
tb_next = None
else:
tb_next = self.tb_next.to_dict()
code = {
'co_filename': self.tb_frame.f_code.co_filename,
'co_name': self.tb_frame.f_code.co_name,
}
frame = {
'f_globals': self.tb_frame.f_globals,
'f_code': code,
'f_lineno': self.tb_frame.f_lineno,
}
return {
'tb_frame': frame,
'tb_lineno': self.tb_lineno,
'tb_next': tb_next,
}
to_dict = as_dict
@classmethod
def from_dict(cls, dct):
"""
Creates an instance from a dictionary with the same structure as ``.as_dict()`` returns.
"""
if dct['tb_next']:
tb_next = cls.from_dict(dct['tb_next'])
else:
tb_next = None
code = _AttrDict(
co_filename=dct['tb_frame']['f_code']['co_filename'],
co_name=dct['tb_frame']['f_code']['co_name'],
)
frame = _AttrDict(
f_globals=dct['tb_frame']['f_globals'],
f_code=code,
f_lineno=dct['tb_frame']['f_lineno'],
)
tb = _AttrDict(
tb_frame=frame,
tb_lineno=dct['tb_lineno'],
tb_next=tb_next,
)
return cls(tb)
@classmethod
def from_string(cls, string, strict=True):
"""
Creates an instance by parsing a stacktrace. Strict means that parsing stops when lines are not indented by at least two spaces
anymore.
"""
frames = []
header = strict
for line in string.splitlines():
line = line.rstrip()
if header:
if line == 'Traceback (most recent call last):':
header = False
continue
frame_match = FRAME_RE.match(line)
if frame_match:
frames.append(frame_match.groupdict())
elif line.startswith(' '):
pass
elif strict:
break # traceback ended
if frames:
previous = None
for frame in reversed(frames):
previous = _AttrDict(
frame,
tb_frame=_AttrDict(
frame,
f_globals=_AttrDict(
__file__=frame['co_filename'],
__name__='?',
),
f_code=_AttrDict(frame),
f_lineno=int(frame['tb_lineno']),
),
tb_next=previous,
)
return cls(previous)
else:
raise TracebackParseError('Could not find any frames in %r.' % string)
# pickling_support.py
# gevent: Trying the dict support, so maybe we don't even need this
# at all.
import sys
from types import TracebackType
#from . import Frame # gevent
#from . import Traceback # gevent
# gevent: defer
# if sys.version_info.major >= 3:
# import copyreg
# else:
# import copy_reg as copyreg
def unpickle_traceback(tb_frame, tb_lineno, tb_next):
ret = object.__new__(Traceback)
ret.tb_frame = tb_frame
ret.tb_lineno = tb_lineno
ret.tb_next = tb_next
return ret.as_traceback()
def pickle_traceback(tb):
return unpickle_traceback, (Frame(tb.tb_frame), tb.tb_lineno, tb.tb_next and Traceback(tb.tb_next))
def unpickle_exception(func, args, cause, tb):
inst = func(*args)
inst.__cause__ = cause
inst.__traceback__ = tb
return inst
def pickle_exception(obj):
# All exceptions, unlike generic Python objects, define __reduce_ex__
# __reduce_ex__(4) should be no different from __reduce_ex__(3).
# __reduce_ex__(5) could bring benefits in the unlikely case the exception
# directly contains buffers, but PickleBuffer objects will cause a crash when
# running on protocol=4, and there's no clean way to figure out the current
# protocol from here. Note that any object returned by __reduce_ex__(3) will
# still be pickled with protocol 5 if pickle.dump() is running with it.
rv = obj.__reduce_ex__(3)
if isinstance(rv, str):
raise TypeError('str __reduce__ output is not supported')
assert isinstance(rv, tuple)
assert len(rv) >= 2
return (unpickle_exception, rv[:2] + (obj.__cause__, obj.__traceback__)) + rv[2:]
def _get_subclasses(cls):
# Depth-first traversal of all direct and indirect subclasses of cls
to_visit = [cls]
while to_visit:
this = to_visit.pop()
yield this
to_visit += list(this.__subclasses__())
def install(*exc_classes_or_instances):
import copyreg
copyreg.pickle(TracebackType, pickle_traceback)
if sys.version_info.major < 3:
# Dummy decorator?
if len(exc_classes_or_instances) == 1:
exc = exc_classes_or_instances[0]
if isinstance(exc, type) and issubclass(exc, BaseException):
return exc
return
if not exc_classes_or_instances:
for exception_cls in _get_subclasses(BaseException):
copyreg.pickle(exception_cls, pickle_exception)
return
for exc in exc_classes_or_instances:
if isinstance(exc, BaseException):
while exc is not None:
copyreg.pickle(type(exc), pickle_exception)
exc = exc.__cause__
elif isinstance(exc, type) and issubclass(exc, BaseException):
copyreg.pickle(exc, pickle_exception)
# Allow using @install as a decorator for Exception classes
if len(exc_classes_or_instances) == 1:
return exc
else:
raise TypeError('Expected subclasses or instances of BaseException, got %s' % (type(exc)))
# gevent API
_installed = False
# 2025-04-14 On Python 3.14a7, attempting to do *anything* (get its type, print it,...)
# with a traceback object that has been reconstituted from one that tblib pickled will
# crash the interpreter. The current HEAD of upstream _tblib can't pass its tests on 3.14
# and also crashes the interpreter. Our temporary fix is to disable this functionality on
# 3.14. While we're in early testing, limit it to exact versions known to be broken, just
# in case we find that it gets fixed in CPython itself.
_broken_tblib_pickle = sys.version_info == (3, 14, 0, 'alpha', 7)
def dump_traceback(tb):
from pickle import dumps
if tb is None or _broken_tblib_pickle:
return dumps(None)
tb = Traceback(tb)
return dumps(tb.to_dict())
def load_traceback(s):
from pickle import loads
as_dict = loads(s)
if as_dict is None:
return None
tb = Traceback.from_dict(as_dict)
return tb.as_traceback()
| Traceback |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 6883,
"end": 7047
} | class ____(Generic[P, R], Group[P, R]):
"""A group of objects returned in a generative group by query."""
generated: Optional[str]
@dataclass
| GenerativeGroup |
python | streamlit__streamlit | lib/tests/streamlit/web/server/component_request_handler_test.py | {
"start": 1536,
"end": 11675
} | class ____(tornado.testing.AsyncHTTPTestCase):
"""Test /component endpoint."""
def setUp(self) -> None:
config = RuntimeConfig(
script_path="mock/script/path.py",
command_line=None,
component_registry=LocalComponentRegistry(),
media_file_storage=MemoryMediaFileStorage("/mock/media"),
uploaded_file_manager=MemoryUploadedFileManager("/mock/upload"),
)
self.runtime = Runtime(config)
super().setUp()
# declare_component needs a script_run_ctx to be set
add_script_run_ctx(threading.current_thread(), create_mock_script_run_ctx())
def tearDown(self) -> None:
super().tearDown()
Runtime._instance = None
# get_app is called in the super constructor
def get_app(self) -> tornado.web.Application:
return tornado.web.Application(
[
(
"/component/(.*)",
ComponentRequestHandler,
dict(registry=self.runtime.component_registry),
)
]
)
def _request_component(self, path, headers=None):
if headers is None:
headers = {}
return self.fetch(f"/component/{path}", method="GET", headers=headers)
def test_success_request(self):
"""Test request success when valid parameters are provided."""
with mock.patch(MOCK_IS_DIR_PATH):
# We don't need the return value in this case.
declare_component("test", path=PATH)
with mock.patch(
"streamlit.web.server.component_request_handler.open",
mock.mock_open(read_data="Test Content"),
):
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test"
)
assert response.code == 200
assert response.body == b"Test Content"
assert response.headers["Access-Control-Allow-Origin"] == "*"
@mock.patch(
"streamlit.web.server.routes.allow_all_cross_origin_requests",
mock.MagicMock(return_value=False),
)
@patch_config_options({"server.corsAllowedOrigins": ["http://example.com"]})
def test_success_request_allowlisted_origin(self):
"""Test request success when valid parameters are provided with an allowlisted origin."""
with mock.patch(MOCK_IS_DIR_PATH):
# We don't need the return value in this case.
declare_component("test", path=PATH)
with mock.patch(
"streamlit.web.server.component_request_handler.open",
mock.mock_open(read_data="Test Content"),
):
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test",
headers={"Origin": "http://example.com"},
)
assert response.code == 200
assert response.body == b"Test Content"
assert response.headers["Access-Control-Allow-Origin"] == "http://example.com"
def test_outside_component_root_request(self):
"""Tests to ensure a path based on the root directory (and therefore
outside of the component root) is disallowed."""
with mock.patch(MOCK_IS_DIR_PATH):
# We don't need the return value in this case.
declare_component("test", path=PATH)
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test//etc/hosts"
)
assert response.code == 403
assert response.body == b"forbidden"
def test_outside_component_dir_with_same_prefix_request(self):
"""Tests to ensure a path based on the same prefix but a different
directory test folder is forbidden."""
with mock.patch(MOCK_IS_DIR_PATH):
# We don't need the return value in this case.
declare_component("test", path=PATH)
response = self._request_component(
f"tests.streamlit.web.server.component_request_handler_test.test/{PATH}_really"
)
assert response.code == 403
assert response.body == b"forbidden"
def test_relative_outside_component_root_request(self):
"""Tests to ensure a path relative to the component root directory
(and specifically outside of the component root) is disallowed."""
with mock.patch(MOCK_IS_DIR_PATH):
# We don't need the return value in this case.
declare_component("test", path=PATH)
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test/../foo"
)
assert response.code == 403
assert response.body == b"forbidden"
def test_invalid_component_request(self):
"""Test request failure when invalid component name is provided."""
response = self._request_component("invalid_component")
assert response.code == 404
assert response.body == b"not found"
def test_invalid_content_request(self):
"""Test request failure when invalid content (file) is provided."""
with mock.patch(MOCK_IS_DIR_PATH):
declare_component("test", path=PATH)
with mock.patch("streamlit.web.server.component_request_handler.open") as m:
m.side_effect = OSError("Invalid content")
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test"
)
assert response.code == 404
assert response.body == b"read error"
def test_directory_request_results_in_read_error(self) -> None:
"""Requesting a directory (trailing slash) should result in 404 read error."""
with mock.patch(MOCK_IS_DIR_PATH):
declare_component("test", path=PATH)
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test/"
)
assert response.code == 404
assert response.body == b"read error"
def test_missing_file_segment_results_in_read_error(self) -> None:
"""Requesting component without a file should result in 404 read error."""
with mock.patch(MOCK_IS_DIR_PATH):
declare_component("test", path=PATH)
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test"
)
assert response.code == 404
assert response.body == b"read error"
def test_symlink_escape_outside_component_root_forbidden(self) -> None:
"""Symlink inside component directory pointing outside should be forbidden (403)."""
with tempfile.TemporaryDirectory() as tmpdir:
comp_root = Path(tmpdir)
comp_root.mkdir(parents=True, exist_ok=True)
outside_dir = Path(tempfile.mkdtemp())
outside_file = outside_dir / "outside.js"
outside_file.write_text("console.log('outside');")
link_path = comp_root / "link_out.js"
try:
os.symlink(outside_file, link_path)
except (OSError, NotImplementedError):
self.skipTest("Symlinks not supported in this environment")
# Register the component with the real directory
declare_component("symlink", path=str(comp_root))
# Use the fully-qualified component name pattern used in other tests
fq_comp = (
"tests.streamlit.web.server.component_request_handler_test.symlink"
)
response = self._request_component(f"{fq_comp}/link_out.js")
assert response.code == 403
assert response.body == b"forbidden"
def test_support_binary_files_request(self):
"""Test support for binary files reads."""
def _open_read(m, payload):
is_binary = False
args, kwargs = m.call_args
if len(args) > 1 and "b" in args[1]:
is_binary = True
encoding = "utf-8"
if "encoding" in kwargs:
encoding = kwargs["encoding"]
if is_binary:
from io import BytesIO
return BytesIO(payload)
from io import TextIOWrapper
return TextIOWrapper(str(payload, encoding=encoding))
with mock.patch(MOCK_IS_DIR_PATH):
declare_component("test", path=PATH)
payload = b"\x00\x01\x00\x00\x00\x0d\x00\x80" # binary non utf-8 payload
with mock.patch("streamlit.web.server.component_request_handler.open") as m:
m.return_value.__enter__ = lambda _: _open_read(m, payload)
response = self._request_component(
"tests.streamlit.web.server.component_request_handler_test.test"
)
assert response.code == 200
assert response.body == payload
def test_mimetype_is_overridden_by_server(self):
"""Test get_content_type function."""
mimetypes.add_type("custom/html", ".html")
mimetypes.add_type("custom/js", ".js")
mimetypes.add_type("custom/mjs", ".mjs")
mimetypes.add_type("custom/css", ".css")
assert ComponentRequestHandler.get_content_type("test.html") == "custom/html"
assert ComponentRequestHandler.get_content_type("test.js") == "custom/js"
assert ComponentRequestHandler.get_content_type("test.mjs") == "custom/mjs"
assert ComponentRequestHandler.get_content_type("test.css") == "custom/css"
# Have the server reinitialize the mimetypes
Server.initialize_mimetypes()
assert ComponentRequestHandler.get_content_type("test.html") == "text/html"
assert (
ComponentRequestHandler.get_content_type("test.js")
== "application/javascript"
)
assert (
ComponentRequestHandler.get_content_type("test.mjs")
== "application/javascript"
)
assert ComponentRequestHandler.get_content_type("test.css") == "text/css"
| ComponentRequestHandlerTest |
python | astropy__astropy | astropy/modeling/polynomial.py | {
"start": 30885,
"end": 38905
} | class ____(PolynomialModel):
r"""
2D Polynomial model.
Represents a general polynomial of degree n:
.. math::
P(x,y) = c_{00} + c_{10}x + ...+ c_{n0}x^n + c_{01}y + ...+ c_{0n}y^n
+ c_{11}xy + c_{12}xy^2 + ... + c_{1(n-1)}xy^{n-1}+ ... + c_{(n-1)1}x^{n-1}y
For explanation of ``x_domain``, ``y_domain``, ``x_window`` and ``y_window``
see :ref:`Notes regarding usage of domain and window <domain-window-note>`.
Parameters
----------
degree : int
Polynomial degree: largest sum of exponents (:math:`i + j`) of
variables in each monomial term of the form :math:`x^i y^j`. The
number of terms in a 2D polynomial of degree ``n`` is given by binomial
coefficient :math:`C(n + 2, 2) = (n + 2)! / (2!\,n!) = (n + 1)(n + 2) / 2`.
x_domain : tuple or None, optional
domain of the x independent variable
If None, it is set to (-1, 1)
y_domain : tuple or None, optional
domain of the y independent variable
If None, it is set to (-1, 1)
x_window : tuple or None, optional
range of the x independent variable
If None, it is set to (-1, 1)
Fitters will remap the x_domain to x_window
y_window : tuple or None, optional
range of the y independent variable
If None, it is set to (-1, 1)
Fitters will remap the y_domain to y_window
**params : dict
keyword: value pairs, representing parameter_name: value
"""
n_inputs = 2
n_outputs = 1
_separable = False
def __init__(
self,
degree,
x_domain=None,
y_domain=None,
x_window=None,
y_window=None,
n_models=None,
model_set_axis=None,
name=None,
meta=None,
**params,
):
super().__init__(
degree,
n_models=n_models,
model_set_axis=model_set_axis,
name=name,
meta=meta,
**params,
)
self._default_domain_window = {
"x_domain": (-1, 1),
"y_domain": (-1, 1),
"x_window": (-1, 1),
"y_window": (-1, 1),
}
self.x_domain = x_domain or self._default_domain_window["x_domain"]
self.y_domain = y_domain or self._default_domain_window["y_domain"]
self.x_window = x_window or self._default_domain_window["x_window"]
self.y_window = y_window or self._default_domain_window["y_window"]
def prepare_inputs(self, x, y, **kwargs):
inputs, broadcasted_shapes = super().prepare_inputs(x, y, **kwargs)
x, y = inputs
return (x, y), broadcasted_shapes
def evaluate(self, x, y, *coeffs):
if self.x_domain is not None:
x = poly_map_domain(x, self.x_domain, self.x_window)
if self.y_domain is not None:
y = poly_map_domain(y, self.y_domain, self.y_window)
invcoeff = self.invlex_coeff(coeffs)
result = self.multivariate_horner(x, y, invcoeff)
# Special case for degree==0 to ensure that the shape of the output is
# still as expected by the broadcasting rules, even though the x and y
# inputs are not used in the evaluation
if self.degree == 0:
output_shape = np.broadcast_shapes(np.shape(coeffs[0]), x.shape)
if output_shape:
new_result = np.empty(output_shape)
new_result[:] = result
result = new_result
return result
def __repr__(self):
return self._format_repr(
[self.degree],
kwargs={
"x_domain": self.x_domain,
"y_domain": self.y_domain,
"x_window": self.x_window,
"y_window": self.y_window,
},
defaults=self._default_domain_window,
)
def __str__(self):
return self._format_str(
[
("Degree", self.degree),
("X_Domain", self.x_domain),
("Y_Domain", self.y_domain),
("X_Window", self.x_window),
("Y_Window", self.y_window),
],
self._default_domain_window,
)
def fit_deriv(self, x, y, *params):
"""
Computes the Vandermonde matrix.
Parameters
----------
x : ndarray
input
y : ndarray
input
*params
throw-away parameter list returned by non-linear fitters
Returns
-------
result : ndarray
The Vandermonde matrix
"""
if x.ndim == 2:
x = x.ravel()
if y.ndim == 2:
y = y.ravel()
if x.size != y.size:
raise ValueError("Expected x and y to be of equal size")
designx = x[:, None] ** np.arange(self.degree + 1)
designy = y[:, None] ** np.arange(1, self.degree + 1)
designmixed = []
for i in range(1, self.degree):
for j in range(1, self.degree):
if i + j <= self.degree:
designmixed.append((x**i) * (y**j))
designmixed = np.array(designmixed).T
if designmixed.any():
v = np.hstack([designx, designy, designmixed])
else:
v = np.hstack([designx, designy])
return v
def invlex_coeff(self, coeffs):
invlex_coeffs = []
lencoeff = range(self.degree + 1)
for i in lencoeff:
for j in lencoeff:
if i + j <= self.degree:
name = f"c{j}_{i}"
coeff = coeffs[self.param_names.index(name)]
invlex_coeffs.append(coeff)
return invlex_coeffs[::-1]
def multivariate_horner(self, x, y, coeffs):
"""
Multivariate Horner's scheme.
Parameters
----------
x, y : array
coeffs : array
Coefficients in inverse lexical order.
"""
alpha = self._invlex()
r0 = coeffs[0]
r1 = r0 * 0.0
r2 = r0 * 0.0
karr = np.diff(alpha, axis=0)
for n in range(len(karr)):
if karr[n, 1] != 0:
r2 = y * (r0 + r1 + r2)
r1 = np.zeros_like(coeffs[0], subok=False)
else:
r1 = x * (r0 + r1)
r0 = coeffs[n + 1]
return r0 + r1 + r2
@property
def input_units(self):
if self.degree == 0 or (
self.c1_0.input_unit is None and self.c0_1.input_unit is None
):
return None
return {
self.inputs[0]: self.c0_0.input_unit / self.c1_0.input_unit,
self.inputs[1]: self.c0_0.input_unit / self.c0_1.input_unit,
}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
mapping = {}
for i in range(self.degree + 1):
for j in range(self.degree + 1):
if i + j > 2:
continue
par = getattr(self, f"c{i}_{j}")
mapping[par.name] = (
outputs_unit[self.outputs[0]]
/ inputs_unit[self.inputs[0]] ** i
/ inputs_unit[self.inputs[1]] ** j
)
return mapping
@property
def x_domain(self):
return self._x_domain
@x_domain.setter
def x_domain(self, val):
self._x_domain = _validate_domain_window(val)
@property
def y_domain(self):
return self._y_domain
@y_domain.setter
def y_domain(self, val):
self._y_domain = _validate_domain_window(val)
@property
def x_window(self):
return self._x_window
@x_window.setter
def x_window(self, val):
self._x_window = _validate_domain_window(val)
@property
def y_window(self):
return self._y_window
@y_window.setter
def y_window(self, val):
self._y_window = _validate_domain_window(val)
| Polynomial2D |
python | ray-project__ray | python/ray/experimental/channel/common.py | {
"start": 18386,
"end": 21147
} | class ____:
def __init__(
self,
output_channels: List[ChannelInterface],
output_idxs: List[Optional[Union[int, str]]],
is_input=False,
):
"""
Initialize the writer.
Args:
output_channels: The output channels to write to.
output_idxs: The indices of the values to write to each channel.
This has the same length as `output_channels`. If `is_input` is True,
the index can be an integer or a string to retrieve the corresponding
value from `args` or `kwargs` in the DAG's input. If `is_input`
is False, the entire value is written if the index is None. Otherwise,
the value at the specified index in the tuple is written.
is_input: Whether the writer is DAG input writer or not.
"""
assert len(output_channels) == len(output_idxs)
self._output_channels = output_channels
self._output_idxs = output_idxs
self._closed = False
self._num_writes = 0
self._is_input = is_input
def get_num_writes(self) -> int:
return self._num_writes
def start(self):
raise NotImplementedError()
def write(self, val: Any, timeout: Optional[float] = None) -> None:
"""
Write the value.
Args:
timeout: The maximum time in seconds to wait for writing. 0 means
immediate timeout (immediate success or timeout without blocking).
-1 and None mean infinite timeout (blocks indefinitely).
"""
raise NotImplementedError()
def close(self) -> None:
self._closed = True
for channel in self._output_channels:
channel.close()
def _adapt(raw_args: Any, key: Optional[Union[int, str]], is_input: bool):
"""
Adapt the raw arguments to the key. If `is_input` is True, this method will
retrieve the value from the input data for an InputAttributeNode. Otherwise, it
will retrieve either a partial value or the entire value from the output of
a ClassMethodNode.
Args:
raw_args: The raw arguments to adapt.
key: The key to adapt.
is_input: Whether the writer is DAG input writer or not.
"""
if is_input:
if not isinstance(raw_args, CompiledDAGArgs):
# Fast path for a single input.
return raw_args
else:
args = raw_args.args
kwargs = raw_args.kwargs
if isinstance(key, int):
return args[key]
else:
return kwargs[key]
else:
if key is not None:
return raw_args[key]
else:
return raw_args
@DeveloperAPI
| WriterInterface |
python | spyder-ide__spyder | spyder/plugins/editor/api/manager.py | {
"start": 729,
"end": 1509
} | class ____(object):
"""
A manager manages a specific aspect of a CodeEditor instance:
- panels management and drawing
Managers are typically created internally when you create a CodeEditor.
You interact with them later.
::
editor = CodeEditor()
# use the panels controller to install a panel
editor.panels.install(MyPanel(), MyPanel.Position.Right)
my_panel = editor.panels.get(MyPanel)
# and so on
"""
@property
def editor(self):
"""Return a reference to the parent CodeEditor widget."""
return self._editor()
def __init__(self, editor):
""":param editor: CodeEditor instance to control."""
super().__init__()
self._editor = weakref.ref(editor)
| Manager |
python | scikit-learn__scikit-learn | sklearn/externals/_arff.py | {
"start": 11924,
"end": 12097
} | class ____(ArffException):
'''Error raised when some attribute declaration is in an invalid format.'''
message = 'Bad @ATTRIBUTE format, at line %d.'
| BadAttributeFormat |
python | pytorch__pytorch | torch/_dynamo/variables/torch_function.py | {
"start": 7468,
"end": 8367
} | class ____:
def __init__(self) -> None:
self.stack: list[Any] = []
def __enter__(self) -> None:
self.stack = torch.overrides._get_current_function_mode_stack()
clear_torch_function_mode_stack()
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
set_torch_function_mode_stack(self.stack)
self.stack = []
@contextlib.contextmanager
def temp_restore_stack(self) -> Generator[None, None, None]:
prev = torch.overrides._get_current_function_mode_stack()
set_torch_function_mode_stack(self.stack)
try:
yield
finally:
set_torch_function_mode_stack(prev)
torch_function_mode_stack_state_mgr = TorchFunctionModeStackStateManager()
| TorchFunctionModeStackStateManager |
python | openai__openai-python | src/openai/types/beta/threads/runs/tool_calls_step_details.py | {
"start": 255,
"end": 574
} | class ____(BaseModel):
tool_calls: List[ToolCall]
"""An array of tool calls the run step was involved in.
These can be associated with one of three types of tools: `code_interpreter`,
`file_search`, or `function`.
"""
type: Literal["tool_calls"]
"""Always `tool_calls`."""
| ToolCallsStepDetails |
python | realpython__materials | python-isinstance/balls_v2.py | {
"start": 481,
"end": 687
} | class ____(Ball):
def __init__(self, color):
super().__init__(color, shape="prolate spheroid")
def get_state(self):
print(f"Color = {self.color}, Shape = {self.shape}")
| AmericanFootBall |
python | kamyu104__LeetCode-Solutions | Python/maximize-subarray-sum-after-removing-all-occurrences-of-one-element.py | {
"start": 91,
"end": 639
} | class ____(object):
def maxSubarraySum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = float("-inf")
curr = mn = mn0 = 0
mn1 = collections.defaultdict(int)
for x in nums:
curr += x
result = max(result, curr-mn)
mn1[x] = min(mn1[x], mn0)+x
mn0 = min(mn0, curr)
mn = min(mn, mn1[x], mn0)
return result
# Time: O(n)
# Space: O(n)
import collections
# hash table, greedy, kadane's algorithm
| Solution |
python | getsentry__sentry | src/sentry/core/endpoints/team_members.py | {
"start": 2538,
"end": 4179
} | class ____(TeamEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.ENTERPRISE
@extend_schema(
operation_id="List a Team's Members",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.TEAM_ID_OR_SLUG,
CursorQueryParam,
],
responses={
200: inline_sentry_response_serializer(
"ListMemberOnTeamResponse", list[OrganizationMemberOnTeamResponse]
),
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
examples=TeamExamples.LIST_TEAM_MEMBERS,
)
def get(self, request: Request, team) -> Response:
"""
List all members on a team.
The response will not include members with pending invites.
"""
queryset = OrganizationMemberTeam.objects.filter(
Q(organizationmember__user_is_active=True, organizationmember__user_id__isnull=False)
| Q(organizationmember__user_id__isnull=True),
organizationmember__organization=team.organization,
organizationmember__invite_status=InviteStatus.APPROVED.value,
team=team,
)
serializer = DetailedOrganizationMemberTeamSerializer(team=team)
return self.paginate(
request=request,
queryset=queryset,
order_by=(
"organizationmember__email",
"id",
),
paginator_cls=OffsetPaginator,
on_results=lambda x: serialize(x, request.user, serializer=serializer),
)
| TeamMembersEndpoint |
python | pandas-dev__pandas | pandas/tests/frame/test_arithmetic.py | {
"start": 9590,
"end": 16723
} | class ____:
# TODO: test_bool_flex_frame needs a better name
def test_bool_flex_frame(self, comparison_op):
data = np.random.default_rng(2).standard_normal((5, 3))
other_data = np.random.default_rng(2).standard_normal((5, 3))
df = DataFrame(data)
other = DataFrame(other_data)
ndim_5 = np.ones(df.shape + (1, 3))
# DataFrame
assert df.eq(df).values.all()
assert not df.ne(df).values.any()
f = getattr(df, comparison_op.__name__)
o = comparison_op
# No NAs
tm.assert_frame_equal(f(other), o(df, other))
# Unaligned
part_o = other.loc[3:, 1:].copy()
rs = f(part_o)
xp = o(df, part_o.reindex(index=df.index, columns=df.columns))
tm.assert_frame_equal(rs, xp)
# ndarray
tm.assert_frame_equal(f(other.values), o(df, other.values))
# scalar
tm.assert_frame_equal(f(0), o(df, 0))
# NAs
msg = "Unable to coerce to Series/DataFrame"
tm.assert_frame_equal(f(np.nan), o(df, np.nan))
with pytest.raises(ValueError, match=msg):
f(ndim_5)
@pytest.mark.parametrize("box", [np.array, Series])
def test_bool_flex_series(self, box):
# Series
# list/tuple
data = np.random.default_rng(2).standard_normal((5, 3))
df = DataFrame(data)
idx_ser = box(np.random.default_rng(2).standard_normal(5))
col_ser = box(np.random.default_rng(2).standard_normal(3))
idx_eq = df.eq(idx_ser, axis=0)
col_eq = df.eq(col_ser)
idx_ne = df.ne(idx_ser, axis=0)
col_ne = df.ne(col_ser)
tm.assert_frame_equal(col_eq, df == Series(col_ser))
tm.assert_frame_equal(col_eq, -col_ne)
tm.assert_frame_equal(idx_eq, -idx_ne)
tm.assert_frame_equal(idx_eq, df.T.eq(idx_ser).T)
tm.assert_frame_equal(col_eq, df.eq(list(col_ser)))
tm.assert_frame_equal(idx_eq, df.eq(Series(idx_ser), axis=0))
tm.assert_frame_equal(idx_eq, df.eq(list(idx_ser), axis=0))
idx_gt = df.gt(idx_ser, axis=0)
col_gt = df.gt(col_ser)
idx_le = df.le(idx_ser, axis=0)
col_le = df.le(col_ser)
tm.assert_frame_equal(col_gt, df > Series(col_ser))
tm.assert_frame_equal(col_gt, -col_le)
tm.assert_frame_equal(idx_gt, -idx_le)
tm.assert_frame_equal(idx_gt, df.T.gt(idx_ser).T)
idx_ge = df.ge(idx_ser, axis=0)
col_ge = df.ge(col_ser)
idx_lt = df.lt(idx_ser, axis=0)
col_lt = df.lt(col_ser)
tm.assert_frame_equal(col_ge, df >= Series(col_ser))
tm.assert_frame_equal(col_ge, -col_lt)
tm.assert_frame_equal(idx_ge, -idx_lt)
tm.assert_frame_equal(idx_ge, df.T.ge(idx_ser).T)
idx_ser = Series(np.random.default_rng(2).standard_normal(5))
col_ser = Series(np.random.default_rng(2).standard_normal(3))
def test_bool_flex_frame_na(self):
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))
# NA
df.loc[0, 0] = np.nan
rs = df.eq(df)
assert not rs.loc[0, 0]
rs = df.ne(df)
assert rs.loc[0, 0]
rs = df.gt(df)
assert not rs.loc[0, 0]
rs = df.lt(df)
assert not rs.loc[0, 0]
rs = df.ge(df)
assert not rs.loc[0, 0]
rs = df.le(df)
assert not rs.loc[0, 0]
def test_bool_flex_frame_complex_dtype(self):
# complex
arr = np.array([np.nan, 1, 6, np.nan])
arr2 = np.array([2j, np.nan, 7, None])
df = DataFrame({"a": arr})
df2 = DataFrame({"a": arr2})
msg = "|".join(
[
"'>' not supported between instances of '.*' and 'complex'",
r"unorderable types: .*complex\(\)", # PY35
]
)
with pytest.raises(TypeError, match=msg):
# inequalities are not well-defined for complex numbers
df.gt(df2)
with pytest.raises(TypeError, match=msg):
# regression test that we get the same behavior for Series
df["a"].gt(df2["a"])
with pytest.raises(TypeError, match=msg):
# Check that we match numpy behavior here
df.values > df2.values
rs = df.ne(df2)
assert rs.values.all()
arr3 = np.array([2j, np.nan, None])
df3 = DataFrame({"a": arr3})
with pytest.raises(TypeError, match=msg):
# inequalities are not well-defined for complex numbers
df3.gt(2j)
with pytest.raises(TypeError, match=msg):
# regression test that we get the same behavior for Series
df3["a"].gt(2j)
with pytest.raises(TypeError, match=msg):
# Check that we match numpy behavior here
df3.values > 2j
def test_bool_flex_frame_object_dtype(self):
# corner, dtype=object
df1 = DataFrame({"col": ["foo", np.nan, "bar"]}, dtype=object)
df2 = DataFrame({"col": ["foo", datetime.now(), "bar"]}, dtype=object)
result = df1.ne(df2)
exp = DataFrame({"col": [False, True, False]})
tm.assert_frame_equal(result, exp)
def test_flex_comparison_nat(self):
# GH 15697, GH 22163 df.eq(pd.NaT) should behave like df == pd.NaT,
# and _definitely_ not be NaN
df = DataFrame([pd.NaT])
result = df == pd.NaT
# result.iloc[0, 0] is an np.bool_ object
assert result.iloc[0, 0].item() is False
result = df.eq(pd.NaT)
assert result.iloc[0, 0].item() is False
result = df != pd.NaT
assert result.iloc[0, 0].item() is True
result = df.ne(pd.NaT)
assert result.iloc[0, 0].item() is True
def test_df_flex_cmp_constant_return_types(self, comparison_op):
# GH 15077, non-empty DataFrame
df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
const = 2
result = getattr(df, comparison_op.__name__)(const).dtypes.value_counts()
tm.assert_series_equal(
result, Series([2], index=[np.dtype(bool)], name="count")
)
def test_df_flex_cmp_constant_return_types_empty(self, comparison_op):
# GH 15077 empty DataFrame
df = DataFrame({"x": [1, 2, 3], "y": [1.0, 2.0, 3.0]})
const = 2
empty = df.iloc[:0]
result = getattr(empty, comparison_op.__name__)(const).dtypes.value_counts()
tm.assert_series_equal(
result, Series([2], index=[np.dtype(bool)], name="count")
)
def test_df_flex_cmp_ea_dtype_with_ndarray_series(self):
ii = pd.IntervalIndex.from_breaks([1, 2, 3])
df = DataFrame({"A": ii, "B": ii})
ser = Series([0, 0])
res = df.eq(ser, axis=0)
expected = DataFrame({"A": [False, False], "B": [False, False]})
tm.assert_frame_equal(res, expected)
ser2 = Series([1, 2], index=["A", "B"])
res2 = df.eq(ser2, axis=1)
tm.assert_frame_equal(res2, expected)
# -------------------------------------------------------------------
# Arithmetic
| TestFrameFlexComparisons |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 9195,
"end": 14851
} | class ____(nn.Module):
"""Conv1d with asymmetric or causal padding and normalization."""
def __init__(
self,
config,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
dilation: int = 1,
groups: int = 1,
pad_mode: Optional[str] = None,
bias: bool = True,
layer_idx: Optional[int] = None,
):
super().__init__()
self.causal = config.use_causal_conv
self.pad_mode = config.pad_mode if pad_mode is None else pad_mode
self.layer_idx = layer_idx
self.in_channels = in_channels
# warn user on unusual setup between dilation and stride
if stride > 1 and dilation > 1:
logger.warning(
"MimiConv1d has been initialized with stride > 1 and dilation > 1"
f" (kernel_size={kernel_size} stride={stride}, dilation={dilation})."
)
self.conv = nn.Conv1d(
in_channels, out_channels, kernel_size, stride, dilation=dilation, groups=groups, bias=bias
)
kernel_size = self.conv.kernel_size[0]
stride = torch.tensor(self.conv.stride[0], dtype=torch.int64)
dilation = self.conv.dilation[0]
# Effective kernel size with dilations.
kernel_size = torch.tensor((kernel_size - 1) * dilation + 1, dtype=torch.int64)
self.register_buffer("stride", stride, persistent=False)
self.register_buffer("kernel_size", kernel_size, persistent=False)
self.register_buffer("padding_total", kernel_size - stride, persistent=False)
# Asymmetric padding required for odd strides
self.padding_right = self.padding_total // 2
self.padding_left = self.padding_total - self.padding_right
def apply_weight_norm(self):
weight_norm = nn.utils.weight_norm
if hasattr(nn.utils.parametrizations, "weight_norm"):
weight_norm = nn.utils.parametrizations.weight_norm
weight_norm(self.conv)
def remove_weight_norm(self):
nn.utils.remove_weight_norm(self.conv)
# Copied from transformers.models.encodec.modeling_encodec.EncodecConv1d._get_extra_padding_for_conv1d
def _get_extra_padding_for_conv1d(
self,
hidden_states: torch.Tensor,
) -> torch.Tensor:
"""See `pad_for_conv1d`."""
length = hidden_states.shape[-1]
n_frames = (length - self.kernel_size + self.padding_total) / self.stride + 1
n_frames = torch.ceil(n_frames).to(torch.int64) - 1
ideal_length = n_frames * self.stride + self.kernel_size - self.padding_total
return ideal_length - length
@staticmethod
# Copied from transformers.models.encodec.modeling_encodec.EncodecConv1d._pad1d
def _pad1d(hidden_states: torch.Tensor, paddings: tuple[int, int], mode: str = "zero", value: float = 0.0):
"""Tiny wrapper around torch.nn.functional.pad, just to allow for reflect padding on small input.
If this is the case, we insert extra 0 padding to the right before the reflection happens.
"""
length = hidden_states.shape[-1]
padding_left, padding_right = paddings
if mode != "reflect":
return nn.functional.pad(hidden_states, paddings, mode, value)
max_pad = max(padding_left, padding_right)
extra_pad = 0
if length <= max_pad:
extra_pad = max_pad - length + 1
hidden_states = nn.functional.pad(hidden_states, (0, extra_pad))
padded = nn.functional.pad(hidden_states, paddings, mode, value)
end = padded.shape[-1] - extra_pad
return padded[..., :end]
def _get_output_length(self, input_length: torch.LongTensor) -> torch.LongTensor:
"""
Return the length of the output of the MimiConv1d.
"""
# padding size
n_frames = (input_length - self.kernel_size + self.padding_total) / self.stride + 1
n_frames = torch.ceil(n_frames).to(torch.int64) - 1
ideal_length = n_frames * self.stride + self.kernel_size - self.padding_total
extra_padding = ideal_length - input_length
if self.causal:
padding_left = self.padding_total
padding_right = extra_padding
else:
padding_left = self.padding_left
padding_right = self.padding_right + extra_padding
# padding
input_length = input_length + padding_left + padding_right
# conv
output_length = (
input_length + 2 * self.conv.padding[0] - self.conv.dilation[0] * (self.conv.kernel_size[0] - 1) - 1
) // self.conv.stride[0] + 1
return output_length
def forward(self, hidden_states, padding_cache=None):
extra_padding = self._get_extra_padding_for_conv1d(hidden_states)
if not self.causal and padding_cache is not None:
raise ValueError("`padding_cache` is not supported for non-causal convolutions.")
if self.causal and padding_cache is not None:
layer_padding_cache = padding_cache.update(hidden_states, self.layer_idx)
hidden_states = torch.cat([layer_padding_cache, hidden_states], dim=2)
elif self.causal:
# Left padding for causal
hidden_states = self._pad1d(hidden_states, (self.padding_total, extra_padding), mode=self.pad_mode)
else:
hidden_states = self._pad1d(
hidden_states, (self.padding_left, self.padding_right + extra_padding), mode=self.pad_mode
)
hidden_states = self.conv(hidden_states)
return hidden_states
| MimiConv1d |
python | plotly__plotly.py | tests/test_optional/test_figure_factory/test_figure_factory.py | {
"start": 40751,
"end": 51608
} | class ____(NumpyTestUtilsMixin, TestCaseNoTemplate):
def test_vmin_and_vmax(self):
# check if vmin is greater than or equal to vmax
u = np.linspace(0, 2, 2)
v = np.linspace(0, 2, 2)
u, v = np.meshgrid(u, v)
u = u.flatten()
v = v.flatten()
x = u
y = v
z = u * v
points2D = np.vstack([u, v]).T
tri = Delaunay(points2D)
simplices = tri.simplices
pattern = (
"Incorrect relation between vmin and vmax. The vmin value cannot "
"be bigger than or equal to the value of vmax."
)
self.assertRaisesRegex(
PlotlyError, pattern, ff.create_trisurf, x, y, z, simplices
)
def test_valid_colormap(self):
# create data for trisurf plot
u = np.linspace(-np.pi, np.pi, 3)
v = np.linspace(-np.pi, np.pi, 3)
u, v = np.meshgrid(u, v)
u = u.flatten()
v = v.flatten()
x = u
y = u * np.cos(v)
z = u * np.sin(v)
points2D = np.vstack([u, v]).T
tri = Delaunay(points2D)
simplices = tri.simplices
# check that a valid plotly colorscale string is entered
pattern = (
"If your colors variable is a string, it must be a Plotly scale, "
"an rgb color or a hex color."
)
self.assertRaisesRegex(
PlotlyError, pattern, ff.create_trisurf, x, y, z, simplices, colormap="foo"
)
# check: if colormap is a list of rgb color strings, make sure the
# entries of each color are no greater than 255.0
pattern2 = "Whoops! The elements in your rgb colors tuples cannot exceed 255.0."
self.assertRaisesRegex(
PlotlyError,
pattern2,
ff.create_trisurf,
x,
y,
z,
simplices,
colormap=["rgb(4, 5, 600)"],
)
# check: if colormap is a list of tuple colors, make sure the entries
# of each tuple are no greater than 1.0
pattern3 = "Whoops! The elements in your colors tuples cannot exceed 1.0."
self.assertRaisesRegex(
PlotlyError,
pattern3,
ff.create_trisurf,
x,
y,
z,
simplices,
colormap=[(0.8, 1.0, 1.2)],
)
def test_trisurf_all_args(self):
# check if trisurf plot matches with expected output
u = np.linspace(-1, 1, 3)
v = np.linspace(-1, 1, 3)
u, v = np.meshgrid(u, v)
u = u.flatten()
v = v.flatten()
x = u
y = v
z = u * v
points2D = np.vstack([u, v]).T
tri = Delaunay(points2D)
simplices = tri.simplices
test_trisurf_plot = ff.create_trisurf(x, y, z, simplices)
exp_trisurf_plot = {
"data": [
{
"facecolor": [
"rgb(143, 123, 97)",
"rgb(255, 127, 14)",
"rgb(143, 123, 97)",
"rgb(31, 119, 180)",
"rgb(143, 123, 97)",
"rgb(31, 119, 180)",
"rgb(143, 123, 97)",
"rgb(255, 127, 14)",
],
"i": [3, 1, 1, 5, 7, 3, 5, 7],
"j": [1, 3, 5, 1, 3, 7, 7, 5],
"k": [4, 0, 4, 2, 4, 6, 4, 8],
"name": "",
"type": "mesh3d",
"x": [-1.0, 0.0, 1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0],
"y": [-1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
"z": [1.0, -0.0, -1.0, -0.0, 0.0, 0.0, -1.0, 0.0, 1.0],
},
{
"line": {"color": "rgb(50, 50, 50)", "width": 1.5},
"mode": "lines",
"showlegend": False,
"type": "scatter3d",
"x": [
-1.0,
0.0,
0.0,
-1.0,
None,
0.0,
-1.0,
-1.0,
0.0,
None,
0.0,
1.0,
0.0,
0.0,
None,
1.0,
0.0,
1.0,
1.0,
None,
0.0,
-1.0,
0.0,
0.0,
None,
-1.0,
0.0,
-1.0,
-1.0,
None,
1.0,
0.0,
0.0,
1.0,
None,
0.0,
1.0,
1.0,
0.0,
None,
],
"y": [
0.0,
-1.0,
0.0,
0.0,
None,
-1.0,
0.0,
-1.0,
-1.0,
None,
-1.0,
0.0,
0.0,
-1.0,
None,
0.0,
-1.0,
-1.0,
0.0,
None,
1.0,
0.0,
0.0,
1.0,
None,
0.0,
1.0,
1.0,
0.0,
None,
0.0,
1.0,
0.0,
0.0,
None,
1.0,
0.0,
1.0,
1.0,
None,
],
"z": [
-0.0,
-0.0,
0.0,
-0.0,
None,
-0.0,
-0.0,
1.0,
-0.0,
None,
-0.0,
0.0,
0.0,
-0.0,
None,
0.0,
-0.0,
-1.0,
0.0,
None,
0.0,
-0.0,
0.0,
0.0,
None,
-0.0,
0.0,
-1.0,
-0.0,
None,
0.0,
0.0,
0.0,
0.0,
None,
0.0,
0.0,
1.0,
0.0,
None,
],
},
{
"hoverinfo": "none",
"marker": {
"color": [-0.33333333333333331, 0.33333333333333331],
"colorscale": [
[0.0, "rgb(31, 119, 180)"],
[1.0, "rgb(255, 127, 14)"],
],
"showscale": True,
"size": 0.1,
},
"mode": "markers",
"showlegend": False,
"type": "scatter3d",
"x": [-1.0],
"y": [-1.0],
"z": [1.0],
},
],
"layout": {
"height": 800,
"scene": {
"aspectratio": {"x": 1, "y": 1, "z": 1},
"xaxis": {
"backgroundcolor": "rgb(230, 230, 230)",
"gridcolor": "rgb(255, 255, 255)",
"showbackground": True,
"zerolinecolor": "rgb(255, 255, 255)",
},
"yaxis": {
"backgroundcolor": "rgb(230, 230, 230)",
"gridcolor": "rgb(255, 255, 255)",
"showbackground": True,
"zerolinecolor": "rgb(255, 255, 255)",
},
"zaxis": {
"backgroundcolor": "rgb(230, 230, 230)",
"gridcolor": "rgb(255, 255, 255)",
"showbackground": True,
"zerolinecolor": "rgb(255, 255, 255)",
},
},
"title": {"text": "Trisurf Plot"},
"width": 800,
},
}
self.assert_fig_equal(test_trisurf_plot["data"][0], exp_trisurf_plot["data"][0])
self.assert_fig_equal(test_trisurf_plot["data"][1], exp_trisurf_plot["data"][1])
self.assert_fig_equal(test_trisurf_plot["data"][2], exp_trisurf_plot["data"][2])
self.assert_fig_equal(test_trisurf_plot["layout"], exp_trisurf_plot["layout"])
# Test passing custom colors
colors_raw = np.random.randn(simplices.shape[0])
colors_str = [
"rgb(%s, %s, %s)" % (i, j, k)
for i, j, k in np.random.randn(simplices.shape[0], 3)
]
# Color == strings should be kept the same
test_colors_plot = ff.create_trisurf(x, y, z, simplices, color_func=colors_str)
self.assertListEqual(
list(test_colors_plot["data"][0]["facecolor"]), list(colors_str)
)
# Colors must match length of simplices
colors_bad = colors_str[:-1]
self.assertRaises(
ValueError, ff.create_trisurf, x, y, z, simplices, color_func=colors_bad
)
# Check converting custom colors to strings
test_colors_plot = ff.create_trisurf(x, y, z, simplices, color_func=colors_raw)
self.assertTrue(isinstance(test_colors_plot["data"][0]["facecolor"][0], str))
| TestTrisurf |
python | tiangolo__fastapi | docs_src/body_nested_models/tutorial003_py39.py | {
"start": 104,
"end": 409
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": item}
return results
| Item |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/shapes_for_arguments.py | {
"start": 899,
"end": 1730
} | class ____(tf.Module):
# Check that we get shapes annotated on function arguments.
#
# Besides checking the shape on the function input argument, this test also
# checks that the shape on the input argument is propagated to the return
# value.
# We eventually want to move the shape inference to a pass separate from
# the initial import, in which case that aspect of this test doesn't make much
# sense and will be superceded by MLIR->MLIR shape inference tests.
#
# CHECK: func {{@[a-zA-Z_0-9]+}}(%arg0: tensor<f32> {{.*}}) -> (tensor<f32> {{.*}})
# CHECK-SAME: attributes {{.*}} tf_saved_model.exported_names = ["some_function"]
@tf.function(input_signature=[tf.TensorSpec([], tf.float32)])
def some_function(self, x):
return x
if __name__ == '__main__':
common.do_test(TestModule)
| TestModule |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 140342,
"end": 143375
} | class ____(Operation):
def __init__(
self, num=50, endpoint=True, base=10, dtype=None, axis=0, *, name=None
):
super().__init__(name=name)
self.num = num
self.endpoint = endpoint
self.base = base
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
self.axis = axis
def call(self, start, stop):
return backend.numpy.logspace(
start,
stop,
num=self.num,
endpoint=self.endpoint,
base=self.base,
dtype=self.dtype,
axis=self.axis,
)
def compute_output_spec(self, start, stop):
start_shape = getattr(start, "shape", [])
stop_shape = getattr(stop, "shape", [])
output_shape = broadcast_shapes(start_shape, stop_shape)
if self.axis == -1:
output_shape = output_shape + [self.num]
elif self.axis >= 0:
output_shape = (
output_shape[: self.axis]
+ [self.num]
+ output_shape[self.axis :]
)
else:
output_shape = (
output_shape[: self.axis + 1]
+ [self.num]
+ output_shape[self.axis + 1 :]
)
dtype = (
self.dtype
if self.dtype is not None
else backend.standardize_dtype(getattr(start, "dtype", type(start)))
)
dtype = backend.result_type(dtype, float)
return KerasTensor(output_shape, dtype=dtype)
@keras_export(["keras.ops.logspace", "keras.ops.numpy.logspace"])
def logspace(start, stop, num=50, endpoint=True, base=10, dtype=None, axis=0):
"""Returns numbers spaced evenly on a log scale.
In linear space, the sequence starts at `base ** start` and ends with
`base ** stop` (see `endpoint` below).
Args:
start: The starting value of the sequence.
stop: The final value of the sequence, unless `endpoint` is `False`.
In that case, `num + 1` values are spaced over the interval in
log-space, of which all but the last (a sequence of length `num`)
are returned.
num: Number of samples to generate. Defaults to `50`.
endpoint: If `True`, `stop` is the last sample. Otherwise, it is not
included. Defaults to `True`.
base: The base of the log space. Defaults to `10`.
dtype: The type of the output tensor.
axis: The axis in the result to store the samples. Relevant only
if start or stop are array-like.
Note:
Torch backend does not support `axis` argument.
Returns:
A tensor of evenly spaced samples on a log scale.
"""
if any_symbolic_tensors((start, stop)):
return Logspace(num, endpoint, base, dtype, axis)(start, stop)
return backend.numpy.logspace(
start,
stop,
num=num,
endpoint=endpoint,
base=base,
dtype=dtype,
axis=axis,
)
| Logspace |
python | pytest-dev__pytest | src/_pytest/_py/path.py | {
"start": 850,
"end": 3567
} | class ____:
_depend_on_existence = "exists", "link", "dir", "file"
def __init__(self, path):
self.path = path
def dotfile(self):
return self.path.basename.startswith(".")
def ext(self, arg):
if not arg.startswith("."):
arg = "." + arg
return self.path.ext == arg
def basename(self, arg):
return self.path.basename == arg
def basestarts(self, arg):
return self.path.basename.startswith(arg)
def relto(self, arg):
return self.path.relto(arg)
def fnmatch(self, arg):
return self.path.fnmatch(arg)
def endswith(self, arg):
return str(self.path).endswith(arg)
def _evaluate(self, kw):
from .._code.source import getrawcode
for name, value in kw.items():
invert = False
meth = None
try:
meth = getattr(self, name)
except AttributeError:
if name[:3] == "not":
invert = True
try:
meth = getattr(self, name[3:])
except AttributeError:
pass
if meth is None:
raise TypeError(f"no {name!r} checker available for {self.path!r}")
try:
if getrawcode(meth).co_argcount > 1:
if (not meth(value)) ^ invert:
return False
else:
if bool(value) ^ bool(meth()) ^ invert:
return False
except (error.ENOENT, error.ENOTDIR, error.EBUSY):
# EBUSY feels not entirely correct,
# but its kind of necessary since ENOMEDIUM
# is not accessible in python
for name in self._depend_on_existence:
if name in kw:
if kw.get(name):
return False
name = "not" + name
if name in kw:
if not kw.get(name):
return False
return True
_statcache: Stat
def _stat(self) -> Stat:
try:
return self._statcache
except AttributeError:
try:
self._statcache = self.path.stat()
except error.ELOOP:
self._statcache = self.path.lstat()
return self._statcache
def dir(self):
return S_ISDIR(self._stat().mode)
def file(self):
return S_ISREG(self._stat().mode)
def exists(self):
return self._stat()
def link(self):
st = self.path.lstat()
return S_ISLNK(st.mode)
| Checkers |
python | google__python-fire | fire/console/console_attr.py | {
"start": 4139,
"end": 4225
} | class ____(object):
"""Characters used by progress trackers."""
| ProgressTrackerSymbols |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modular_dinov3_vit.py | {
"start": 9528,
"end": 11714
} | class ____(PixtralAttention):
def __init__(self, config: DINOv3ViTConfig):
super().__init__(config)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
"""Input shape: Batch x Time x Channel"""
batch_size, patches, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| DINOv3ViTAttention |
python | sympy__sympy | sympy/polys/polyoptions.py | {
"start": 8660,
"end": 9217
} | class ____(Option, metaclass=OptionType):
"""``sort`` option to polynomial manipulation functions. """
option = 'sort'
requires: list[str] = []
excludes: list[str] = []
@classmethod
def default(cls):
return []
@classmethod
def preprocess(cls, sort):
if isinstance(sort, str):
return [ gen.strip() for gen in sort.split('>') ]
elif hasattr(sort, '__getitem__'):
return list(map(str, sort))
else:
raise OptionError("invalid argument for 'sort' option")
| Sort |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/cloudsql/main.py | {
"start": 2060,
"end": 2568
} | class ____(webapp2.RequestHandler):
def get(self):
"""Simple request handler that shows all of the MySQL variables."""
self.response.headers["Content-Type"] = "text/plain"
db = connect_to_cloudsql()
cursor = db.cursor()
cursor.execute("SHOW VARIABLES")
for r in cursor.fetchall():
self.response.write("{}\n".format(r))
app = webapp2.WSGIApplication(
[
("/", MainPage),
],
debug=True,
)
# [END gae_python_mysql_app]
| MainPage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/unit_tests/test_limit_reducing_error_handler.py | {
"start": 3868,
"end": 6509
} | class ____:
def test_order_refunds_stream_500_error_handling(self, requests_mock):
# Mock the events endpoint to prevent NoMockAddress error
requests_mock.get(
"https://test-shop.myshopify.com/admin/api/2025-01/events.json?filter=Order&verb=destroy",
[{"status_code": 200, "json": {"events": []}}],
)
# Simulate initial URL with 500 error, then success with pagination
requests_mock.get(
"https://test-shop.myshopify.com/admin/api/2025-01/orders.json?limit=250&status=any",
[
{"status_code": 500}, # Initial request fails
{
"status_code": 200,
"json": ORDERS_WITH_REFUNDS_PAGE_1,
"headers": {
"Link": '<https://test-shop.myshopify.com/admin/api/2025-01/orders.json?limit=250&page_info=page1>; rel="next"'
},
},
],
)
# Response for reduced limit
requests_mock.get(
"https://test-shop.myshopify.com/admin/api/2025-01/orders.json?limit=125&status=any",
[
{
"status_code": 200,
"json": ORDERS_WITH_REFUNDS_PAGE_1,
"headers": {
"Link": '<https://test-shop.myshopify.com/admin/api/2025-01/orders.json?limit=125&page_info=page1>; rel="next"'
},
}
],
)
# Paginated response
requests_mock.get(
"https://test-shop.myshopify.com/admin/api/2025-01/orders.json?limit=250&page_info=page1",
[{"status_code": 200, "json": ORDERS_WITH_REFUNDS_PAGE_2, "headers": {}}], # No next page
)
# Configure the stream
config = {"shop": "test-shop", "authenticator": None}
parent_stream = Orders(config)
stream = OrderRefunds(config)
# Read records
records = []
for slice_ in stream.stream_slices(sync_mode="full_refresh"):
records.extend(list(stream.read_records(sync_mode="full_refresh", stream_slice=slice_)))
# Assertions
assert len(records) == 250 # Total refunds: 125 + 125
assert records[0]["id"] == 10 # First refund ID
assert records[-1]["id"] == 2500 # Last refund ID
# Assert that a request with the reduced limit was actually made
assert any(
"limit=125" in req.url for req in requests_mock.request_history
), "No request was made with the reduced limit (limit=125)"
| TestOrderRefundsLimitReducingErrorHandler |
python | eventlet__eventlet | eventlet/semaphore.py | {
"start": 64,
"end": 6086
} | class ____:
"""An unbounded semaphore.
Optionally initialize with a resource *count*, then :meth:`acquire` and
:meth:`release` resources as needed. Attempting to :meth:`acquire` when
*count* is zero suspends the calling greenthread until *count* becomes
nonzero again.
This is API-compatible with :class:`threading.Semaphore`.
It is a context manager, and thus can be used in a with block::
sem = Semaphore(2)
with sem:
do_some_stuff()
If not specified, *value* defaults to 1.
It is possible to limit acquire time::
sem = Semaphore()
ok = sem.acquire(timeout=0.1)
# True if acquired, False if timed out.
"""
def __init__(self, value=1):
try:
value = int(value)
except ValueError as e:
msg = 'Semaphore() expect value :: int, actual: {} {}'.format(type(value), str(e))
raise TypeError(msg)
if value < 0:
msg = 'Semaphore() expect value >= 0, actual: {}'.format(repr(value))
raise ValueError(msg)
self.counter = value
self._waiters = collections.deque()
def __repr__(self):
params = (self.__class__.__name__, hex(id(self)),
self.counter, len(self._waiters))
return '<%s at %s c=%s _w[%s]>' % params
def __str__(self):
params = (self.__class__.__name__, self.counter, len(self._waiters))
return '<%s c=%s _w[%s]>' % params
def locked(self):
"""Returns true if a call to acquire would block.
"""
return self.counter <= 0
def bounded(self):
"""Returns False; for consistency with
:class:`~eventlet.semaphore.CappedSemaphore`.
"""
return False
def acquire(self, blocking=True, timeout=None):
"""Acquire a semaphore.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.
Timeout value must be strictly positive.
"""
if timeout == -1:
timeout = None
if timeout is not None and timeout < 0:
raise ValueError("timeout value must be strictly positive")
if not blocking:
if timeout is not None:
raise ValueError("can't specify timeout for non-blocking acquire")
timeout = 0
if not blocking and self.locked():
return False
current_thread = eventlet.getcurrent()
if self.counter <= 0 or self._waiters:
if current_thread not in self._waiters:
self._waiters.append(current_thread)
try:
if timeout is not None:
ok = False
with eventlet.Timeout(timeout, False):
while self.counter <= 0:
hubs.get_hub().switch()
ok = True
if not ok:
return False
else:
# If someone else is already in this wait loop, give them
# a chance to get out.
while True:
hubs.get_hub().switch()
if self.counter > 0:
break
finally:
try:
self._waiters.remove(current_thread)
except ValueError:
# Fine if its already been dropped.
pass
self.counter -= 1
return True
def __enter__(self):
self.acquire()
def release(self, blocking=True):
"""Release a semaphore, incrementing the internal counter by one. When
it was zero on entry and another thread is waiting for it to become
larger than zero again, wake up that thread.
The *blocking* argument is for consistency with CappedSemaphore and is
ignored
"""
self.counter += 1
if self._waiters:
hubs.get_hub().schedule_call_global(0, self._do_acquire)
return True
def _do_acquire(self):
if self._waiters and self.counter > 0:
waiter = self._waiters.popleft()
waiter.switch()
def __exit__(self, typ, val, tb):
self.release()
@property
def balance(self):
"""An integer value that represents how many new calls to
:meth:`acquire` or :meth:`release` would be needed to get the counter to
0. If it is positive, then its value is the number of acquires that can
happen before the next acquire would block. If it is negative, it is
the negative of the number of releases that would be required in order
to make the counter 0 again (one more release would push the counter to
1 and unblock acquirers). It takes into account how many greenthreads
are currently blocking in :meth:`acquire`.
"""
# positive means there are free items
# zero means there are no free items but nobody has requested one
# negative means there are requests for items, but no items
return self.counter - len(self._waiters)
| Semaphore |
python | pytorch__pytorch | benchmarks/inductor_backends/cutlass.py | {
"start": 3409,
"end": 3927
} | class ____:
op_name: str
shape: tuple[int, int, int]
dtype: torch.dtype
batch_size: int
experiments: list[ExperimentConfig] = field(default_factory=list)
def name(self) -> str:
M, N, K = self.shape
B = self.batch_size
sizes = (
f"(BS: {B}, {M}x{K}, {K}x{N})"
if self.op_name == "bmm"
else f"({M}x{K}, {K}x{N})"
)
return f"{self.op_name} {sizes} {self.dtype}"
@dataclass(frozen=True, kw_only=True)
| ExperimentGroupConfig |
python | huggingface__transformers | src/transformers/models/longformer/modeling_longformer.py | {
"start": 1370,
"end": 3947
} | class ____(ModelOutput):
r"""
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
attention_window + 1)`, where `x` is the number of tokens with global attention mask.
Local attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token in the sequence to every token with
global attention (first `x` values) and to every token in the attention window (remaining `attention_window
+ 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
(succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
If the attention window contains a token with global attention, the attention weight at the corresponding
index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
accessed from `global_attentions`.
global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
last_hidden_state: torch.FloatTensor
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
global_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for Longformer's outputs that also contains a pooling of the last hidden states.
"""
)
| LongformerBaseModelOutput |
python | ipython__ipython | IPython/utils/process.py | {
"start": 688,
"end": 1990
} | class ____(Exception):
pass
def find_cmd(cmd):
"""Find absolute path to executable cmd in a cross platform manner.
This function tries to determine the full path to a command line program
using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
time it will use the version that is first on the users `PATH`.
Warning, don't use this to find IPython command line programs as there
is a risk you will find the wrong one. Instead find those using the
following code and looking for the application itself::
import sys
argv = [sys.executable, '-m', 'IPython']
Parameters
----------
cmd : str
The command line program to look for.
"""
path = shutil.which(cmd)
if path is None:
raise FindCmdError('command could not be found: %s' % cmd)
return path
def abbrev_cwd():
""" Return abbreviated version of cwd, e.g. d:mydir """
cwd = os.getcwd().replace('\\','/')
drivepart = ''
tail = cwd
if sys.platform == 'win32':
if len(cwd) < 4:
return cwd
drivepart,tail = os.path.splitdrive(cwd)
parts = tail.split('/')
if len(parts) > 2:
tail = '/'.join(parts[-2:])
return (drivepart + (
cwd == '/' and '/' or tail))
| FindCmdError |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_coding_agents.py | {
"start": 866,
"end": 1403
} | class ____(CodingAgentIntegrationProvider):
"""Mock coding agent provider for tests."""
key = "mock_agent"
name = "Mock Agent"
def get_agent_name(self) -> str:
return "Mock Agent"
def get_agent_key(self) -> str:
return "mock_agent"
def get_pipeline_views(self):
return []
def build_integration(self, state):
return {
"external_id": "mock_agent",
"name": "Mock Agent",
"metadata": {"api_key": "test_key"},
}
| MockCodingAgentProvider |
python | apache__airflow | providers/alibaba/tests/unit/alibaba/cloud/operators/test_oss.py | {
"start": 1868,
"end": 2396
} | class ____:
@mock.patch("airflow.providers.alibaba.cloud.operators.oss.OSSHook")
def test_execute(self, mock_hook):
operator = OSSDeleteBucketOperator(
task_id=MOCK_TASK_ID, region=MOCK_REGION, bucket_name=MOCK_BUCKET, oss_conn_id=MOCK_OSS_CONN_ID
)
operator.execute(None)
mock_hook.assert_called_once_with(oss_conn_id=MOCK_OSS_CONN_ID, region=MOCK_REGION)
mock_hook.return_value.delete_bucket.assert_called_once_with(bucket_name=MOCK_BUCKET)
| TestOSSDeleteBucketOperator |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/clipboard/base.py | {
"start": 1768,
"end": 2515
} | class ____(Clipboard):
"""
Clipboard class that can dynamically returns any Clipboard.
:param get_clipboard: Callable that returns a :class:`.Clipboard` instance.
"""
def __init__(self, get_clipboard: Callable[[], Clipboard | None]) -> None:
self.get_clipboard = get_clipboard
def _clipboard(self) -> Clipboard:
return self.get_clipboard() or DummyClipboard()
def set_data(self, data: ClipboardData) -> None:
self._clipboard().set_data(data)
def set_text(self, text: str) -> None:
self._clipboard().set_text(text)
def rotate(self) -> None:
self._clipboard().rotate()
def get_data(self) -> ClipboardData:
return self._clipboard().get_data()
| DynamicClipboard |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/hubspot/tests.py | {
"start": 242,
"end": 1164
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = HubspotProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"token": "CNye4dqFMBICAAEYhOKlDZZ_z6IVKI_xMjIUgmFsNQzgBjNE9YBmhAhNOtfN0ak6BAAAAEFCFIIwn2EVRLpvJI9hP4tbIeKHw7ZXSgNldTFSAFoA",
"user": "m@acme.com",
"hub_domain": "acme.com",
"scopes": ["oauth"],
"scope_to_scope_group_pks": [25, 31],
"trial_scopes": [],
"trial_scope_to_scope_group_pks": [],
"hub_id": 211580,
"app_id": 833572,
"expires_in": 1799,
"user_id": 42607123,
"token_type": "access"
}""",
)
def get_expected_to_str(self):
return "m@acme.com"
| HubspotTests |
python | pydata__xarray | xarray/ufuncs.py | {
"start": 1974,
"end": 2244
} | class ____(_ufunc_wrapper):
"""Wrapper for dispatching unary ufuncs."""
def __call__(self, x, /, **kwargs):
xp = get_array_namespace(x)
func = getattr(xp, self.__name__)
return xr.apply_ufunc(func, x, dask="allowed", **kwargs)
| _unary_ufunc |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/utils.py | {
"start": 14368,
"end": 16224
} | class ____(HttpStatusErrorHandler):
"""
Error handler that halves the page size (limit) on each 500 error, down to 1.
No stream instance required; operates directly on the request URL.
"""
def __init__(self, max_retries: int, error_mapping: dict):
super().__init__(logger=None, max_retries=max_retries, error_mapping=error_mapping)
def interpret_response(self, response_or_exception: Optional[Union[requests.Response, Exception]] = None) -> ErrorResolution:
if isinstance(response_or_exception, requests.Response):
response = response_or_exception
if response.status_code == 500:
# Extract current limit from the URL, default to 250 if not present
parsed = urlparse(response.request.url)
query = parse_qs(parsed.query)
current_limit = int(query.get("limit", ["250"])[0])
if current_limit > 1:
new_limit = max(1, current_limit // 2)
query["limit"] = [str(new_limit)]
new_query = urlencode(query, doseq=True)
response.request.url = urlunparse(parsed._replace(query=new_query))
return ErrorResolution(
response_action=ResponseAction.RETRY,
failure_type=FailureType.transient_error,
error_message=f"Server error 500: Reduced limit to {new_limit} and updating request URL",
)
return ErrorResolution(
response_action=ResponseAction.FAIL,
failure_type=FailureType.transient_error,
error_message="Persistent 500 error after reducing limit to 1",
)
return super().interpret_response(response_or_exception)
| LimitReducingErrorHandler |
python | spyder-ide__spyder | spyder/api/utils.py | {
"start": 1970,
"end": 2453
} | class ____:
"""
Dummy class to mark abstract attributes.
"""
pass
def abstract_attribute(
obj: typing.Optional[
typing.Union[typing.Callable[_P, _T], DummyAttribute]
] = None
) -> _T:
"""
Decorator to mark abstract attributes. Must be used in conjunction with the
ABCMeta metaclass.
"""
if obj is None:
obj = DummyAttribute()
setattr(obj, "__is_abstract_attribute__", True)
return obj # type: ignore
| DummyAttribute |
python | getsentry__sentry | src/sentry/core/endpoints/scim/teams.py | {
"start": 9835,
"end": 19361
} | class ____(SCIMEndpoint, TeamDetailsEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.EXPERIMENTAL,
"PATCH": ApiPublishStatus.PUBLIC,
}
permission_classes = (OrganizationSCIMTeamPermission,)
_allow_idp_changes = True
def convert_args(
self, request: Request, organization_id_or_slug: int | str, team_id_or_slug, *args, **kwargs
):
args, kwargs = super().convert_args(request, organization_id_or_slug)
try:
kwargs["team"] = self._get_team(kwargs["organization"], team_id_or_slug)
except Team.DoesNotExist:
raise ResourceDoesNotExist(detail=SCIM_404_GROUP_RES)
return (args, kwargs)
def _get_team(self, organization, team_id_or_slug):
team = (
Team.objects.filter(organization=organization, slug__id_or_slug=team_id_or_slug)
.select_related("organization")
.get()
)
if team.status != TeamStatus.ACTIVE:
raise Team.DoesNotExist
return team
@extend_schema(
operation_id="Query an Individual Team",
parameters=[GlobalParams.TEAM_ID_OR_SLUG, GlobalParams.ORG_ID_OR_SLUG],
request=None,
responses={
200: TeamSCIMSerializer,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
examples=SCIMExamples.QUERY_INDIVIDUAL_TEAM,
)
def get(self, request: Request, organization: Organization, team: Team) -> Response: # type: ignore[override] # convert_args changed shape from baseclass
"""
Query an individual team with a SCIM Group GET Request.
- Note that the members field will only contain up to 10000 members.
"""
query_params = self.get_query_parameters(request)
context = serialize(
team,
serializer=TeamSCIMSerializer(expand=_team_expand(query_params["excluded_attributes"])),
)
return Response(context)
def _add_members_operation(self, request: Request, operation, team):
for member in operation["value"]:
member = OrganizationMember.objects.get(
organization=team.organization, id=member["value"]
)
if OrganizationMemberTeam.objects.filter(team=team, organizationmember=member).exists():
# if a member already belongs to a team, do nothing
continue
with transaction.atomic(router.db_for_write(OrganizationMemberTeam)):
omt = OrganizationMemberTeam.objects.create(team=team, organizationmember=member)
self.create_audit_entry(
request=request,
organization=team.organization,
target_object=omt.id,
target_user_id=member.user_id,
event=audit_log.get_event_id("MEMBER_JOIN_TEAM"),
data=omt.get_audit_log_data(),
)
def _remove_members_operation(self, request: Request, member_id, team):
member = OrganizationMember.objects.get(organization=team.organization, id=member_id)
with transaction.atomic(router.db_for_write(OrganizationMemberTeam)):
try:
omt = OrganizationMemberTeam.objects.get(team=team, organizationmember=member)
except OrganizationMemberTeam.DoesNotExist:
return
self.create_audit_entry(
request=request,
organization=team.organization,
target_object=omt.id,
target_user_id=member.user_id,
event=audit_log.get_event_id("MEMBER_LEAVE_TEAM"),
data=omt.get_audit_log_data(),
)
omt.delete()
def _rename_team_operation(self, request: Request, new_name, team):
serializer = TeamSerializer(
team,
data={"name": new_name, "slug": slugify(new_name)},
partial=True,
)
if not serializer.is_valid():
raise serializers.ValidationError(serializer.errors)
team = serializer.save()
self.create_audit_entry(
request=request,
organization=team.organization,
target_object=team.id,
event=audit_log.get_event_id("TEAM_EDIT"),
data=team.get_audit_log_data(),
)
@extend_schema(
operation_id="Update a Team's Attributes",
parameters=[GlobalParams.ORG_ID_OR_SLUG, GlobalParams.TEAM_ID_OR_SLUG],
request=SCIMTeamPatchRequestSerializer,
responses={
204: RESPONSE_SUCCESS,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def patch(self, request: Request, organization, team):
"""
Update a team's attributes with a SCIM Group PATCH Request.
"""
serializer = SCIMTeamPatchRequestSerializer(data=request.data)
if not serializer.is_valid():
raise SCIMApiError(detail=json.dumps(serializer.errors))
operations = request.data.get("Operations", [])
if len(operations) > 100:
return Response(SCIM_400_TOO_MANY_PATCH_OPS_ERROR, status=400)
try:
with transaction.atomic(router.db_for_write(OrganizationMemberTeam)):
team.idp_provisioned = True
team.save()
for operation in operations:
op = operation["op"].lower()
if op == TeamPatchOps.ADD and operation["path"] == "members":
self._add_members_operation(request, operation, team)
elif op == TeamPatchOps.REMOVE and "members" in operation["path"]:
self._remove_members_operation(
request, self._get_member_id_for_remove_op(operation), team
)
elif op == TeamPatchOps.REPLACE:
path = operation.get("path")
if path == "members":
# delete all the current team members
# and replace with the ones in the operation list
with transaction.atomic(router.db_for_write(OrganizationMember)):
existing = list(
OrganizationMemberTeam.objects.filter(team_id=team.id)
)
OrganizationMemberTeam.objects.bulk_delete(existing)
self._add_members_operation(request, operation, team)
# azure and okta handle team name change operation differently
elif path is None:
# for okta
self._rename_team_operation(
request, operation["value"]["displayName"], team
)
elif path == "displayName":
# for azure
self._rename_team_operation(request, operation["value"], team)
else:
return Response(SCIM_400_UNSUPPORTED_ATTRIBUTE, status=400)
except OrganizationMember.DoesNotExist:
raise ResourceDoesNotExist(detail=SCIM_404_USER_RES)
except IntegrityError as e:
sentry_sdk.capture_exception(e)
return Response(SCIM_400_INTEGRITY_ERROR, status=400)
metrics.incr("sentry.scim.team.update", tags={"organization": organization})
return self.respond(status=204)
@extend_schema(
operation_id="Delete an Individual Team",
parameters=[GlobalParams.ORG_ID_OR_SLUG, GlobalParams.TEAM_ID_OR_SLUG],
responses={
204: RESPONSE_SUCCESS,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def delete(self, request: Request, organization: Organization, team: Team) -> HttpResponseBase: # type: ignore[override] # convert_args changed shape from baseclass
"""
Delete a team with a SCIM Group DELETE Request.
"""
metrics.incr("sentry.scim.team.delete")
return super().delete(request, team)
def put(self, request: Request, organization: Organization, team: Team) -> Response: # type: ignore[override] # convert_args changed shape from baseclass
# override parent's put since we don't have puts
# in SCIM Team routes
return self.http_method_not_allowed(request)
def _get_member_id_for_remove_op(self, operation):
if "value" in operation:
# azure sends member ids in this format under the key 'value'
return operation["value"][0]["value"]
try:
# grab the filter out of the brackets of the string that looks
# like so: members[value eq "123124"]
regex_search = re.search(r"\[(.*?)\]", operation["path"])
if regex_search is None:
raise SCIMFilterError
filter_path = regex_search.groups()[0]
return parse_filter_conditions(filter_path)
except SCIMFilterError:
raise ParseError(detail=SCIM_400_INVALID_FILTER)
| OrganizationSCIMTeamDetails |
python | numpy__numpy | numpy/_core/tests/_locales.py | {
"start": 1042,
"end": 2176
} | class ____:
"""Sets LC_NUMERIC to a locale with comma as decimal point.
Classes derived from this class have setup and teardown methods that run
tests with locale.LC_NUMERIC set to a locale where commas (',') are used as
the decimal point instead of periods ('.'). On exit the locale is restored
to the initial locale. It also serves as context manager with the same
effect. If no such locale is available, the test is skipped.
"""
(cur_locale, tst_locale) = find_comma_decimal_point_locale()
def setup_method(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
def teardown_method(self):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
def __enter__(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
def __exit__(self, type, value, traceback):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
| CommaDecimalPointLocale |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_user_members.py | {
"start": 327,
"end": 499
} | class ____(GQLResult):
members: List[UserRegistryMemberFragment]
RegistryUserMembers.model_rebuild()
RegistryUserMembersProject.model_rebuild()
| RegistryUserMembersProject |
python | doocs__leetcode | solution/0500-0599/0535.Encode and Decode TinyURL/Solution.py | {
"start": 0,
"end": 614
} | class ____:
def __init__(self):
self.m = defaultdict()
self.idx = 0
self.domain = 'https://tinyurl.com/'
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
self.idx += 1
self.m[str(self.idx)] = longUrl
return f'{self.domain}{self.idx}'
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
idx = shortUrl.split('/')[-1]
return self.m[idx]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
| Codec |
python | python-poetry__poetry | src/poetry/installation/operations/install.py | {
"start": 208,
"end": 906
} | class ____(Operation):
def __init__(
self, package: Package, reason: str | None = None, priority: int = 0
) -> None:
super().__init__(reason, priority=priority)
self._package = package
@property
def package(self) -> Package:
return self._package
@property
def job_type(self) -> str:
return "install"
def __str__(self) -> str:
return (
"Installing"
f" {self.package.pretty_name} ({self.format_version(self.package)})"
)
def __repr__(self) -> str:
return (
"<Install"
f" {self.package.pretty_name} ({self.format_version(self.package)})>"
)
| Install |
python | pytorch__pytorch | torch/backends/quantized/__init__.py | {
"start": 1333,
"end": 1861
} | class ____(types.ModuleType):
def __init__(self, m, name):
super().__init__(name)
self.m = m
def __getattr__(self, attr):
return self.m.__getattribute__(attr)
engine = _QEngineProp()
supported_engines = _SupportedQEnginesProp()
# This is the sys.modules replacement trick, see
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
sys.modules[__name__] = QuantizedEngine(sys.modules[__name__], __name__)
engine: str
supported_engines: list[str]
| QuantizedEngine |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/asm.py | {
"start": 1996,
"end": 2090
} | class ____(stlink_task):
pass
def configure(conf):
conf.env.ASMPATH_ST = '-I%s'
| asmstlib |
python | astropy__astropy | astropy/io/ascii/rst.py | {
"start": 261,
"end": 622
} | class ____(FixedWidthHeader):
position_line = 0
start_line = 1
splitter_class = DefaultSplitter
position_char = "="
def get_fixedwidth_params(self, line):
vals, starts, ends = super().get_fixedwidth_params(line)
# The right hand column can be unbounded
ends[-1] = None
return vals, starts, ends
| SimpleRSTHeader |
python | google__pytype | pytype/pyi/parser_test.py | {
"start": 85799,
"end": 86956
} | class ____(parser_test_base.ParserTestBase):
def test_from_typing(self):
self.check(
"""
from typing import Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
class X: ...
def f(x: Callable[Concatenate[X, P], R]) -> Callable[P, R]: ...
""",
"""
from typing import Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
class X: ...
def f(x: Callable[Concatenate[X, P], R]) -> Callable[P, R]: ...
""",
)
def test_from_typing_extensions(self):
self.check(
"""
from typing import Callable, TypeVar
from typing_extensions import Concatenate, ParamSpec
P = ParamSpec('P')
R = TypeVar('R')
class X: ...
def f(x: Callable[Concatenate[X, P], R]) -> Callable[P, R]: ...
""",
"""
from typing import Callable, TypeVar
from typing_extensions import Concatenate, ParamSpec
P = ParamSpec('P')
R = TypeVar('R')
class X: ...
def f(x: Callable[Concatenate[X, P], R]) -> Callable[P, R]: ...
""",
)
| ConcatenateTest |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 75860,
"end": 76633
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
# Reformer is using Rev Nets, thus last layer outputs are concatenated and
# Layer Norm is done over 2 * hidden_size
self.seq_len_dim = 1
self.chunk_size_lm_head = config.chunk_size_lm_head
self.decoder = nn.Linear(2 * config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
def forward_chunk(self, hidden_states):
hidden_states = self.decoder(hidden_states)
return hidden_states
@auto_docstring
| ReformerOnlyLMHead |
python | fastapi__sqlmodel | docs_src/tutorial/connect/select/tutorial004_py310.py | {
"start": 222,
"end": 2149
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
with Session(engine) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar")
session.add(team_preventers)
session.add(team_z_force)
session.commit()
hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team_id=team_z_force.id
)
hero_rusty_man = Hero(
name="Rusty-Man",
secret_name="Tommy Sharp",
age=48,
team_id=team_preventers.id,
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_deadpond)
session.refresh(hero_rusty_man)
session.refresh(hero_spider_boy)
print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)
def select_heroes():
with Session(engine) as session:
statement = select(Hero).join(Team).where(Team.name == "Preventers")
results = session.exec(statement)
for hero in results:
print("Preventer Hero:", hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | django__django | tests/fixtures/models.py | {
"start": 1974,
"end": 2242
} | class ____(models.Model):
objects = PersonManager()
name = models.CharField(max_length=100, unique=True)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
def natural_key(self):
return (self.name,)
| Person |
python | mwaskom__seaborn | tests/_core/test_scales.py | {
"start": 22153,
"end": 25654
} | class ____:
@pytest.fixture
def x(self):
return pd.Series([True, False, False, True], name="x", dtype=bool)
def test_coordinate(self, x):
s = Boolean()._setup(x, Coordinate())
assert_array_equal(s(x), x.astype(float))
def test_coordinate_axis(self, x):
ax = mpl.figure.Figure().subplots()
s = Boolean()._setup(x, Coordinate(), ax.xaxis)
assert_array_equal(s(x), x.astype(float))
f = ax.xaxis.get_major_formatter()
assert f.format_ticks([0, 1]) == ["False", "True"]
@pytest.mark.parametrize(
"dtype,value",
[
(object, np.nan),
(object, None),
("boolean", pd.NA),
]
)
def test_coordinate_missing(self, x, dtype, value):
x = x.astype(dtype)
x[2] = value
s = Boolean()._setup(x, Coordinate())
assert_array_equal(s(x), x.astype(float))
def test_color_defaults(self, x):
s = Boolean()._setup(x, Color())
cs = color_palette()
expected = [cs[int(x_i)] for x_i in ~x]
assert_array_equal(s(x), expected)
def test_color_list_palette(self, x):
cs = color_palette("crest", 2)
s = Boolean(cs)._setup(x, Color())
expected = [cs[int(x_i)] for x_i in ~x]
assert_array_equal(s(x), expected)
def test_color_tuple_palette(self, x):
cs = tuple(color_palette("crest", 2))
s = Boolean(cs)._setup(x, Color())
expected = [cs[int(x_i)] for x_i in ~x]
assert_array_equal(s(x), expected)
def test_color_dict_palette(self, x):
cs = color_palette("crest", 2)
pal = {True: cs[0], False: cs[1]}
s = Boolean(pal)._setup(x, Color())
expected = [pal[x_i] for x_i in x]
assert_array_equal(s(x), expected)
def test_object_defaults(self, x):
vs = ["x", "y", "z"]
class MockProperty(ObjectProperty):
def _default_values(self, n):
return vs[:n]
s = Boolean()._setup(x, MockProperty())
expected = [vs[int(x_i)] for x_i in ~x]
assert s(x) == expected
def test_object_list(self, x):
vs = ["x", "y"]
s = Boolean(vs)._setup(x, ObjectProperty())
expected = [vs[int(x_i)] for x_i in ~x]
assert s(x) == expected
def test_object_dict(self, x):
vs = {True: "x", False: "y"}
s = Boolean(vs)._setup(x, ObjectProperty())
expected = [vs[x_i] for x_i in x]
assert s(x) == expected
def test_fill(self, x):
s = Boolean()._setup(x, Fill())
assert_array_equal(s(x), x)
def test_interval_defaults(self, x):
vs = (1, 2)
class MockProperty(IntervalProperty):
_default_range = vs
s = Boolean()._setup(x, MockProperty())
expected = [vs[int(x_i)] for x_i in x]
assert_array_equal(s(x), expected)
def test_interval_tuple(self, x):
vs = (3, 5)
s = Boolean(vs)._setup(x, IntervalProperty())
expected = [vs[int(x_i)] for x_i in x]
assert_array_equal(s(x), expected)
def test_finalize(self, x):
ax = mpl.figure.Figure().subplots()
s = Boolean()._setup(x, Coordinate(), ax.xaxis)
s._finalize(Plot(), ax.xaxis)
assert ax.get_xlim() == (1.5, -.5)
assert_array_equal(ax.get_xticks(), [0, 1])
assert ax.xaxis.major.formatter(0) == "False"
assert ax.xaxis.major.formatter(1) == "True"
| TestBoolean |
python | langchain-ai__langchain | libs/core/tests/unit_tests/vectorstores/test_vectorstore.py | {
"start": 548,
"end": 2061
} | class ____(VectorStore):
"""A VectorStore that only implements add texts."""
def __init__(self) -> None:
self.store: dict[str, Document] = {}
@override
def add_texts(
self,
texts: Iterable[str],
metadatas: list[dict] | None = None,
ids: list[str] | None = None,
**kwargs: Any,
) -> list[str]:
if not isinstance(texts, list):
texts = list(texts)
ids_iter = iter(ids or [])
ids_ = []
metadatas_ = metadatas or [{} for _ in texts]
for text, metadata in zip(texts, metadatas_ or [], strict=False):
next_id = next(ids_iter, None)
id_ = next_id or str(uuid.uuid4())
self.store[id_] = Document(page_content=text, metadata=metadata, id=id_)
ids_.append(id_)
return ids_
def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
return [self.store[id_] for id_ in ids if id_ in self.store]
@classmethod
@override
def from_texts(
cls,
texts: list[str],
embedding: Embeddings,
metadatas: list[dict] | None = None,
**kwargs: Any,
) -> CustomAddTextsVectorstore:
vectorstore = CustomAddTextsVectorstore()
vectorstore.add_texts(texts, metadatas=metadatas, **kwargs)
return vectorstore
def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> list[Document]:
raise NotImplementedError
| CustomAddTextsVectorstore |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator.py | {
"start": 12242,
"end": 12382
} | class ____(ResourceClosure):
def _init_remote_value(self):
return RemoteVariable(self, self._output_type_spec)
| PerWorkerVariableClosure |
python | doocs__leetcode | solution/1900-1999/1904.The Number of Full Rounds You Have Played/Solution.py | {
"start": 0,
"end": 316
} | class ____:
def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:
def f(s: str) -> int:
return int(s[:2]) * 60 + int(s[3:])
a, b = f(loginTime), f(logoutTime)
if a > b:
b += 1440
a, b = (a + 14) // 15, b // 15
return max(0, b - a)
| Solution |
python | pytorch__pytorch | torch/testing/_internal/distributed/_tensor/common_dtensor.py | {
"start": 5476,
"end": 6104
} | class ____(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.attention_norm = nn.LayerNorm(args.dim)
self.attention = Attention(args)
self.ffn_norm = nn.LayerNorm(args.dim)
self.feed_forward = FeedForward(
args.dim, hidden_dim=4 * args.dim, dropout_p=args.dropout_p
)
def forward(self, x):
h = x + self.attention(self.attention_norm(x))
out = h + self.feed_forward(self.ffn_norm(h))
return out
# A toy transformer model, partly inspired by the nanoGPT model:
# https://github.com/karpathy/nanoGPT.
| TransformerBlock |
python | jazzband__django-model-utils | tests/models.py | {
"start": 11325,
"end": 12451
} | class ____:
"""
Descriptor that returns a string version of the underlying integer value.
"""
def __init__(self, name: str):
self.name = name
@overload
def __get__(self, obj: None, cls: type[models.Model] | None = None) -> StringyDescriptor:
...
@overload
def __get__(self, obj: models.Model, cls: type[models.Model]) -> str:
...
def __get__(self, obj: models.Model | None, cls: type[models.Model] | None = None) -> StringyDescriptor | str:
if obj is None:
return self
if self.name in obj.get_deferred_fields():
# This queries the database, and sets the value on the instance.
assert cls is not None
fields_map = {f.name: f for f in cls._meta.fields}
field = fields_map[self.name]
DeferredAttribute(field=field).__get__(obj, cls)
return str(obj.__dict__[self.name])
def __set__(self, obj: object, value: str) -> None:
obj.__dict__[self.name] = int(value)
def __delete__(self, obj: object) -> None:
del obj.__dict__[self.name]
| StringyDescriptor |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 58357,
"end": 59359
} | class ____(BaseValidator):
"""
"any": {
"description": "Any type.",
"requiredOpts": [],
"otherOpts": [
"dflt",
"values",
"arrayOk"
]
},
"""
def __init__(self, plotly_name, parent_name, values=None, array_ok=False, **kwargs):
super(AnyValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
self.values = values
self.array_ok = array_ok
def description(self):
desc = """\
The '{plotly_name}' property accepts values of any type
""".format(plotly_name=self.plotly_name)
return desc
def validate_coerce(self, v):
if is_none_or_typed_array_spec(v):
pass
elif self.array_ok and is_homogeneous_array(v):
v = copy_to_readonly_numpy_array(v, kind="O")
elif self.array_ok and is_simple_array(v):
v = to_scalar_or_list(v)
return v
| AnyValidator |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 3382,
"end": 3652
} | class ____(scrapy.Spider):
name = 'sp'
custom_settings = {}
async def start(self):
self.logger.debug('It works!')
return
yield
""")
(proj_mod_path / "spiders" / "aiosp.py").write_text("""
import asyncio
import scrapy
| MySpider |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_views.py | {
"start": 19865,
"end": 20818
} | class ____(TestCase):
def setUp(self):
self.owner = get(User, username="owner")
self.member = get(User, username="member")
self.project = get(Project, slug="project")
self.organization = get(
Organization,
owners=[self.owner],
projects=[self.project],
)
self.client.force_login(self.owner)
def test_unspecified_slug_redirects_to_organization_edit(self):
self.assertEqual(Organization.objects.count(), 1)
resp = self.client.get(
reverse("organization_choose", kwargs={"next_name": "organization_edit"})
)
self.assertRedirects(
resp, reverse("organization_edit", kwargs={"slug": self.organization.slug})
)
@override_settings(
RTD_ALLOW_ORGANIZATIONS=True,
RTD_DEFAULT_FEATURES=dict([RTDProductFeature(TYPE_AUDIT_LOGS, value=90).to_item()]),
)
| OrganizationUnspecifiedSingleOrganizationRedirect |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/editorstack/editorstack.py | {
"start": 3119,
"end": 3190
} | class ____:
OptionsMenu = "editorstack_options_menu"
| EditorStackMenus |
python | spack__spack | lib/spack/spack/cmd/__init__.py | {
"start": 21246,
"end": 21503
} | class ____(spack.error.SpackError):
"""Exception class thrown for impermissible command names"""
def __init__(self, name):
self.name = name
super().__init__("{0} is not a permissible Spack command name.".format(name))
| CommandNameError |
python | crytic__slither | tests/e2e/detectors/test_detectors.py | {
"start": 383,
"end": 49522
} | class ____: # pylint: disable=too-few-public-methods
def __init__(
self,
detector: Type[AbstractDetector],
test_file: str,
solc_ver: str,
additional_files: Optional[List[str]] = None,
):
"""
:param detector:
:param test_file:
:param solc_ver:
:param additional_files: If the test changes additional files, list them here to allow the
test to update the source mapping
"""
self.detector = detector
self.test_file = test_file
self.solc_ver = solc_ver
if additional_files is None:
self.additional_files = []
else:
self.additional_files = additional_files
def set_solc(test_item: Test): # pylint: disable=too-many-lines
# hacky hack hack to pick the solc version we want
env = dict(os.environ)
if not solc_select.artifact_path(test_item.solc_ver).exists():
print("Installing solc version", test_item.solc_ver)
solc_select.install_artifacts([test_item.solc_ver])
env["SOLC_VERSION"] = test_item.solc_ver
os.environ.clear()
os.environ.update(env)
def id_test(test_item: Test):
return f"{test_item.detector.__name__}-{test_item.solc_ver}-{test_item.test_file}"
ALL_TESTS = [
Test(
all_detectors.UninitializedFunctionPtrsConstructor,
"uninitialized_function_ptr_constructor.sol",
"0.4.25",
),
Test(
all_detectors.UninitializedFunctionPtrsConstructor,
"uninitialized_function_ptr_constructor.sol",
"0.5.8",
),
Test(
all_detectors.UninitializedFunctionPtrsConstructor,
"uninitialized_function_ptr_constructor.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyBenign,
"reentrancy-benign.sol",
"0.4.25",
),
Test(
all_detectors.ReentrancyBenign,
"reentrancy-benign.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyBenign,
"reentrancy-benign.sol",
"0.6.11",
),
Test(
all_detectors.ReentrancyBenign,
"reentrancy-benign.sol",
"0.7.6",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"reentrancy-write.sol",
"0.4.25",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"reentrancy-write.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"reentrancy-write.sol",
"0.6.11",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"reentrancy-write.sol",
"0.7.6",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"DAO.sol",
"0.4.25",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"comment.sol",
"0.8.2",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"no-reentrancy-staticcall.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"no-reentrancy-staticcall.sol",
"0.6.11",
),
Test(
all_detectors.ReentrancyReadBeforeWritten,
"no-reentrancy-staticcall.sol",
"0.7.6",
),
Test(
all_detectors.BooleanEquality,
"boolean-constant-equality.sol",
"0.4.25",
),
Test(
all_detectors.BooleanEquality,
"boolean-constant-equality.sol",
"0.5.16",
),
Test(
all_detectors.BooleanEquality,
"boolean-constant-equality.sol",
"0.6.11",
),
Test(
all_detectors.BooleanEquality,
"boolean-constant-equality.sol",
"0.7.6",
),
Test(
all_detectors.BooleanConstantMisuse,
"boolean-constant-misuse.sol",
"0.4.25",
),
Test(
all_detectors.BooleanConstantMisuse,
"boolean-constant-misuse.sol",
"0.5.16",
),
Test(
all_detectors.BooleanConstantMisuse,
"boolean-constant-misuse.sol",
"0.6.11",
),
Test(
all_detectors.BooleanConstantMisuse,
"boolean-constant-misuse.sol",
"0.7.6",
),
Test(
all_detectors.UncheckedLowLevel,
"unchecked_lowlevel.sol",
"0.4.25",
),
Test(
all_detectors.UncheckedLowLevel,
"unchecked_lowlevel.sol",
"0.5.16",
),
Test(
all_detectors.UncheckedLowLevel,
"unchecked_lowlevel.sol",
"0.6.11",
),
Test(
all_detectors.UncheckedLowLevel,
"unchecked_lowlevel.sol",
"0.7.6",
),
Test(
all_detectors.UnindexedERC20EventParameters,
"erc20_indexed.sol",
"0.4.25",
),
Test(
all_detectors.UnindexedERC20EventParameters,
"erc20_indexed.sol",
"0.5.16",
),
Test(
all_detectors.UnindexedERC20EventParameters,
"erc20_indexed.sol",
"0.6.11",
),
Test(
all_detectors.UnindexedERC20EventParameters,
"erc20_indexed.sol",
"0.7.6",
),
Test(
all_detectors.IncorrectERC20InterfaceDetection,
"incorrect_erc20_interface.sol",
"0.4.25",
),
Test(
all_detectors.IncorrectERC20InterfaceDetection,
"incorrect_erc20_interface.sol",
"0.5.16",
),
Test(
all_detectors.IncorrectERC20InterfaceDetection,
"incorrect_erc20_interface.sol",
"0.6.11",
),
Test(
all_detectors.IncorrectERC20InterfaceDetection,
"incorrect_erc20_interface.sol",
"0.7.6",
),
Test(
all_detectors.IncorrectERC721InterfaceDetection,
"incorrect_erc721_interface.sol",
"0.4.25",
),
Test(
all_detectors.IncorrectERC721InterfaceDetection,
"incorrect_erc721_interface.sol",
"0.5.16",
),
Test(
all_detectors.IncorrectERC721InterfaceDetection,
"incorrect_erc721_interface.sol",
"0.6.11",
),
Test(
all_detectors.IncorrectERC721InterfaceDetection,
"incorrect_erc721_interface.sol",
"0.7.6",
),
Test(
all_detectors.UninitializedStateVarsDetection,
"uninitialized.sol",
"0.4.25",
),
Test(
all_detectors.UninitializedStateVarsDetection,
"uninitialized.sol",
"0.5.16",
),
Test(
all_detectors.UninitializedStateVarsDetection,
"uninitialized.sol",
"0.6.11",
),
Test(
all_detectors.UninitializedStateVarsDetection,
"uninitialized.sol",
"0.7.6",
),
Test(all_detectors.Backdoor, "backdoor.sol", "0.4.25"),
Test(all_detectors.Backdoor, "backdoor.sol", "0.5.16"),
Test(all_detectors.Backdoor, "backdoor.sol", "0.6.11"),
Test(all_detectors.Backdoor, "backdoor.sol", "0.7.6"),
Test(all_detectors.Suicidal, "suicidal.sol", "0.4.25"),
Test(all_detectors.Suicidal, "suicidal.sol", "0.5.16"),
Test(all_detectors.Suicidal, "suicidal.sol", "0.6.11"),
Test(all_detectors.Suicidal, "suicidal.sol", "0.7.6"),
Test(
all_detectors.ConstantPragma,
"pragma.0.4.25.sol",
"0.4.25",
["pragma.0.4.24.sol"],
),
Test(
all_detectors.ConstantPragma,
"pragma.0.5.16.sol",
"0.5.16",
["pragma.0.5.15.sol"],
),
Test(
all_detectors.ConstantPragma,
"pragma.0.6.11.sol",
"0.6.11",
["pragma.0.6.10.sol"],
),
Test(
all_detectors.ConstantPragma,
"pragma.0.7.6.sol",
"0.7.6",
["pragma.0.7.5.sol"],
),
Test(all_detectors.IncorrectSolc, "static.sol", "0.4.25"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.5.14"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.5.16"),
Test(all_detectors.IncorrectSolc, "dynamic_1.sol", "0.5.16"),
Test(all_detectors.IncorrectSolc, "dynamic_2.sol", "0.5.16"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.6.10"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.6.11"),
Test(all_detectors.IncorrectSolc, "dynamic_1.sol", "0.6.11"),
Test(all_detectors.IncorrectSolc, "dynamic_2.sol", "0.6.11"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.7.4"),
Test(all_detectors.IncorrectSolc, "static.sol", "0.7.6"),
Test(all_detectors.IncorrectSolc, "dynamic_1.sol", "0.7.6"),
Test(all_detectors.IncorrectSolc, "dynamic_2.sol", "0.7.6"),
Test(
all_detectors.ReentrancyEth,
"reentrancy.sol",
"0.4.25",
),
Test(
all_detectors.ReentrancyEth,
"reentrancy_indirect.sol",
"0.4.25",
),
Test(
all_detectors.ReentrancyEth,
"reentrancy.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyEth,
"reentrancy_indirect.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyEth,
"reentrancy.sol",
"0.6.11",
),
Test(
all_detectors.ReentrancyEth,
"reentrancy_indirect.sol",
"0.6.11",
),
Test(all_detectors.ReentrancyEth, "reentrancy.sol", "0.7.6"),
Test(
all_detectors.ReentrancyEth,
"reentrancy_indirect.sol",
"0.7.6",
),
Test(
all_detectors.ReentrancyEth,
"DAO.sol",
"0.4.25",
),
# Test the nonReentrant filtering
Test(all_detectors.ReentrancyEth, "reentrancy_with_non_reentrant.sol", "0.8.10"),
# Test parse_ignore_comments
Test(all_detectors.ReentrancyEth, "reentrancy_filtered_comments.sol", "0.8.10"),
Test(
all_detectors.UninitializedStorageVars,
"uninitialized_storage_pointer.sol",
"0.4.25",
),
Test(
all_detectors.UninitializedStorageVars,
"uninitialized_storage_pointer.sol",
"0.8.19",
),
Test(all_detectors.TxOrigin, "tx_origin.sol", "0.4.25"),
Test(all_detectors.TxOrigin, "tx_origin.sol", "0.5.16"),
Test(all_detectors.TxOrigin, "tx_origin.sol", "0.6.11"),
Test(all_detectors.TxOrigin, "tx_origin.sol", "0.7.6"),
Test(
all_detectors.UnusedStateVars,
"unused_state.sol",
"0.4.25",
),
Test(
all_detectors.UnusedStateVars,
"unused_state.sol",
"0.5.16",
),
Test(
all_detectors.UnusedStateVars,
"unused_state.sol",
"0.6.11",
),
Test(
all_detectors.UnusedStateVars,
"unused_state.sol",
"0.7.6",
),
Test(all_detectors.LockedEther, "locked_ether.sol", "0.4.25"),
Test(all_detectors.LockedEther, "locked_ether.sol", "0.5.16"),
Test(all_detectors.LockedEther, "locked_ether.sol", "0.6.11"),
Test(all_detectors.LockedEther, "locked_ether.sol", "0.7.6"),
Test(
all_detectors.ArbitrarySendEth,
"arbitrary_send_eth.sol",
"0.4.25",
),
Test(
all_detectors.ArbitrarySendEth,
"arbitrary_send_eth.sol",
"0.5.16",
),
Test(
all_detectors.ArbitrarySendEth,
"arbitrary_send_eth.sol",
"0.6.11",
),
Test(
all_detectors.ArbitrarySendEth,
"arbitrary_send_eth.sol",
"0.7.6",
),
Test(
all_detectors.Assembly,
"inline_assembly_contract.sol",
"0.4.25",
),
Test(
all_detectors.Assembly,
"inline_assembly_library.sol",
"0.4.25",
),
Test(
all_detectors.Assembly,
"inline_assembly_contract.sol",
"0.5.16",
),
Test(
all_detectors.Assembly,
"inline_assembly_library.sol",
"0.5.16",
),
Test(
all_detectors.Assembly,
"inline_assembly_contract.sol",
"0.6.11",
),
Test(
all_detectors.Assembly,
"inline_assembly_library.sol",
"0.6.11",
),
Test(
all_detectors.Assembly,
"inline_assembly_contract.sol",
"0.7.6",
),
Test(
all_detectors.Assembly,
"inline_assembly_library.sol",
"0.7.6",
),
Test(
all_detectors.LowLevelCalls,
"low_level_calls.sol",
"0.4.25",
),
Test(
all_detectors.LowLevelCalls,
"low_level_calls.sol",
"0.5.16",
),
Test(
all_detectors.LowLevelCalls,
"low_level_calls.sol",
"0.6.11",
),
Test(
all_detectors.LowLevelCalls,
"low_level_calls.sol",
"0.7.6",
),
Test(
all_detectors.CouldBeConstant,
"const_state_variables.sol",
"0.4.25",
),
Test(
all_detectors.CouldBeConstant,
"const_state_variables.sol",
"0.5.16",
),
Test(
all_detectors.CouldBeConstant,
"const_state_variables.sol",
"0.6.11",
),
Test(
all_detectors.CouldBeConstant,
"const_state_variables.sol",
"0.7.6",
),
Test(
all_detectors.CouldBeConstant,
"const_state_variables.sol",
"0.8.0",
),
Test(
all_detectors.CouldBeConstant,
"unused_yul.sol",
"0.8.0",
),
Test(
all_detectors.CouldBeImmutable,
"immut_state_variables.sol",
"0.4.25",
),
Test(
all_detectors.CouldBeImmutable,
"immut_state_variables.sol",
"0.5.16",
),
Test(
all_detectors.CouldBeImmutable,
"immut_state_variables.sol",
"0.6.11",
),
Test(
all_detectors.CouldBeImmutable,
"immut_state_variables.sol",
"0.7.6",
),
Test(
all_detectors.CouldBeImmutable,
"immut_state_variables.sol",
"0.8.0",
),
Test(
all_detectors.ExternalFunction,
"external_function.sol",
"0.4.25",
),
Test(
all_detectors.ExternalFunction,
"external_function_2.sol",
"0.4.25",
),
Test(
all_detectors.ExternalFunction,
"external_function_3.sol",
"0.4.25",
),
Test(
all_detectors.ExternalFunction,
"external_function.sol",
"0.5.16",
),
Test(
all_detectors.ExternalFunction,
"external_function_2.sol",
"0.5.16",
),
Test(
all_detectors.ExternalFunction,
"external_function_3.sol",
"0.5.16",
),
Test(
all_detectors.ExternalFunction,
"external_function.sol",
"0.6.11",
),
Test(
all_detectors.ExternalFunction,
"external_function_2.sol",
"0.6.11",
),
Test(
all_detectors.ExternalFunction,
"external_function_3.sol",
"0.6.11",
),
Test(
all_detectors.ExternalFunction,
"external_function.sol",
"0.7.6",
),
Test(
all_detectors.ExternalFunction,
"external_function_2.sol",
"0.7.6",
),
Test(
all_detectors.ExternalFunction,
"external_function_3.sol",
"0.7.6",
),
Test(
all_detectors.NamingConvention,
"naming_convention.sol",
"0.4.25",
),
Test(
all_detectors.NamingConvention,
"naming_convention.sol",
"0.5.16",
),
Test(
all_detectors.NamingConvention,
"naming_convention.sol",
"0.6.11",
),
Test(
all_detectors.NamingConvention,
"naming_convention.sol",
"0.7.6",
),
Test(
all_detectors.NamingConvention,
"no_warning_for_public_constants.sol",
"0.4.25",
),
Test(
all_detectors.NamingConvention,
"no_warning_for_public_constants.sol",
"0.5.16",
),
Test(
all_detectors.NamingConvention,
"no_warning_for_public_constants.sol",
"0.6.11",
),
Test(
all_detectors.NamingConvention,
"no_warning_for_public_constants.sol",
"0.7.6",
),
Test(
all_detectors.ControlledDelegateCall,
"controlled_delegatecall.sol",
"0.4.25",
),
Test(
all_detectors.ControlledDelegateCall,
"controlled_delegatecall.sol",
"0.5.16",
),
Test(
all_detectors.ControlledDelegateCall,
"controlled_delegatecall.sol",
"0.6.11",
),
Test(
all_detectors.ControlledDelegateCall,
"controlled_delegatecall.sol",
"0.7.6",
),
Test(
all_detectors.UninitializedLocalVars,
"uninitialized_local_variable.sol",
"0.4.25",
),
Test(
all_detectors.UninitializedLocalVars,
"uninitialized_local_variable.sol",
"0.5.16",
),
Test(
all_detectors.UninitializedLocalVars,
"uninitialized_local_variable.sol",
"0.6.11",
),
Test(
all_detectors.UninitializedLocalVars,
"uninitialized_local_variable.sol",
"0.7.6",
),
Test(all_detectors.ConstantFunctionsAsm, "constant.sol", "0.4.25"),
Test(
all_detectors.ConstantFunctionsState,
"constant.sol",
"0.4.25",
),
Test(all_detectors.ConstantFunctionsAsm, "constant.sol", "0.5.16"),
Test(
all_detectors.ConstantFunctionsState,
"constant.sol",
"0.5.16",
),
Test(all_detectors.ConstantFunctionsAsm, "constant.sol", "0.6.11"),
Test(
all_detectors.ConstantFunctionsState,
"constant.sol",
"0.6.11",
),
Test(all_detectors.ConstantFunctionsAsm, "constant.sol", "0.7.6"),
Test(all_detectors.ConstantFunctionsState, "constant.sol", "0.7.6"),
Test(
all_detectors.UnusedReturnValues,
"unused_return.sol",
"0.4.25",
),
Test(
all_detectors.UnusedReturnValues,
"unused_return.sol",
"0.5.16",
),
Test(
all_detectors.UnusedReturnValues,
"unused_return.sol",
"0.6.11",
),
Test(
all_detectors.UnusedReturnValues,
"unused_return.sol",
"0.7.6",
),
Test(
all_detectors.UncheckedTransfer,
"unused_return_transfers.sol",
"0.7.6",
),
Test(
all_detectors.ShadowingAbstractDetection,
"shadowing_abstract.sol",
"0.4.25",
),
Test(
all_detectors.ShadowingAbstractDetection,
"shadowing_abstract.sol",
"0.5.16",
),
Test(
all_detectors.ShadowingAbstractDetection,
"shadowing_state_variable.sol",
"0.7.5",
),
Test(
all_detectors.ShadowingAbstractDetection,
"public_gap_variable.sol",
"0.7.5",
),
Test(
all_detectors.StateShadowing,
"shadowing_state_variable.sol",
"0.4.25",
),
Test(
all_detectors.StateShadowing,
"shadowing_state_variable.sol",
"0.5.16",
),
Test(
all_detectors.StateShadowing,
"shadowing_state_variable.sol",
"0.6.11",
),
Test(
all_detectors.StateShadowing,
"shadowing_state_variable.sol",
"0.7.5",
),
Test(
all_detectors.StateShadowing,
"public_gap_variable.sol",
"0.7.5",
),
Test(
all_detectors.StateShadowing,
"shadowing_state_variable.sol",
"0.7.6",
),
Test(all_detectors.Timestamp, "timestamp.sol", "0.4.25"),
Test(all_detectors.Timestamp, "timestamp.sol", "0.5.16"),
Test(all_detectors.Timestamp, "timestamp.sol", "0.6.11"),
Test(all_detectors.Timestamp, "timestamp.sol", "0.7.6"),
Test(
all_detectors.MultipleCallsInLoop,
"multiple_calls_in_loop.sol",
"0.4.25",
),
Test(
all_detectors.MultipleCallsInLoop,
"multiple_calls_in_loop.sol",
"0.5.16",
),
Test(
all_detectors.MultipleCallsInLoop,
"multiple_calls_in_loop.sol",
"0.6.11",
),
Test(
all_detectors.MultipleCallsInLoop,
"multiple_calls_in_loop.sol",
"0.7.6",
),
Test(
all_detectors.BuiltinSymbolShadowing,
"shadowing_builtin_symbols.sol",
"0.4.25",
),
Test(
all_detectors.BuiltinSymbolShadowing,
"shadowing_builtin_symbols.sol",
"0.5.16",
),
Test(
all_detectors.LocalShadowing,
"shadowing_local_variable.sol",
"0.4.25",
),
Test(
all_detectors.LocalShadowing,
"shadowing_local_variable.sol",
"0.5.16",
),
Test(
all_detectors.LocalShadowing,
"shadowing_local_variable.sol",
"0.6.11",
),
Test(
all_detectors.LocalShadowing,
"shadowing_local_variable.sol",
"0.7.6",
),
Test(
all_detectors.RightToLeftOverride,
"right_to_left_override.sol",
"0.4.25",
),
Test(
all_detectors.RightToLeftOverride,
"right_to_left_override.sol",
"0.5.16",
),
Test(
all_detectors.RightToLeftOverride,
"right_to_left_override.sol",
"0.6.11",
),
Test(
all_detectors.RightToLeftOverride,
"unicode_direction_override.sol",
"0.8.0",
),
Test(all_detectors.VoidConstructor, "void-cst.sol", "0.4.25"),
Test(all_detectors.VoidConstructor, "void-cst.sol", "0.5.16"),
Test(all_detectors.VoidConstructor, "void-cst.sol", "0.6.11"),
Test(all_detectors.VoidConstructor, "void-cst.sol", "0.7.6"),
Test(
all_detectors.UncheckedSend,
"unchecked_send.sol",
"0.4.25",
),
Test(
all_detectors.UncheckedSend,
"unchecked_send.sol",
"0.5.16",
),
Test(
all_detectors.UncheckedSend,
"unchecked_send.sol",
"0.6.11",
),
Test(
all_detectors.UncheckedSend,
"unchecked_send.sol",
"0.7.6",
),
Test(
all_detectors.ReentrancyEvent,
"reentrancy-events.sol",
"0.5.16",
),
Test(
all_detectors.ReentrancyEvent,
"reentrancy-events.sol",
"0.6.11",
),
Test(
all_detectors.ReentrancyEvent,
"reentrancy-events.sol",
"0.7.6",
),
Test(
all_detectors.IncorrectStrictEquality,
"incorrect_equality.sol",
"0.4.25",
),
Test(
all_detectors.IncorrectStrictEquality,
"incorrect_equality.sol",
"0.5.16",
),
Test(
all_detectors.IncorrectStrictEquality,
"incorrect_equality.sol",
"0.6.11",
),
Test(
all_detectors.IncorrectStrictEquality,
"incorrect_equality.sol",
"0.7.6",
),
Test(
all_detectors.TooManyDigits,
"too_many_digits.sol",
"0.4.25",
),
Test(
all_detectors.TooManyDigits,
"too_many_digits.sol",
"0.5.16",
),
Test(
all_detectors.TooManyDigits,
"too_many_digits.sol",
"0.6.11",
),
Test(
all_detectors.TooManyDigits,
"too_many_digits.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Buggy.sol",
"0.4.25",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Fixed.sol",
"0.4.25",
),
Test(
all_detectors.UnprotectedUpgradeable,
"whitelisted.sol",
"0.4.25",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Reinitializer.sol",
"0.4.25",
),
Test(
all_detectors.UnprotectedUpgradeable,
"AnyInitializer.sol",
"0.4.25",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Buggy.sol",
"0.5.16",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Fixed.sol",
"0.5.16",
),
Test(
all_detectors.UnprotectedUpgradeable,
"whitelisted.sol",
"0.5.16",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Reinitializer.sol",
"0.5.16",
),
Test(
all_detectors.UnprotectedUpgradeable,
"AnyInitializer.sol",
"0.5.16",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Buggy.sol",
"0.6.11",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Fixed.sol",
"0.6.11",
),
Test(
all_detectors.UnprotectedUpgradeable,
"whitelisted.sol",
"0.6.11",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Reinitializer.sol",
"0.6.11",
),
Test(
all_detectors.UnprotectedUpgradeable,
"AnyInitializer.sol",
"0.6.11",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Buggy.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Fixed.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Reinitializer.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"AnyInitializer.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"whitelisted.sol",
"0.7.6",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Buggy.sol",
"0.8.15",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Fixed.sol",
"0.8.15",
),
Test(
all_detectors.UnprotectedUpgradeable,
"whitelisted.sol",
"0.8.15",
),
Test(
all_detectors.UnprotectedUpgradeable,
"Reinitializer.sol",
"0.8.15",
),
Test(
all_detectors.UnprotectedUpgradeable,
"AnyInitializer.sol",
"0.8.15",
),
Test(
all_detectors.ABIEncoderV2Array,
"storage_ABIEncoderV2_array.sol",
"0.4.25",
),
Test(
all_detectors.ABIEncoderV2Array,
"storage_ABIEncoderV2_array.sol",
"0.5.10",
),
Test(
all_detectors.ABIEncoderV2Array,
"storage_ABIEncoderV2_array.sol",
"0.5.9",
),
Test(
all_detectors.ArrayByReference,
"array_by_reference.sol",
"0.4.25",
),
Test(
all_detectors.ArrayByReference,
"array_by_reference.sol",
"0.5.16",
),
Test(
all_detectors.ArrayByReference,
"array_by_reference.sol",
"0.6.11",
),
Test(
all_detectors.ArrayByReference,
"array_by_reference.sol",
"0.7.6",
),
Test(
all_detectors.AssertStateChange,
"assert_state_change.sol",
"0.4.25",
),
Test(
all_detectors.AssertStateChange,
"assert_state_change.sol",
"0.5.16",
),
Test(
all_detectors.AssertStateChange,
"assert_state_change.sol",
"0.6.11",
),
Test(
all_detectors.AssertStateChange,
"assert_state_change.sol",
"0.7.6",
),
Test(
all_detectors.ArrayLengthAssignment,
"array_length_assignment.sol",
"0.4.25",
),
Test(
all_detectors.ArrayLengthAssignment,
"array_length_assignment.sol",
"0.5.16",
),
Test(
all_detectors.CostlyOperationsInLoop,
"multiple_costly_operations_in_loop.sol",
"0.4.25",
),
Test(
all_detectors.CostlyOperationsInLoop,
"multiple_costly_operations_in_loop.sol",
"0.5.16",
),
Test(
all_detectors.CostlyOperationsInLoop,
"multiple_costly_operations_in_loop.sol",
"0.6.11",
),
Test(
all_detectors.CostlyOperationsInLoop,
"multiple_costly_operations_in_loop.sol",
"0.7.6",
),
Test(
all_detectors.FunctionInitializedState,
"function_init_state_variables.sol",
"0.4.25",
),
Test(
all_detectors.FunctionInitializedState,
"function_init_state_variables.sol",
"0.5.16",
),
Test(
all_detectors.FunctionInitializedState,
"function_init_state_variables.sol",
"0.6.11",
),
Test(
all_detectors.FunctionInitializedState,
"function_init_state_variables.sol",
"0.7.6",
),
Test(
all_detectors.MappingDeletionDetection,
"MappingDeletion.sol",
"0.4.25",
),
Test(
all_detectors.MappingDeletionDetection,
"MappingDeletion.sol",
"0.5.16",
),
Test(
all_detectors.MappingDeletionDetection,
"MappingDeletion.sol",
"0.6.11",
),
Test(
all_detectors.MappingDeletionDetection,
"MappingDeletion.sol",
"0.7.6",
),
Test(
all_detectors.PublicMappingNested,
"public_mappings_nested.sol",
"0.4.25",
),
Test(
all_detectors.RedundantStatements,
"redundant_statements.sol",
"0.4.25",
),
Test(
all_detectors.RedundantStatements,
"redundant_statements.sol",
"0.5.16",
),
Test(
all_detectors.RedundantStatements,
"redundant_statements.sol",
"0.6.11",
),
Test(
all_detectors.RedundantStatements,
"redundant_statements.sol",
"0.7.6",
),
Test(
all_detectors.ReusedBaseConstructor,
"reused_base_constructor.sol",
"0.4.21",
),
Test(
all_detectors.ReusedBaseConstructor,
"reused_base_constructor.sol",
"0.4.25",
),
Test(
all_detectors.StorageSignedIntegerArray,
"storage_signed_integer_array.sol",
"0.5.10",
),
Test(
all_detectors.StorageSignedIntegerArray,
"storage_signed_integer_array.sol",
"0.5.16",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented.sol",
"0.4.25",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented.sol",
"0.5.16",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented.sol",
"0.6.11",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented.sol",
"0.7.6",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented_interfaces.sol",
"0.5.16",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented_interfaces.sol",
"0.6.11",
),
Test(
all_detectors.UnimplementedFunctionDetection,
"unimplemented_interfaces.sol",
"0.7.6",
),
Test(all_detectors.BadPRNG, "bad_prng.sol", "0.4.25"),
Test(all_detectors.BadPRNG, "bad_prng.sol", "0.5.16"),
Test(all_detectors.BadPRNG, "bad_prng.sol", "0.6.11"),
Test(all_detectors.BadPRNG, "bad_prng.sol", "0.7.6"),
Test(
all_detectors.MissingEventsAccessControl,
"missing_events_access_control.sol",
"0.4.25",
),
Test(
all_detectors.MissingEventsAccessControl,
"missing_events_access_control.sol",
"0.5.16",
),
Test(
all_detectors.MissingEventsAccessControl,
"missing_events_access_control.sol",
"0.6.11",
),
Test(
all_detectors.MissingEventsAccessControl,
"missing_events_access_control.sol",
"0.7.6",
),
Test(
all_detectors.MissingEventsArithmetic,
"missing_events_arithmetic.sol",
"0.4.25",
),
Test(
all_detectors.MissingEventsArithmetic,
"missing_events_arithmetic.sol",
"0.5.16",
),
Test(
all_detectors.MissingEventsArithmetic,
"missing_events_arithmetic.sol",
"0.6.11",
),
Test(
all_detectors.MissingEventsArithmetic,
"missing_events_arithmetic.sol",
"0.7.6",
),
Test(
all_detectors.ModifierDefaultDetection,
"modifier_default.sol",
"0.4.25",
),
Test(
all_detectors.ModifierDefaultDetection,
"modifier_default.sol",
"0.5.16",
),
Test(
all_detectors.ModifierDefaultDetection,
"modifier_default.sol",
"0.6.11",
),
Test(
all_detectors.ModifierDefaultDetection,
"modifier_default.sol",
"0.7.6",
),
Test(
all_detectors.IncorrectUnaryExpressionDetection,
"invalid_unary_expression.sol",
"0.4.25",
),
Test(
all_detectors.MissingZeroAddressValidation,
"missing_zero_address_validation.sol",
"0.4.25",
),
Test(
all_detectors.MissingZeroAddressValidation,
"missing_zero_address_validation.sol",
"0.5.16",
),
Test(
all_detectors.MissingZeroAddressValidation,
"missing_zero_address_validation.sol",
"0.6.11",
),
Test(
all_detectors.MissingZeroAddressValidation,
"missing_zero_address_validation.sol",
"0.7.6",
),
Test(
all_detectors.PredeclarationUsageLocal,
"predeclaration_usage_local.sol",
"0.4.25",
),
Test(
all_detectors.DeadCode,
"dead-code.sol",
"0.8.0",
),
Test(
all_detectors.WriteAfterWrite,
"write-after-write.sol",
"0.8.0",
),
Test(
all_detectors.ShiftParameterMixup,
"shift_parameter_mixup.sol",
"0.4.25",
),
Test(
all_detectors.ShiftParameterMixup,
"shift_parameter_mixup.sol",
"0.5.16",
),
Test(
all_detectors.ShiftParameterMixup,
"shift_parameter_mixup.sol",
"0.6.11",
),
Test(
all_detectors.ShiftParameterMixup,
"shift_parameter_mixup.sol",
"0.7.6",
),
Test(
all_detectors.MissingInheritance,
"unimplemented_interface.sol",
"0.4.25",
),
Test(
all_detectors.MissingInheritance,
"unimplemented_interface.sol",
"0.5.16",
),
Test(
all_detectors.MissingInheritance,
"unimplemented_interface.sol",
"0.6.11",
),
Test(
all_detectors.MissingInheritance,
"unimplemented_interface.sol",
"0.7.6",
),
# Does not work on the CI. Most likely because of solc 0.4.2?
# Test(
# all_detectors.EnumConversion,
# "enum_conversion.sol",
# "0.4.2",
# ),
Test(
all_detectors.MultipleConstructorSchemes,
"multiple_constructor_schemes.sol",
"0.4.22",
),
Test(
all_detectors.DeprecatedStandards,
"deprecated_calls.sol",
"0.4.25",
),
Test(
all_detectors.DivideBeforeMultiply,
"divide_before_multiply.sol",
"0.4.25",
),
Test(
all_detectors.DivideBeforeMultiply,
"divide_before_multiply.sol",
"0.5.16",
),
Test(
all_detectors.DivideBeforeMultiply,
"divide_before_multiply.sol",
"0.6.11",
),
Test(
all_detectors.DivideBeforeMultiply,
"divide_before_multiply.sol",
"0.7.6",
),
Test(
all_detectors.TypeBasedTautology,
"type_based_tautology.sol",
"0.4.25",
),
Test(
all_detectors.TypeBasedTautology,
"type_based_tautology.sol",
"0.5.16",
),
Test(
all_detectors.TypeBasedTautology,
"type_based_tautology.sol",
"0.6.11",
),
Test(
all_detectors.TypeBasedTautology,
"type_based_tautology.sol",
"0.7.6",
),
Test(
all_detectors.MsgValueInLoop,
"msg_value_loop.sol",
"0.4.25",
),
Test(
all_detectors.MsgValueInLoop,
"msg_value_loop.sol",
"0.5.16",
),
Test(
all_detectors.MsgValueInLoop,
"msg_value_loop.sol",
"0.6.11",
),
Test(
all_detectors.MsgValueInLoop,
"msg_value_loop.sol",
"0.7.6",
),
Test(
all_detectors.MsgValueInLoop,
"msg_value_loop.sol",
"0.8.0",
),
Test(
all_detectors.DelegatecallInLoop,
"delegatecall_loop.sol",
"0.4.25",
),
Test(
all_detectors.DelegatecallInLoop,
"delegatecall_loop.sol",
"0.5.16",
),
Test(
all_detectors.DelegatecallInLoop,
"delegatecall_loop.sol",
"0.6.11",
),
Test(
all_detectors.DelegatecallInLoop,
"delegatecall_loop.sol",
"0.7.6",
),
Test(
all_detectors.DelegatecallInLoop,
"delegatecall_loop.sol",
"0.8.0",
),
Test(
all_detectors.ProtectedVariables,
"comment.sol",
"0.8.2",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20.sol",
"0.4.25",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20.sol",
"0.5.16",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20.sol",
"0.6.11",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20.sol",
"0.7.6",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20.sol",
"0.8.0",
),
Test(
all_detectors.ArbitrarySendErc20NoPermit,
"arbitrary_send_erc20_inheritance.sol",
"0.8.0",
),
Test(
all_detectors.ArbitrarySendErc20Permit,
"arbitrary_send_erc20_permit.sol",
"0.4.25",
),
Test(
all_detectors.ArbitrarySendErc20Permit,
"arbitrary_send_erc20_permit.sol",
"0.5.16",
),
Test(
all_detectors.ArbitrarySendErc20Permit,
"arbitrary_send_erc20_permit.sol",
"0.6.11",
),
Test(
all_detectors.ArbitrarySendErc20Permit,
"arbitrary_send_erc20_permit.sol",
"0.7.6",
),
Test(
all_detectors.ArbitrarySendErc20Permit,
"arbitrary_send_erc20_permit.sol",
"0.8.0",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_collision.sol",
"0.4.25",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_collision.sol",
"0.5.16",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_collision.sol",
"0.6.11",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_collision.sol",
"0.7.6",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_collision.sol",
"0.8.0",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_wrong_return_type.sol",
"0.4.25",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_wrong_return_type.sol",
"0.5.16",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_wrong_return_type.sol",
"0.6.11",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_wrong_return_type.sol",
"0.7.6",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_wrong_return_type.sol",
"0.8.0",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_state_var_collision.sol",
"0.4.25",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_state_var_collision.sol",
"0.5.16",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_state_var_collision.sol",
"0.6.11",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_state_var_collision.sol",
"0.7.6",
),
Test(
all_detectors.DomainSeparatorCollision,
"permit_domain_state_var_collision.sol",
"0.8.0",
),
Test(
all_detectors.VarReadUsingThis,
"var_read_using_this.sol",
"0.4.25",
),
Test(
all_detectors.VarReadUsingThis,
"var_read_using_this.sol",
"0.5.16",
),
Test(all_detectors.VarReadUsingThis, "var_read_using_this.sol", "0.6.11"),
Test(
all_detectors.VarReadUsingThis,
"var_read_using_this.sol",
"0.7.6",
),
Test(
all_detectors.VarReadUsingThis,
"var_read_using_this.sol",
"0.8.15",
),
Test(
all_detectors.CyclomaticComplexity,
"HighCyclomaticComplexity.sol",
"0.8.16",
),
Test(
all_detectors.CyclomaticComplexity,
"LowCyclomaticComplexity.sol",
"0.8.16",
),
Test(
all_detectors.CacheArrayLength,
"CacheArrayLength.sol",
"0.8.17",
),
Test(
all_detectors.IncorrectUsingFor,
"IncorrectUsingForTopLevel.sol",
"0.8.17",
),
Test(
all_detectors.EncodePackedCollision,
"encode_packed_collision.sol",
"0.7.6",
),
Test(
all_detectors.IncorrectReturn,
"incorrect_return.sol",
"0.8.10",
),
Test(
all_detectors.ReturnInsteadOfLeave,
"incorrect_return.sol",
"0.8.10",
),
Test(
all_detectors.IncorrectOperatorExponentiation,
"incorrect_exp.sol",
"0.7.6",
),
Test(
all_detectors.TautologicalCompare,
"compare.sol",
"0.8.20",
),
Test(
all_detectors.ReturnBomb,
"return_bomb.sol",
"0.8.20",
),
Test(
all_detectors.OutOfOrderRetryable,
"out_of_order_retryable.sol",
"0.8.20",
),
Test(
all_detectors.GelatoUnprotectedRandomness,
"gelato_unprotected_randomness.sol",
"0.8.20",
),
Test(
all_detectors.ChronicleUncheckedPrice,
"chronicle_unchecked_price.sol",
"0.8.20",
),
Test(
all_detectors.PythUncheckedConfidence,
"pyth_unchecked_confidence.sol",
"0.8.20",
),
Test(
all_detectors.PythUncheckedPublishTime,
"pyth_unchecked_publishtime.sol",
"0.8.20",
),
Test(
all_detectors.ChainlinkFeedRegistry,
"chainlink_feed_registry.sol",
"0.8.20",
),
Test(
all_detectors.PythDeprecatedFunctions,
"pyth_deprecated_functions.sol",
"0.8.20",
),
Test(
all_detectors.OptimismDeprecation,
"optimism_deprecation.sol",
"0.8.20",
),
# Test(
# all_detectors.UnusedImport,
# "ConstantContractLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ConstantContractLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ConstantTopLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ConstantTopLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ContractUsedInContractTest1.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ContractUsedInContractTest2.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "ContractUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomErrorTopLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomEventContractLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomEventContractLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedInContractTest1.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedInContractTest2.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedInContractTest3.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedInContractTest4.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedTopLevelTest1.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeContractLevelUsedTopLevelTest2.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedInContractTest1.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedInContractTest2.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedInContractTest3.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedInContractTest4.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedTopLevelTest1.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "CustomTypeTopLevelUsedTopLevelTest2.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "EnumContractLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "EnumContractLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "EnumTopLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "EnumTopLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "FunctionContractLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "FunctionContractLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "FunctionTopLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "FunctionTopLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "LibraryUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "LibraryUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "StructContractLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "StructContractLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "StructTopLevelUsedInContractTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "StructTopLevelUsedTopLevelTest.sol",
# "0.8.16",
# ),
# Test(
# all_detectors.UnusedImport,
# "C.sol",
# "0.8.16",
# ),
]
GENERIC_PATH = "/GENERIC_PATH"
TEST_DATA_DIR = Path(__file__).resolve().parent / "test_data"
# pylint: disable=too-many-locals
@pytest.mark.parametrize("test_item", ALL_TESTS, ids=id_test)
def test_detector(test_item: Test, snapshot):
test_dir_path = Path(
TEST_DATA_DIR,
test_item.detector.ARGUMENT,
test_item.solc_ver,
).as_posix()
test_file_path = Path(test_dir_path, test_item.test_file).as_posix()
zip_artifact_path = Path(f"{test_file_path}-{test_item.solc_ver}.zip").as_posix()
crytic_compile = load_from_zip(zip_artifact_path)[0]
sl = Slither(crytic_compile)
sl.register_detector(test_item.detector)
results = sl.run_detectors()
actual_output = ""
for detector_result in results:
for result in detector_result:
actual_output += result["description"]
actual_output += "\n"
assert snapshot() == actual_output
def _generate_compile(test_item: Test, skip_existing=False):
test_dir_path = Path(
TEST_DATA_DIR,
test_item.detector.ARGUMENT,
test_item.solc_ver,
).as_posix()
test_file_path = Path(test_dir_path, test_item.test_file).as_posix()
zip_artifact_path = Path(f"{test_file_path}-{test_item.solc_ver}.zip").as_posix()
if skip_existing:
if os.path.isfile(zip_artifact_path):
return
set_solc(test_item)
crytic_compile = CryticCompile(test_file_path)
save_to_zip([crytic_compile], zip_artifact_path)
if __name__ == "__main__":
if len(sys.argv) != 2:
print(
"To generate the zip artifacts run\n\tpython tests/e2e/tests/test_detectors.py --compile"
)
elif sys.argv[1] == "--compile":
for next_test in ALL_TESTS:
_generate_compile(next_test, skip_existing=True)
| Test |
python | plotly__plotly.py | plotly/graph_objs/contourcarpet/colorbar/_tickfont.py | {
"start": 233,
"end": 9949
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contourcarpet.colorbar"
_path_str = "contourcarpet.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.contourcarpet.
colorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Tickfont
"""
super().__init__("tickfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.contourcarpet.colorbar.Tickfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Tickfont`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tickfont |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_join.py | {
"start": 151,
"end": 1813
} | class ____:
def test_join_outer_indexer(self):
pi = period_range("1/1/2000", "1/20/2000", freq="D")
result = pi._outer_indexer(pi)
tm.assert_extension_array_equal(result[0], pi._values)
tm.assert_numpy_array_equal(result[1], np.arange(len(pi), dtype=np.intp))
tm.assert_numpy_array_equal(result[2], np.arange(len(pi), dtype=np.intp))
def test_joins(self, join_type):
index = period_range("1/1/2000", "1/20/2000", freq="D")
joined = index.join(index[:-5], how=join_type)
assert isinstance(joined, PeriodIndex)
assert joined.freq == index.freq
def test_join_self(self, join_type):
index = period_range("1/1/2000", "1/20/2000", freq="D")
res = index.join(index, how=join_type)
assert index is res
def test_join_does_not_recur(self):
df = DataFrame(
np.ones((3, 2)),
index=date_range("2020-01-01", periods=3),
columns=period_range("2020-01-01", periods=2),
)
ser = df.iloc[:2, 0]
res = ser.index.join(df.columns, how="outer")
expected = Index(
[ser.index[0], ser.index[1], df.columns[0], df.columns[1]], object
)
tm.assert_index_equal(res, expected)
def test_join_mismatched_freq_raises(self):
# pre-GH#55782 this raises IncompatibleFrequency
index = period_range("1/1/2000", "1/20/2000", freq="D")
index3 = period_range("1/1/2000", "1/20/2000", freq="2D")
result = index.join(index3)
expected = index.astype(object).join(index3.astype(object))
tm.assert_index_equal(result, expected)
| TestJoin |
python | python__mypy | mypyc/irbuild/missingtypevisitor.py | {
"start": 178,
"end": 699
} | class ____(ExtendedTraverserVisitor):
"""AST visitor that can be used to add any missing types as a generic AnyType."""
def __init__(self, types: dict[Expression, Type]) -> None:
super().__init__()
self.types: dict[Expression, Type] = types
def visit(self, o: Node) -> bool:
if isinstance(o, Expression) and o not in self.types:
self.types[o] = AnyType(TypeOfAny.special_form)
# If returns True, will continue to nested nodes.
return True
| MissingTypesVisitor |
python | getsentry__sentry | src/sentry/rules/actions/notify_event.py | {
"start": 381,
"end": 1759
} | class ____(EventAction):
"""Used for notifying *all* enabled plugins."""
id = "sentry.rules.actions.notify_event.NotifyEventAction"
label = "Send a notification (for all legacy integrations)"
prompt = "Send a notification to all legacy integrations"
def get_plugins(self) -> Sequence[LegacyPluginService]:
from sentry.plugins.bases.notify import NotificationPlugin
results = []
for plugin in plugins.for_project(self.project, version=1):
if not isinstance(plugin, NotificationPlugin):
continue
results.append(LegacyPluginService(plugin))
return results
def after(
self, event: GroupEvent, notification_uuid: str | None = None
) -> Generator[CallbackFuture]:
group = event.group
for plugin_ in self.get_plugins():
# plugin is now wrapped in the LegacyPluginService object
plugin = plugin_.service
if not safe_execute(plugin.should_notify, group=group, event=event):
continue
metrics.incr(
"notifications.sent",
instance=plugin.slug,
tags={
"issue_type": event.group.issue_type.slug,
},
skip_internal=False,
)
yield self.future(plugin.rule_notify)
| NotifyEventAction |
python | getsentry__sentry | src/sentry/seer/endpoints/seer_rpc.py | {
"start": 4901,
"end": 6424
} | class ____(TypedDict):
data: list[dict[str, Any]]
meta: dict[str, Any]
def compare_signature(url: str, body: bytes, signature: str) -> bool:
"""
Compare request data + signature signed by one of the shared secrets.
Once a key has been able to validate the signature other keys will
not be attempted. We should only have multiple keys during key rotations.
"""
if not settings.SEER_RPC_SHARED_SECRET:
raise RpcAuthenticationSetupException(
"Cannot validate RPC request signatures without SEER_RPC_SHARED_SECRET"
)
if not signature.startswith("rpc0:"):
logger.error("Seer RPC signature validation failed: invalid signature prefix")
return False
if not body:
logger.error("Seer RPC signature validation failed: no body")
return False
try:
# We aren't using the version bits currently.
_, signature_data = signature.split(":", 2)
signature_input = body
for key in settings.SEER_RPC_SHARED_SECRET:
computed = hmac.new(key.encode(), signature_input, hashlib.sha256).hexdigest()
is_valid = hmac.compare_digest(computed.encode(), signature_data.encode())
if is_valid:
return True
except Exception:
logger.exception("Seer RPC signature validation failed")
return False
logger.error("Seer RPC signature validation failed")
return False
@AuthenticationSiloLimit(SiloMode.CONTROL, SiloMode.REGION)
| SpansResponse |
python | dask__dask | dask/dataframe/dask_expr/io/parquet.py | {
"start": 2813,
"end": 7308
} | class ____:
_filesystems = weakref.WeakValueDictionary() # type: ignore[var-annotated]
_filesystem_pickle_cache = (-1, None)
def __init__(
self, fragment, filesystem, file_size=None, fragment_packed=None
) -> None:
"""Wrap a pyarrow Fragment to only deserialize when needed."""
# https://github.com/apache/arrow/issues/40279
self._fragment = fragment
self._fragment_packed = fragment_packed
self._file_size = file_size
self._fs = None
self._filesystem = filesystem
def pack(self):
if self._fragment_packed is None:
part_expr = self._fragment.partition_expression
if part_expr.equals(pc.scalar(True)):
part_expr = True
pqformat = self._fragment.format
if pqformat.read_options.equals(pa_ds.ParquetFileFormat().read_options):
pqformat = None
fs = self._filesystem or self._fragment.filesystem
assert fs.equals(self._fragment.filesystem)
if self._filesystem_pickle_cache[0] != id(fs):
FragmentWrapper._filesystem_pickle_cache = (id(fs), pickle.dumps(fs))
fs_pkl = FragmentWrapper._filesystem_pickle_cache[1]
self._fragment_packed = (
pqformat,
(
self._fragment.path
if self._fragment.buffer is None
else self._fragment.buffer
),
fs_pkl,
part_expr,
self._file_size,
)
self._fs = self._fragment = None
def unpack(self):
if self._fragment is None:
(
pqformat,
path_or_buffer,
fs_raw,
partition_expression,
file_size,
) = self._fragment_packed
fs = FragmentWrapper._filesystems.get(fs_raw)
if fs is None:
fs = pickle.loads(fs_raw)
FragmentWrapper._filesystems[fs_raw] = fs
if partition_expression is True:
partition_expression = pc.scalar(True)
# arrow doesn't keep the python object alive so if we want to reuse
# we need to keep a reference
self._fs = fs
if pqformat is None:
pqformat = pa_ds.ParquetFileFormat()
self._fragment = pqformat.make_fragment(
path_or_buffer,
filesystem=fs,
partition_expression=partition_expression,
file_size=file_size,
)
self._fragment_packed = None
@property
def fragment(self):
self.unpack()
return self._fragment
def __dask_tokenize__(self):
return type(self).__name__, normalize_token(
(
self.fragment,
self._fragment_packed,
self._file_size,
)
)
def __reduce__(self):
self.pack()
return FragmentWrapper, (None, None, None, self._fragment_packed)
def _control_cached_plan(key):
if len(_cached_plan) > _CACHED_PLAN_SIZE and key not in _cached_plan:
key_to_pop = list(_cached_plan.keys())[0]
_cached_plan.pop(key_to_pop)
@normalize_token.register(pa_ds.Dataset)
def normalize_pa_ds(ds):
return (ds.files, ds.schema)
@normalize_token.register(pa_ds.FileFormat)
def normalize_pa_file_format(file_format):
return str(file_format)
@normalize_token.register(pa.Schema)
def normalize_pa_schema(schema):
return schema.to_string()
@normalize_token.register(pq.ParquetSchema)
def normalize_pq_schema(schema):
try:
return hash(schema)
except TypeError: # pyarrow version not supporting ParquetSchema hash
return hash(repr(schema))
@normalize_token.register(pq.FileMetaData)
def normalize_pq_filemetadata(meta):
try:
return hash(meta)
except TypeError:
# pyarrow version not implementing hash for FileMetaData
# use same logic as implemented in version that does support hashing
# https://github.com/apache/arrow/blob/bbe59b35de33a0534fc76c9617aa4746031ce16c/python/pyarrow/_parquet.pyx#L853
return hash(
(
repr(meta.schema),
meta.num_rows,
meta.num_row_groups,
meta.format_version,
meta.serialized_size,
)
)
| FragmentWrapper |
python | doocs__leetcode | solution/1500-1599/1510.Stone Game IV/Solution2.py | {
"start": 0,
"end": 315
} | class ____:
def winnerSquareGame(self, n: int) -> bool:
f = [False] * (n + 1)
for i in range(1, n + 1):
j = 1
while j <= i // j:
if not f[i - j * j]:
f[i] = True
break
j += 1
return f[n]
| Solution |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 98567,
"end": 100504
} | class ____(SingleContinuousDistribution):
_argnames = ('sigma',)
set = Interval(0, oo)
@staticmethod
def check(sigma):
_value_check(sigma > 0, "Scale parameter sigma must be positive.")
def pdf(self, x):
sigma = self.sigma
return x/sigma**2*exp(-x**2/(2*sigma**2))
def _cdf(self, x):
sigma = self.sigma
return 1 - exp(-(x**2/(2*sigma**2)))
def _characteristic_function(self, t):
sigma = self.sigma
return 1 - sigma*t*exp(-sigma**2*t**2/2) * sqrt(pi/2) * (erfi(sigma*t/sqrt(2)) - I)
def _moment_generating_function(self, t):
sigma = self.sigma
return 1 + sigma*t*exp(sigma**2*t**2/2) * sqrt(pi/2) * (erf(sigma*t/sqrt(2)) + 1)
def Rayleigh(name, sigma):
r"""
Create a continuous random variable with a Rayleigh distribution.
Explanation
===========
The density of the Rayleigh distribution is given by
.. math ::
f(x) := \frac{x}{\sigma^2} e^{-x^2/2\sigma^2}
with :math:`x > 0`.
Parameters
==========
sigma : Real number, `\sigma > 0`
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Rayleigh, density, E, variance
>>> from sympy import Symbol
>>> sigma = Symbol("sigma", positive=True)
>>> z = Symbol("z")
>>> X = Rayleigh("x", sigma)
>>> density(X)(z)
z*exp(-z**2/(2*sigma**2))/sigma**2
>>> E(X)
sqrt(2)*sqrt(pi)*sigma/2
>>> variance(X)
-pi*sigma**2/2 + 2*sigma**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Rayleigh_distribution
.. [2] https://mathworld.wolfram.com/RayleighDistribution.html
"""
return rv(name, RayleighDistribution, (sigma, ))
#-------------------------------------------------------------------------------
# Reciprocal distribution --------------------------------------------------------
| RayleighDistribution |
python | kamyu104__LeetCode-Solutions | Python/find-the-duplicate-number.py | {
"start": 29,
"end": 802
} | class ____(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Treat each (key, value) pair of the array as the (pointer, next) node of the linked list,
# thus the duplicated number will be the begin of the cycle in the linked list.
# Besides, there is always a cycle in the linked list which
# starts from the first element of the array.
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
# Time: O(nlogn)
# Space: O(1)
# Binary search method.
| Solution |
python | falconry__falcon | examples/recipes/raw_url_path_wsgi.py | {
"start": 317,
"end": 848
} | class ____:
def on_get(self, req, resp, url):
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)
resp.media = {'url': url}
def on_get_status(self, req, resp, url):
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)
resp.media = {'cached': True}
app = falcon.App(middleware=[RawPathComponent()])
app.add_route('/cache/{url}', URLResource())
app.add_route('/cache/{url}/status', URLResource(), suffix='status')
| URLResource |
python | getsentry__sentry | tests/acceptance/test_quick_start.py | {
"start": 386,
"end": 3710
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.login_as(self.user)
@with_feature("organizations:onboarding")
def test_quick_start_sidebar_is_not_automatically_opened_after_project_creation(self) -> None:
settings.PRIVACY_URL = "https://sentry.io/privacy/"
settings.TERMS_URL = "https://sentry.io/terms/"
self.browser.get("/organizations/new/")
self.browser.element('input[name="name"]').send_keys("new org")
self.browser.element('input[name="agreeTerms"]').click()
self.browser.click('button[type="submit"]')
self.browser.wait_until_test_id("platform-javascript-react")
self.browser.click('[data-test-id="platform-javascript-react"')
self.browser.click('button[aria-label="Create Project"]')
self.browser.wait_until(xpath='//h2[text()="Configure React SDK"]')
assert not self.browser.element_exists_by_test_id("quick-start-content")
@with_feature("organizations:onboarding")
def test_quick_start_not_rendered_because_all_tasks_completed_and_overdue(self) -> None:
# Record tasks with all marked as COMPLETE, all overdue
for task in list(OrganizationOnboardingTask.TASK_KEY_MAP.keys()):
OrganizationOnboardingTask.objects.record(
organization_id=self.organization.id,
task=task,
status=OnboardingTaskStatus.COMPLETE,
date_completed=datetime(year=2024, month=12, day=25, tzinfo=timezone.utc),
)
self.browser.get(f"/organizations/{self.organization.slug}/")
self.browser.wait_until_not('[aria-label="Onboarding"]')
@with_feature("organizations:onboarding")
def test_quick_start_renders_even_when_all_tasks_are_overdue_but_one_is_missing_to_complete(
self,
) -> None:
excluded_required_task = OnboardingTask.FIRST_TRANSACTION
tasks_to_process = list(
OrganizationOnboardingTask.TASK_KEY_MAP.keys() - {excluded_required_task}
)
for task in tasks_to_process:
OrganizationOnboardingTask.objects.record(
organization_id=self.organization.id,
task=task,
status=OnboardingTaskStatus.COMPLETE,
date_completed=datetime(year=2024, month=12, day=25, tzinfo=timezone.utc),
)
self.browser.get(f"/organizations/{self.organization.slug}/")
self.browser.wait_until('[aria-label="Onboarding"]')
@with_feature("organizations:onboarding")
def test_record_works_when_already_exists(self) -> None:
OrganizationOnboardingTask.objects.create(
organization_id=self.organization.id,
task=OnboardingTask.FIRST_TRANSACTION,
status=OnboardingTaskStatus.SKIPPED,
date_completed=datetime(year=2024, month=12, day=25, tzinfo=timezone.utc),
)
assert not OrganizationOnboardingTask.objects.record(
organization_id=self.organization.id,
task=OnboardingTask.FIRST_TRANSACTION,
status=OnboardingTaskStatus.COMPLETE,
date_completed=datetime(year=2024, month=12, day=25, tzinfo=timezone.utc),
)
| OrganizationQuickStartTest |
python | django__django | tests/migrations/test_operations.py | {
"start": 286161,
"end": 290383
} | class ____(SimpleTestCase):
def test_references_model(self):
operation = FieldOperation(
"MoDel", "field", models.ForeignKey("Other", models.CASCADE)
)
# Model name match.
self.assertIs(operation.references_model("mOdEl", "migrations"), True)
# Referenced field.
self.assertIs(operation.references_model("oTher", "migrations"), True)
# Doesn't reference.
self.assertIs(operation.references_model("Whatever", "migrations"), False)
def test_references_field_by_name(self):
operation = FieldOperation("MoDel", "field", models.BooleanField(default=False))
self.assertIs(operation.references_field("model", "field", "migrations"), True)
def test_references_field_by_remote_field_model(self):
operation = FieldOperation(
"Model", "field", models.ForeignKey("Other", models.CASCADE)
)
self.assertIs(
operation.references_field("Other", "whatever", "migrations"), True
)
self.assertIs(
operation.references_field("Missing", "whatever", "migrations"), False
)
def test_references_field_by_from_fields(self):
operation = FieldOperation(
"Model",
"field",
models.fields.related.ForeignObject(
"Other", models.CASCADE, ["from"], ["to"]
),
)
self.assertIs(operation.references_field("Model", "from", "migrations"), True)
self.assertIs(operation.references_field("Model", "to", "migrations"), False)
self.assertIs(operation.references_field("Other", "from", "migrations"), False)
self.assertIs(operation.references_field("Model", "to", "migrations"), False)
def test_references_field_by_to_fields(self):
operation = FieldOperation(
"Model",
"field",
models.ForeignKey("Other", models.CASCADE, to_field="field"),
)
self.assertIs(operation.references_field("Other", "field", "migrations"), True)
self.assertIs(
operation.references_field("Other", "whatever", "migrations"), False
)
self.assertIs(
operation.references_field("Missing", "whatever", "migrations"), False
)
def test_references_field_by_through(self):
operation = FieldOperation(
"Model", "field", models.ManyToManyField("Other", through="Through")
)
self.assertIs(
operation.references_field("Other", "whatever", "migrations"), True
)
self.assertIs(
operation.references_field("Through", "whatever", "migrations"), True
)
self.assertIs(
operation.references_field("Missing", "whatever", "migrations"), False
)
def test_reference_field_by_through_fields(self):
operation = FieldOperation(
"Model",
"field",
models.ManyToManyField(
"Other", through="Through", through_fields=("first", "second")
),
)
self.assertIs(
operation.references_field("Other", "whatever", "migrations"), True
)
self.assertIs(
operation.references_field("Through", "whatever", "migrations"), False
)
self.assertIs(
operation.references_field("Through", "first", "migrations"), True
)
self.assertIs(
operation.references_field("Through", "second", "migrations"), True
)
def test_references_field_by_generated_field(self):
operation = FieldOperation(
"Model",
"field",
models.GeneratedField(
expression=F("foo") + F("bar"),
output_field=models.IntegerField(),
db_persist=True,
),
)
self.assertIs(operation.references_field("Model", "foo", "migrations"), True)
self.assertIs(operation.references_field("Model", "bar", "migrations"), True)
self.assertIs(operation.references_field("Model", "alien", "migrations"), False)
self.assertIs(operation.references_field("Other", "foo", "migrations"), False)
| FieldOperationTests |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 4408,
"end": 6319
} | class ____:
def test_trivial_input(self):
assert all(x.size == 0 for x in _cplxreal([]))
x = _cplxreal(1)
assert x[0].size == 0
xp_assert_equal(x[1], np.asarray([1]))
def test_output_order(self):
zc, zr = _cplxreal(np.roots(array([1, 0, 0, 1])))
xp_assert_close(np.append(zc, zr), [1/2 + 1j*sin(pi/3), -1])
eps = spacing(1)
a = [0+1j, 0-1j, eps + 1j, eps - 1j, -eps + 1j, -eps - 1j,
1, 4, 2, 3, 0, 0,
2+3j, 2-3j,
1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, # sorts out of order
3+1j, 3+1j, 3+1j, 3-1j, 3-1j, 3-1j,
2-3j, 2+3j]
zc, zr = _cplxreal(a)
xp_assert_close(zc, [1j, 1j, 1j, 1+1j, 1+2j, 2+3j, 2+3j, 3+1j, 3+1j,
3+1j])
xp_assert_close(zr, [0.0, 0, 1, 2, 3, 4])
z = array([1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, 1+eps+3j, 1-2*eps-3j,
0+1j, 0-1j, 2+4j, 2-4j, 2+3j, 2-3j, 3+7j, 3-7j, 4-eps+1j,
4+eps-2j, 4-1j, 4-eps+2j])
zc, zr = _cplxreal(z)
xp_assert_close(zc, [1j, 1+1j, 1+2j, 1+3j, 2+3j, 2+4j, 3+7j, 4+1j,
4+2j])
xp_assert_equal(zr, np.asarray([]))
def test_unmatched_conjugates(self):
# 1+2j is unmatched
assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j])
# 1+2j and 1-3j are unmatched
assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j, 1-3j])
# 1+3j is unmatched
assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+3j])
# No pairs
assert_raises(ValueError, _cplxreal, [1+3j])
assert_raises(ValueError, _cplxreal, [1-3j])
def test_real_integer_input(self):
zc, zr = _cplxreal([2, 0, 1, 4])
xp_assert_equal(zc, np.asarray([]))
xp_assert_equal(zr, [0, 1, 2, 4])
@make_xp_test_case(tf2zpk)
| TestCplxReal |
python | huggingface__transformers | src/transformers/models/dinov2/modeling_dinov2.py | {
"start": 10203,
"end": 10930
} | class ____(nn.Module):
"""
The residual connection is defined in Dinov2Layer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config: Dinov2Config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Dinov2
| Dinov2SelfOutput |
python | kamyu104__LeetCode-Solutions | Python/frog-position-after-t-seconds.py | {
"start": 87,
"end": 1136
} | class ____(object):
def frogPosition(self, n, edges, t, target):
"""
:type n: int
:type edges: List[List[int]]
:type t: int
:type target: int
:rtype: float
"""
G = collections.defaultdict(list)
for u, v in edges:
G[u].append(v)
G[v].append(u)
stk = [(t, 1, 0, 1)]
while stk:
new_stk = []
while stk:
t, node, parent, choices = stk.pop()
if not t or not (len(G[node])-(parent != 0)):
if node == target:
return 1.0/choices
continue
for child in G[node]:
if child == parent:
continue
new_stk.append((t-1, child, node,
choices*(len(G[node])-(parent != 0))))
stk = new_stk
return 0.0
# Time: O(n)
# Space: O(n)
# dfs solution with stack with better precision
| Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_detector_types.py | {
"start": 619,
"end": 1710
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
@extend_schema(
operation_id="Fetch Detector Types",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
],
responses={
201: inline_sentry_response_serializer("ListDetectorTypes", list[str]),
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(self, request, organization):
"""
Returns a list of detector types for a given org
"""
type_slugs = [
gt.slug
for gt in grouptype.registry.get_visible(organization)
if gt.detector_settings is not None and gt.detector_settings.handler is not None
]
type_slugs.sort()
return self.paginate(
request=request,
queryset=type_slugs,
paginator_cls=OffsetPaginator,
)
| OrganizationDetectorTypeIndexEndpoint |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/llms/types.py | {
"start": 21929,
"end": 23782
} | class ____(BaseModel):
model_config = ConfigDict(
protected_namespaces=("pydantic_model_",), arbitrary_types_allowed=True
)
context_window: int = Field(
default=DEFAULT_CONTEXT_WINDOW,
description=(
"Total number of tokens the model can be input and output for one response."
),
)
num_output: int = Field(
default=DEFAULT_NUM_OUTPUTS,
description="Number of tokens the model can output when generating a response.",
)
is_chat_model: bool = Field(
default=False,
description=(
"Set True if the model exposes a chat interface (i.e. can be passed a"
" sequence of messages, rather than text), like OpenAI's"
" /v1/chat/completions endpoint."
),
)
is_function_calling_model: bool = Field(
default=False,
# SEE: https://openai.com/blog/function-calling-and-other-api-updates
description=(
"Set True if the model supports function calling messages, similar to"
" OpenAI's function calling API. For example, converting 'Email Anya to"
" see if she wants to get coffee next Friday' to a function call like"
" `send_email(to: string, body: string)`."
),
)
model_name: str = Field(
default="unknown",
description=(
"The model's name used for logging, testing, and sanity checking. For some"
" models this can be automatically discerned. For other models, like"
" locally loaded models, this must be manually specified."
),
)
system_role: MessageRole = Field(
default=MessageRole.SYSTEM,
description="The role this specific LLM provider"
"expects for system prompt. E.g. 'SYSTEM' for OpenAI, 'CHATBOT' for Cohere",
)
| LLMMetadata |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 17929,
"end": 18014
} | class ____(IdxMin):
groupby_chunk = M.idxmax
groupby_aggregate = M.first
| IdxMax |
python | ijl__orjson | test/test_default.py | {
"start": 302,
"end": 530
} | class ____:
def __init__(self, cur):
self.cur = cur
def default_recursive(obj):
if obj.cur != 0:
obj.cur -= 1
return obj
return obj.cur
def default_raises(obj):
raise TypeError
| Recursive |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/types.py | {
"start": 191,
"end": 395
} | class ____(TypedDict):
train_data: torch.Tensor
train_labels: torch.Tensor
val_data: torch.Tensor
val_labels: torch.Tensor
test_data: torch.Tensor
test_labels: torch.Tensor
| DataBatch |
python | google__pytype | pytype/constant_folding_test.py | {
"start": 899,
"end": 6129
} | class ____(test_base.UnitTest):
"""Tests for FoldConstant."""
def _compile(self, src, mode="exec"):
exe = (["python" + ".".join(map(str, self.python_version))], [])
pyc_data = compiler.compile_src_string_to_pyc_string(
src,
filename="test_input.py",
python_version=self.python_version,
python_exe=exe,
mode=mode,
)
code = pyc.parse_pyc_string(pyc_data)
code, _ = blocks.process_code(code)
return code
def _find_load_folded(self, code):
out = []
for block in code.order:
out.extend([x for x in block if isinstance(x, opcodes.LOAD_FOLDED_CONST)])
return out
def _fold(self, code):
code = constant_folding.fold_constants(code)
folded = self._find_load_folded(code)
actual = [show_op(op) for op in folded]
return actual
def _process(self, src):
src = fmt(src)
code = self._compile(src)
actual = self._fold(code)
return actual
def check_folding_error(self, src):
with self.assertRaises(constant_folding.ConstantError):
self._process(src)
def test_basic(self):
actual = self._process("a = [1, 2, 3]")
self.assertCountEqual(
actual, [(1, ("list", int), [1, 2, 3], [int, int, int])]
)
def test_union(self):
actual = self._process("a = [1, 2, '3']")
self.assertCountEqual(
actual, [(1, ("list", (int, str)), [1, 2, "3"], [int, int, str])]
)
def test_str_to_list(self):
actual = self._process("a = [*'abc']")
self.assertCountEqual(
actual, [(1, ("list", str), ["a", "b", "c"], [str, str, str])]
)
def test_bad_extend(self):
with self.assertRaises(constant_folding.ConstantError):
self._process("a = [1, 2, *3]")
def test_map(self):
actual = self._process("a = {'x': 1, 'y': '2'}")
self.assertCountEqual(
actual,
[(
1,
("map", str, (int, str)),
{"x": 1, "y": "2"},
{"x": int, "y": str},
)],
)
def test_tuple(self):
actual = self._process("a = (1, '2', True)")
# Tuples are already a single LOAD_CONST operation and so don't get folded
self.assertCountEqual(actual, [])
def test_list_of_tuple(self):
actual = self._process("a = [(1, '2', 3), (4, '5', 6)]")
val = [(1, "2", 3), (4, "5", 6)]
elements = [("tuple", int, str, int), ("tuple", int, str, int)]
self.assertCountEqual(
actual, [(1, ("list", ("tuple", int, str, int)), val, elements)]
)
def test_list_of_varied_tuple(self):
actual = self._process("a = [(1, '2', 3), ('4', '5', 6)]")
val = [(1, "2", 3), ("4", "5", 6)]
elements = [("tuple", int, str, int), ("tuple", str, str, int)]
self.assertCountEqual(
actual,
[(
1,
("list", (("tuple", int, str, int), ("tuple", str, str, int))),
val,
elements,
)],
)
def test_nested(self):
actual = self._process("""
a = {
'x': [(1, '2', 3), ('4', '5', 6)],
'y': [{'a': 'b'}, {'c': 'd'}],
('p', 'q'): 'r'
}
""")
val = {
"x": [(1, "2", 3), ("4", "5", 6)],
"y": [{"a": "b"}, {"c": "d"}],
("p", "q"): "r",
}
x = ("list", (("tuple", int, str, int), ("tuple", str, str, int)))
y = ("list", ("map", str, str))
k = (("tuple", str, str), str)
elements = {"x": x, "y": y, ("p", "q"): str}
self.assertCountEqual(actual, [(1, ("map", k, (y, x, str)), val, elements)])
def test_partial(self):
actual = self._process("""
x = 1
a = {
"x": x,
"y": [{"a": "b"}, {"c": "d"}],
}
""")
val = [{"a": "b"}, {"c": "d"}]
map_type = ("map", str, str)
self.assertCountEqual(
actual, [(4, ("list", map_type), val, [map_type, map_type])]
)
def test_nested_partial(self):
# Test that partial expressions get cleaned off the stack properly. The 'if'
# is there to introduce block boundaries.
actual = self._process("""
v = None
x = {
[{'a': 'c', 'b': v}],
[{'a': 'd', 'b': v}]
}
if __random__:
y = [{'value': v, 'type': 'a'}]
else:
y = [{'value': v, 'type': 'b'}]
""")
self.assertCountEqual(actual, [])
def test_function_call(self):
actual = self._process("""
a = {
'name': 'x'.isascii(),
'type': 'package',
'foo': sorted(set())
}
""")
self.assertCountEqual(actual, [])
def test_fstring(self):
actual = self._process("""
x = 'hello'
y = set(1, 2, 3)
a = f'foo{x}{y}' # Not folded
b = f'foo{0:08}' # Folded
c = f'foo{x:<9}' # Not folded
d = f'foo{x:}' # Internal empty string after : folded
e = f'foo{x:0{8}x}' # Internal subsection '0{8}x' folded
f = f'{x:05}.a' # Not folded
g = f'pre.{x:05}.post' # Not folded
""")
self.assertCountEqual(actual, [(x, str, "", None) for x in (4, 6, 7)])
def test_errors(self):
# Check that malformed constants raise a ConstantFoldingError rather than
# crash pytype.
self.check_folding_error("{[1, 2]}")
self.check_folding_error("[*42]")
self.check_folding_error("{**42}")
| TestFolding |
python | automl__auto-sklearn | test/test_automl/automl_utils.py | {
"start": 2893,
"end": 9280
} | class ____(object):
def __init__(self, logfile: str):
self.logfile = logfile
self.lines = self.parse_logfile()
def parse_logfile(self) -> typing.List[str]:
# We care about the [debug/info/...] messages
# At the time of writing, the message format was:
# [DEBUG] [2020-11-30 11:54:05,072:EnsembleBuilder] Restricting your
# function to 3072 mb memory.
#
# [DEBUG] [2020-11-30 11:53:55,062:pynisher] Redirecting
# output of the function to files.
assert os.path.exists(self.logfile), "{} not found".format(self.logfile)
with open(self.logfile) as fh:
content = [line.strip() for line in fh if re.search(r"[\w+]", line)]
return content
def count_ensembler_iterations(self) -> int:
iterations = []
# One thing is to call phynisher, the other is to actually execute the funciton
iterations_from_inside_ensemble_builder = []
for line in self.lines:
# Pynisher call
# we have to count the start msg from pynisher
# and the return msg
# We expect the start msg to be something like:
# [DEBUG] [2020-11-26 19:22:42,160:EnsembleBuilder] \
# Function called with argument: (61....
# [DEBUG] [2020-11-30 11:53:47,069:EnsembleBuilder] \
# Function called with argument: (28.246965646743774, 1, False), {}
match = re.search(
r"EnsembleBuilder]\s+Function called with argument:\s+\(\d+\.\d+, (\d+), \w+", # noqa: E501
line,
)
if match:
iterations.append(int(match.group(1)))
# Ensemble Builder actual call
# Here we expect the msg:
# [DEBUG] [2020-11-30 11:53:14,877:EnsembleBuilder] Starting iteration 0,
# time left: 61.266255
# [DEBUG] [2020-11-27 20:27:28,044:EnsembleBuilder] Starting iteration 2,
# time left: 10.603252
match = re.search(r"EnsembleBuilder]\s+Starting iteration (\d+)", line)
if match:
iterations_from_inside_ensemble_builder.append(int(match.group(1)))
# The ensemble builder might not be called if there is no time.
# Here we expect the msg:
# [DEBUG] [2020-11-27 20:27:28,044:EnsembleBuilder] \
# Not starting iteration 2, as time left: 1.59324
match = re.search(r"EnsembleBuilder]\s+Not starting iteration (\d+)", line)
if match:
iterations_from_inside_ensemble_builder.append(int(match.group(1)))
assert iterations == iterations_from_inside_ensemble_builder, "{} ! {}".format(
iterations, iterations_from_inside_ensemble_builder
)
return iterations
def count_ensembler_success_pynisher_calls(self) -> int:
# We expect the return msg to be something like:
# [DEBUG] [2020-11-30 11:53:47,911:EnsembleBuilder] return value:
# (([{'Timestamp': Timestamp('2020-11-30 11:53:47.910727'),
# 'ensemble_optimization_score': 0.9787234042553191}], 50, None, None, None), 0)
# [DEBUG] [2020-11-30 11:54:05,984:EnsembleBuilder] return value:
# (([{'Timestamp': Timestamp('2020-11- 30 11:54:05.983837'),
# 'ensemble_optimization_score': 0.9787234042553191}], 50, None, None, None), 0)
return_msgs = len(
[
line
for line in self.lines
if re.search(r"EnsembleBuilder]\s+return value:.*Timestamp", line)
]
)
return return_msgs
def count_tae_pynisher_calls(self) -> int:
# We expect the return msg to be something like:
"""
[DEBUG] [2020-12-16 11:57:08,987:Client-pynisher] Function called with argument: (),
{'queue': <multiprocessing.queues.Queue object at 0x7f9e3cfaae20>, 'config': 1
[DEBUG] [2020-12-16 11:57:10,537:Client-pynisher] Function called with argument: (),
{'queue': <multiprocessing.queues.Queue object at 0x7f16f5d95c40>, 'config': Configuration:
""" # noqa: E501
# Only the parenthesis below need to be escaped, ] and { do not.
call_msgs = len(
[
line
for line in self.lines
if re.search(
r"pynisher]\s+Function called with argument: \(\), {", line
)
]
)
return call_msgs
def count_tae_pynisher_returns(self) -> int:
# We expect the return msg to be something like:
# [DEBUG] [2020-11-30 11:53:11,264:pynisher] return value: (None, 0)
# [DEBUG] [2020-11-30 11:53:13,768:pynisher] return value: (None, 0)
return_msgs = len(
[
line
for line in self.lines
if re.search(r"pynisher]\s+return value:\s+", line)
]
)
# When the pynisher pipe is prematurely closed, we also expect:
# Your function call closed the pipe prematurely
# -> Subprocess probably got an uncatchable signal
# We expect the return msg to be something like:
# OR
# Something else went wrong, sorry.
premature_msgs = len(
[
line
for line in self.lines
if re.search(
r"pynisher]\s+Your function call closed the pipe prematurely", line
)
]
)
failure_msgs = len(
[
line
for line in self.lines
if re.search(r"pynisher]\s+Something else went wrong, sorry.", line)
]
)
return return_msgs + premature_msgs + failure_msgs
def get_automl_setting_from_log(self, dataset_name: str, setting: str) -> str:
for line in self.lines:
# We expect messages of the form
"""
[DEBUG] [2020-11-30 11:53:10,457:AutoML(5):breast_cancer] ensemble_size: 50
[DEBUG] [2020-11-30 11:53:10,457:AutoML(5):breast_cancer] ensemble_nbest: 50
""" # noqa: E501
match = re.search(f"{dataset_name}]\\s*{setting}\\s*:\\s*(\\w+)", line)
if match:
return match.group(1)
return None
| AutoMLLogParser |
python | google__jax | jax/_src/linear_util.py | {
"start": 10050,
"end": 20153
} | class ____(NamedTuple):
"""Debugging info about a func, its arguments, and results."""
traced_for: str # e.g. 'jit', 'scan', etc
func_src_info: str
"""e.g. f'{fun.__name__} at {filename}:{lineno}' or {fun.__name__} if we have
no source location information. The first word is always the function name,
which may be '<unknown>'.
"""
arg_names: tuple[str, ...] | None
"""The paths of the flattened non-static argnames,
e.g. `('x', 'dict_arg["a"]', ... )`.
Uses the empty string for the args that do not correspond to
user-named arguments, e.g., tangent args in `jax.jvp`, or for arguments that
we are not yet tracking properly. The value `None` denotes argument names.
At the moment, `arg_names` accuracy is best-effort.
Use `safe_arg_names` to detect and handle an unexpected
number of elements in `arg_names`.
"""
result_paths: tuple[str, ...] | InitialResultPaths | Callable[[], tuple[str, ...]] | None
"""The paths to the flattened results, e.g., `('result[0]', result[1])` for a
function that returns a tuple of arrays, or `(result,)` for a function that
returns a single array. The value `None` denotes unknown paths.
When we first create a `DebugInfo`, we may use the value
`initial_result_paths`, which we replace with a thunk when we put the
debug info into a `lu.WrappedFun`, before we start tracing. After tracing,
we call `self.resolve_result_paths()` to execute the thunk and replace
the result paths with a tuple.
Use `safe_result_paths` to detect and handle an unexpected
number of elements in `result_paths`.
"""
def resolve_result_paths(self) -> DebugInfo:
"""Return a debug info with resolved result paths."""
assert self.result_paths is not initial_result_paths
if callable(self.result_paths):
paths = tuple(self.result_paths())
return self._replace(result_paths=paths)
return self
@property
def func_name(self) -> str:
return self.func_src_info.split(" ")[0]
def replace_func_name(self, name: str) -> DebugInfo:
func_src_comps = self.func_src_info.split(" ")
func_src_comps[0] = name
return self._replace(func_src_info=" ".join(func_src_comps))
def set_result_paths(self, ans):
result_paths = tuple(f"result{_clean_keystr_arg_names(path)}"
for path, _ in generate_key_paths(ans))
return self._replace(result_paths=result_paths)
@property
def func_filename(self) -> str | None:
m = _re_func_src_info.match(self.func_src_info)
if not m: return None
return m.group(3)
@property
def func_lineno(self) -> int | None:
m = _re_func_src_info.match(self.func_src_info)
if not m or m.group(4) is None: return None
return int(m.group(4))
def safe_arg_names(self, expected_count: int) -> tuple[str, ...]:
"""Get the arg_names with a safety check."""
self.assert_arg_names(expected_count)
if self.arg_names is not None:
return self.arg_names
return ("",) * expected_count
def assert_arg_names(self, expected_count: int):
assert self.arg_names is None or len(self.arg_names) == expected_count, (
expected_count, self)
def filter_arg_names(self, keep: Sequence[bool]) -> tuple[str, ...] | None:
"""Keep only the arg_names for which `keep` is True."""
if self.arg_names is None:
return None
return tuple(v for v, b in zip(self.safe_arg_names(len(keep)), keep) if b)
def safe_result_paths(self, expected_count: int) -> tuple[str, ...]:
"""Get the result paths with a safety check. Empty paths mean unknown."""
assert self.result_paths is not initial_result_paths and not callable(self.result_paths), self
self.assert_result_paths(expected_count)
if self.result_paths is not None:
return self.result_paths # type: ignore
return ("",) * expected_count
def assert_result_paths(self, expected_count: int):
assert self.result_paths is None or len(self.result_paths) == expected_count, ( # type: ignore
expected_count, self)
def filter_result_paths(self, keep: Sequence[bool]) -> tuple[str, ...] | None:
"""Keep only the result_paths for which `keep` is True."""
assert self.result_paths is not initial_result_paths and not callable(self.result_paths), self
if self.result_paths is None: return None
return tuple(v for v, b in zip(self.result_paths, keep) if b) # type: ignore
def with_unknown_names(self) -> DebugInfo:
return self._replace(arg_names=None, result_paths=None)
_re_func_src_info = re.compile(r"([^ ]+)( at (.+):(\d+))?$")
def _missing_debug_info(for_what: str) -> DebugInfo:
warnings.warn(
f"{for_what} is missing a DebugInfo object. "
"This behavior is deprecated, use api_util.debug_info() to "
"construct a proper DebugInfo object and propagate it to this function. "
"See https://github.com/jax-ml/jax/issues/26480 for more details.",
DeprecationWarning, stacklevel=2)
return DebugInfo("missing_debug_info", "<missing_debug_info>", None, None)
def wrap_init(f: Callable, params=None, *, debug_info: DebugInfo) -> WrappedFun:
"""Wraps function `f` as a `WrappedFun`, suitable for transformation."""
params_dict = {} if params is None else params
params = () if params is None else tuple(sorted(params.items()))
fun = WrappedFun(f, partial(f, **params_dict), (), (), params, None, debug_info)
if debug_info.result_paths is initial_result_paths:
fun, result_paths_thunk = _get_result_paths_thunk(fun)
debug_info = debug_info._replace(
result_paths=HashableFunction(result_paths_thunk, closure=()))
fun = WrappedFun(fun.f, fun.f_transformed, fun.transforms, fun.stores,
fun.params, fun.in_type, debug_info)
return fun
# We replace <flat index 0> with 0
_re_clean_keystr_arg_names = re.compile(r"<flat index ([^>]+)>")
def _clean_keystr_arg_names(k: KeyPath) -> str:
res = keystr(k)
return _re_clean_keystr_arg_names.sub(r"\1", res)
@transformation_with_aux2
def _get_result_paths_thunk(_fun: Callable, _store: Store, *args, **kwargs):
ans = _fun(*args, **kwargs)
result_paths = tuple(f"result{_clean_keystr_arg_names(path)}" for path, _ in generate_key_paths(ans))
if _store:
# In some instances a lu.WrappedFun is called multiple times, e.g.,
# the bwd function in a custom_vjp
assert _store.val == result_paths, (_store, result_paths)
else:
_store.store(result_paths)
return ans
def annotate(f: WrappedFun, in_type: core.InputType | None) -> WrappedFun:
assert f.in_type is None
if in_type is None:
return f
_check_input_type(in_type)
return WrappedFun(f.f, f.f_transformed, f.transforms, f.stores, f.params, in_type, f.debug_info)
def _check_input_type(in_type: core.InputType) -> None:
# Check that in_type is syntactically well-formed
assert type(in_type) is tuple and all(type(e) is tuple for e in in_type)
assert all(isinstance(a, core.AbstractValue) and type(b) is bool
for a, b in in_type)
def valid_size(d) -> bool:
if isinstance(d, core.DBIdx) and type(d.val) is int and d.val >= 0:
return True
return (isinstance(d, (int, core.DBIdx, core.DArray)) and
(not isinstance(d, core.DArray) or type(d) is core.bint and not d.shape))
assert all(valid_size(d) for a, _ in in_type if type(a) is core.DShapedArray
for d in a.shape)
# Check that all DBIdx point to positions to the left of the input on which
# they appear.
assert all(d.val < i for i, (aval, _) in enumerate(in_type)
if isinstance(aval, core.DShapedArray) for d in aval.shape
if isinstance(d, core.DBIdx))
# Check that all implicit arguments have at least one DBIdx pointing to them.
provided = [e for _, e in in_type]
for aval, _ in in_type:
if type(aval) is core.DShapedArray:
for d in aval.shape:
if isinstance(d, core.DBIdx):
provided[d.val] = True
assert all(provided)
def cache(call: Callable, *,
explain: Callable[[WrappedFun, bool, dict, tuple, float], None] | None = None):
"""Memoization decorator for functions taking a WrappedFun as first argument.
Args:
call: a Python callable that takes a WrappedFun as its first argument. The
underlying transforms and params on the WrappedFun are used as part of the
memoization cache key.
explain: a function that is invoked upon cache misses to log an explanation
of the miss.
Invoked with `(fun, is_cache_first_use, cache, key, elapsed_sec)`.
Returns:
A memoized version of ``call``.
"""
fun_caches: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
def memoized_fun(fun: WrappedFun, *args):
cache = fun_caches.setdefault(fun.f, new_cache := {}) # type: ignore
key = (fun.transforms, fun.params, fun.in_type, args, config.trace_context())
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
if do_explain := explain and config.explain_cache_misses.value:
start = time.time()
ans = call(fun, *args)
if do_explain:
explain(fun, cache is new_cache, cache, key, time.time() - start) # type: ignore
cache[key] = (ans, fun.stores)
return ans
def _evict_function(f):
fun_caches.pop(f, None)
memoized_fun.cache_clear = fun_caches.clear # type: ignore
memoized_fun.evict_function = _evict_function # type: ignore
register_cache(memoized_fun, str(call))
return memoized_fun
@transformation2
def hashable_partial(f, *args):
return f(*args)
def merge_linear_aux(aux1, aux2):
try:
out1 = aux1()
except StoreException:
# store 1 was not occupied, so store 2 better be
try:
out2 = aux2()
except StoreException:
raise StoreException("neither store occupied") from None
else:
return False, out2
else:
# store 1 was occupied, so let's check store 2 is not occupied
try:
out2 = aux2()
except StoreException:
return True, out1
else:
raise StoreException("both stores occupied")
| DebugInfo |
python | Netflix__metaflow | metaflow/_vendor/click/types.py | {
"start": 12951,
"end": 13373
} | class ____(ParamType):
name = "uuid"
def convert(self, value, param, ctx):
import uuid
try:
if PY2 and isinstance(value, text_type):
value = value.encode("ascii")
return uuid.UUID(value)
except ValueError:
self.fail("{} is not a valid UUID value".format(value), param, ctx)
def __repr__(self):
return "UUID"
| UUIDParameterType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.