uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26c3f613f674abf7923810e7 | train | class | class SHA1:
digester: DataDigester = S1()
@staticmethod
def digest(data: bytes) -> bytes:
assert SHA1.digester is not None, 'SHA1 coder not set yet'
return SHA1.digester.digest(data=data)
| class SHA1:
| digester: DataDigester = S1()
@staticmethod
def digest(data: bytes) -> bytes:
assert SHA1.digester is not None, 'SHA1 coder not set yet'
return SHA1.digester.digest(data=data)
| ()
class MD5:
digester: DataDigester = M5()
@staticmethod
def digest(data: bytes) -> bytes:
assert MD5.digester is not None, 'MD5 coder not set yet'
return MD5.digester.digest(data=data)
class SHA1:
| 64 | 64 | 59 | 4 | 60 | dimchat/mkm-py | mkm/crypto/digest.py | Python | SHA1 | SHA1 | 115 | 121 | 115 | 115 | 50010ba7c79d4bbedccad4b4139546170717e159 | bigcode/the-stack | train |
c4b44beacb88a4aa092ed5c2 | train | class | class KECCAK256:
digester: DataDigester = None
@staticmethod
def digest(data: bytes) -> bytes:
assert KECCAK256.digester is not None, 'KECCAK256 coder not set yet'
return KECCAK256.digester.digest(data=data)
| class KECCAK256:
| digester: DataDigester = None
@staticmethod
def digest(data: bytes) -> bytes:
assert KECCAK256.digester is not None, 'KECCAK256 coder not set yet'
return KECCAK256.digester.digest(data=data)
| SHA256:
digester: DataDigester = S256()
@staticmethod
def digest(data: bytes) -> bytes:
assert SHA256.digester is not None, 'SHA256 coder not set yet'
return SHA256.digester.digest(data=data)
class KECCAK256:
| 64 | 64 | 66 | 6 | 58 | dimchat/mkm-py | mkm/crypto/digest.py | Python | KECCAK256 | KECCAK256 | 133 | 139 | 133 | 133 | 7ebce238898768484606533240caeb36d1931256 | bigcode/the-stack | train |
94c3b32e792b467a200fa707 | train | function | def md5(data: bytes) -> bytes:
return MD5.digest(data=data)
| def md5(data: bytes) -> bytes:
| return MD5.digest(data=data)
| 5, SHA-256, RipeMD-160
"""
import hashlib
from abc import abstractmethod
class DataDigester:
@abstractmethod
def digest(self, data: bytes) -> bytes:
raise NotImplemented
"""
Interfaces
"""
def md5(data: bytes) -> bytes:
| 64 | 64 | 18 | 10 | 54 | dimchat/mkm-py | mkm/crypto/digest.py | Python | md5 | md5 | 49 | 50 | 49 | 49 | 348827ec333e05f0e7dad20bdcfff5170f541a60 | bigcode/the-stack | train |
3189b336fd22527bb5d32a61 | train | class | class RIPEMD160:
digester: DataDigester = R160()
@staticmethod
def digest(data: bytes) -> bytes:
assert RIPEMD160.digester is not None, 'RIPEMD160 coder not set yet'
return RIPEMD160.digester.digest(data=data)
| class RIPEMD160:
| digester: DataDigester = R160()
@staticmethod
def digest(data: bytes) -> bytes:
assert RIPEMD160.digester is not None, 'RIPEMD160 coder not set yet'
return RIPEMD160.digester.digest(data=data)
| ester: DataDigester = None
@staticmethod
def digest(data: bytes) -> bytes:
assert KECCAK256.digester is not None, 'KECCAK256 coder not set yet'
return KECCAK256.digester.digest(data=data)
class RIPEMD160:
| 64 | 64 | 67 | 6 | 58 | dimchat/mkm-py | mkm/crypto/digest.py | Python | RIPEMD160 | RIPEMD160 | 142 | 148 | 142 | 142 | c7c8e02a1b735181cbbca126a8224c9fa498b8e1 | bigcode/the-stack | train |
e74e872c2d97b717c705a9d3 | train | class | class M5(DataDigester):
def digest(self, data: bytes) -> bytes:
""" MD5 digest """
hash_obj = hashlib.md5()
hash_obj.update(data)
return hash_obj.digest()
| class M5(DataDigester):
| def digest(self, data: bytes) -> bytes:
""" MD5 digest """
hash_obj = hashlib.md5()
hash_obj.update(data)
return hash_obj.digest()
| :
return SHA256.digest(data=data)
def keccak256(data: bytes) -> bytes:
return KECCAK256.digest(data=data)
def ripemd160(data: bytes) -> bytes:
return RIPEMD160.digest(data=data)
"""
Implementations
"""
class M5(DataDigester):
| 64 | 64 | 45 | 7 | 57 | dimchat/mkm-py | mkm/crypto/digest.py | Python | M5 | M5 | 74 | 80 | 74 | 75 | e129b56b54e2f7ecec3ac924595aac7df189edc6 | bigcode/the-stack | train |
c38ce7509e0c09212710dd70 | train | class | @dataclass(eq=False, repr=False)
class DeleteCredentialTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
| @dataclass(eq=False, repr=False)
class DeleteCredentialTemplateRequest(betterproto.Message):
| id: str = betterproto.string_field(1)
| proto.Message):
templates: List["TemplateData"] = betterproto.message_field(1)
has_more_results: bool = betterproto.bool_field(2)
continuation_token: str = betterproto.string_field(3)
@dataclass(eq=False, repr=False)
class DeleteCredentialTemplateRequest(betterproto.Message):
| 64 | 64 | 30 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | DeleteCredentialTemplateRequest | DeleteCredentialTemplateRequest | 56 | 58 | 56 | 57 | e6b164d8a0777fd46373d032fb66b53cff53459c | bigcode/the-stack | train |
ef946dd2d12bf24c459f1202 | train | class | @dataclass(eq=False, repr=False)
class CreateCredentialTemplateResponse(betterproto.Message):
data: "TemplateData" = betterproto.message_field(1)
| @dataclass(eq=False, repr=False)
class CreateCredentialTemplateResponse(betterproto.Message):
| data: "TemplateData" = betterproto.message_field(1)
| fields: Dict[str, "TemplateField"] = betterproto.map_field(
2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
allow_additional_fields: bool = betterproto.bool_field(3)
@dataclass(eq=False, repr=False)
class CreateCredentialTemplateResponse(betterproto.Message):
| 64 | 64 | 33 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | CreateCredentialTemplateResponse | CreateCredentialTemplateResponse | 77 | 79 | 77 | 78 | ce026cf25b787380f749242ace593c4606e691ba | bigcode/the-stack | train |
40d86cbfbdb983b78ff71986 | train | class | @dataclass(eq=False, repr=False)
class SearchCredentialTemplatesResponse(betterproto.Message):
items_json: str = betterproto.string_field(1)
has_more: bool = betterproto.bool_field(2)
count: int = betterproto.int32_field(3)
continuation_token: str = betterproto.string_field(4)
| @dataclass(eq=False, repr=False)
class SearchCredentialTemplatesResponse(betterproto.Message):
| items_json: str = betterproto.string_field(1)
has_more: bool = betterproto.bool_field(2)
count: int = betterproto.int32_field(3)
continuation_token: str = betterproto.string_field(4)
| (1)
@dataclass(eq=False, repr=False)
class SearchCredentialTemplatesRequest(betterproto.Message):
query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
@dataclass(eq=False, repr=False)
class SearchCredentialTemplatesResponse(betterproto.Message):
| 64 | 64 | 70 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | SearchCredentialTemplatesResponse | SearchCredentialTemplatesResponse | 35 | 40 | 35 | 36 | 34bf20b07d04d1b6145f65a468c55415e891d9dd | bigcode/the-stack | train |
e7885d6336717269aea55a1b | train | class | @dataclass(eq=False, repr=False)
class ListCredentialTemplatesRequest(betterproto.Message):
query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
| @dataclass(eq=False, repr=False)
class ListCredentialTemplatesRequest(betterproto.Message):
| query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
| betterproto.string_field(1)
has_more: bool = betterproto.bool_field(2)
count: int = betterproto.int32_field(3)
continuation_token: str = betterproto.string_field(4)
@dataclass(eq=False, repr=False)
class ListCredentialTemplatesRequest(betterproto.Message):
| 64 | 64 | 43 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | ListCredentialTemplatesRequest | ListCredentialTemplatesRequest | 43 | 46 | 43 | 44 | 27fb22d49de1f85bedf94cb5973a707d2046bf58 | bigcode/the-stack | train |
367264d70ea354344614b472 | train | class | @dataclass(eq=False, repr=False)
class GetCredentialTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
| @dataclass(eq=False, repr=False)
class GetCredentialTemplateRequest(betterproto.Message):
| id: str = betterproto.string_field(1)
| .grpclib_server import ServiceBase
import grpclib
class FieldType(betterproto.Enum):
STRING = 0
NUMBER = 1
BOOL = 2
DATETIME = 4
@dataclass(eq=False, repr=False)
class GetCredentialTemplateRequest(betterproto.Message):
| 64 | 64 | 30 | 18 | 45 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | GetCredentialTemplateRequest | GetCredentialTemplateRequest | 19 | 21 | 19 | 20 | cdde9ce6b247ffe72221a4a20a6648db7f96a3b3 | bigcode/the-stack | train |
fc6a47a7543ae41aef0872be | train | class | @dataclass(eq=False, repr=False)
class GetTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
| @dataclass(eq=False, repr=False)
class GetTemplateRequest(betterproto.Message):
| id: str = betterproto.string_field(1)
| class TemplateField(betterproto.Message):
description: str = betterproto.string_field(2)
optional: bool = betterproto.bool_field(3)
type: "FieldType" = betterproto.enum_field(4)
@dataclass(eq=False, repr=False)
class GetTemplateRequest(betterproto.Message):
| 64 | 64 | 29 | 17 | 47 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | GetTemplateRequest | GetTemplateRequest | 89 | 91 | 89 | 90 | 32100cf4c4a4d8cb879b1a20d4bb8aa4ceea2762 | bigcode/the-stack | train |
99904617cd136cc79a8de4c9 | train | class | class CredentialTemplatesBase(ServiceBase):
async def create(
self,
name: str,
fields: Dict[str, "TemplateField"],
allow_additional_fields: bool,
) -> "CreateCredentialTemplateResponse":
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
async def get(self, ... | class CredentialTemplatesBase(ServiceBase):
| async def create(
self,
name: str,
fields: Dict[str, "TemplateField"],
allow_additional_fields: bool,
) -> "CreateCredentialTemplateResponse":
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
async def get(self, id: str) -> "GetCredentialTemplateResponse":... | async def list(
self, *, query: str = "", continuation_token: str = ""
) -> "ListCredentialTemplatesResponse":
request = ListCredentialTemplatesRequest()
request.query = query
request.continuation_token = continuation_token
return await self._unary_unary(
"/ser... | 253 | 253 | 844 | 7 | 246 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | CredentialTemplatesBase | CredentialTemplatesBase | 195 | 306 | 195 | 195 | a2c4791929db79680402eef46ff5c23265f680eb | bigcode/the-stack | train |
bb85ea01d86403bdf920fc0b | train | class | class CredentialTemplatesStub(betterproto.ServiceStub):
async def create(
self,
*,
name: str = "",
fields: Dict[str, "TemplateField"] = None,
allow_additional_fields: bool = False,
) -> "CreateCredentialTemplateResponse":
request = CreateCredentialTemplateRequest... | class CredentialTemplatesStub(betterproto.ServiceStub):
| async def create(
self,
*,
name: str = "",
fields: Dict[str, "TemplateField"] = None,
allow_additional_fields: bool = False,
) -> "CreateCredentialTemplateResponse":
request = CreateCredentialTemplateRequest()
request.name = name
request.fields = ... | name: str = betterproto.string_field(2)
version: int = betterproto.int32_field(3)
fields: Dict[str, "TemplateField"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
allow_additional_fields: bool = betterproto.bool_field(5)
schema_uri: str = betterproto.string... | 132 | 132 | 442 | 10 | 122 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | CredentialTemplatesStub | CredentialTemplatesStub | 124 | 192 | 124 | 124 | ace472dfb53e52097f4252c192cc1496bd81ebb3 | bigcode/the-stack | train |
f49f17f0c97480f2879bbc15 | train | class | @dataclass(eq=False, repr=False)
class SearchCredentialTemplatesRequest(betterproto.Message):
query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
| @dataclass(eq=False, repr=False)
class SearchCredentialTemplatesRequest(betterproto.Message):
| query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
| ):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class GetCredentialTemplateResponse(betterproto.Message):
template: "TemplateData" = betterproto.message_field(1)
@dataclass(eq=False, repr=False)
class SearchCredentialTemplatesRequest(betterproto.Message):
| 64 | 64 | 43 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | SearchCredentialTemplatesRequest | SearchCredentialTemplatesRequest | 29 | 32 | 29 | 30 | 62245e749afcd17fe65681c78dbc27395b56250b | bigcode/the-stack | train |
3812504f12c82f698b08f880 | train | class | @dataclass(eq=False, repr=False)
class ListTemplatesResponse(betterproto.Message):
templates: List["TemplateData"] = betterproto.message_field(1)
| @dataclass(eq=False, repr=False)
class ListTemplatesResponse(betterproto.Message):
| templates: List["TemplateData"] = betterproto.message_field(1)
| repr=False)
class GetTemplateResponse(betterproto.Message):
data: "TemplateData" = betterproto.message_field(1)
@dataclass(eq=False, repr=False)
class ListTemplatesRequest(betterproto.Message):
pass
@dataclass(eq=False, repr=False)
class ListTemplatesResponse(betterproto.Message):
| 64 | 64 | 33 | 17 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | ListTemplatesResponse | ListTemplatesResponse | 104 | 106 | 104 | 105 | 5c5c5ba4310321132be74e92af35eccb5387bbbf | bigcode/the-stack | train |
8bd21eddb70abd25caecfda7 | train | class | class FieldType(betterproto.Enum):
STRING = 0
NUMBER = 1
BOOL = 2
DATETIME = 4
| class FieldType(betterproto.Enum):
| STRING = 0
NUMBER = 1
BOOL = 2
DATETIME = 4
| sources: services/verifiable-credentials/templates/v1/templates.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import Dict, List
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
class FieldType(betterproto.Enum):
| 64 | 64 | 33 | 8 | 55 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | FieldType | FieldType | 12 | 16 | 12 | 12 | 34f632e32a4689b0fe866c002801fe5ff7d6feeb | bigcode/the-stack | train |
45869f9e4c33745e02e22705 | train | class | @dataclass(eq=False, repr=False)
class GetTemplateResponse(betterproto.Message):
data: "TemplateData" = betterproto.message_field(1)
| @dataclass(eq=False, repr=False)
class GetTemplateResponse(betterproto.Message):
| data: "TemplateData" = betterproto.message_field(1)
| (3)
type: "FieldType" = betterproto.enum_field(4)
@dataclass(eq=False, repr=False)
class GetTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class GetTemplateResponse(betterproto.Message):
| 64 | 64 | 32 | 17 | 47 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | GetTemplateResponse | GetTemplateResponse | 94 | 96 | 94 | 95 | 7089299cbb915b4cc7d7b6358352940bf23c703d | bigcode/the-stack | train |
d918329a97182413956662be | train | class | @dataclass(eq=False, repr=False)
class DeleteCredentialTemplateResponse(betterproto.Message):
pass
| @dataclass(eq=False, repr=False)
class DeleteCredentialTemplateResponse(betterproto.Message):
| pass
| (2)
continuation_token: str = betterproto.string_field(3)
@dataclass(eq=False, repr=False)
class DeleteCredentialTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class DeleteCredentialTemplateResponse(betterproto.Message):
| 64 | 64 | 21 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | DeleteCredentialTemplateResponse | DeleteCredentialTemplateResponse | 61 | 63 | 61 | 62 | f343082434318e1fb7376eb4925eaff498fe9c88 | bigcode/the-stack | train |
b8c37b12587ea7e4cb6257cf | train | class | @dataclass(eq=False, repr=False)
class TemplateField(betterproto.Message):
description: str = betterproto.string_field(2)
optional: bool = betterproto.bool_field(3)
type: "FieldType" = betterproto.enum_field(4)
| @dataclass(eq=False, repr=False)
class TemplateField(betterproto.Message):
| description: str = betterproto.string_field(2)
optional: bool = betterproto.bool_field(3)
type: "FieldType" = betterproto.enum_field(4)
| allow_additional_fields: bool = betterproto.bool_field(3)
@dataclass(eq=False, repr=False)
class CreateCredentialTemplateResponse(betterproto.Message):
data: "TemplateData" = betterproto.message_field(1)
@dataclass(eq=False, repr=False)
class TemplateField(betterproto.Message):
| 64 | 64 | 55 | 16 | 48 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | TemplateField | TemplateField | 82 | 86 | 82 | 83 | 8739af20c230a63e74dd0e8e7a52ab2e7482f9f5 | bigcode/the-stack | train |
9e7f15851f431c7b39df8350 | train | class | @dataclass(eq=False, repr=False)
class CreateCredentialTemplateRequest(betterproto.Message):
"""Request to create new template"""
name: str = betterproto.string_field(1)
fields: Dict[str, "TemplateField"] = betterproto.map_field(
2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
allow_... | @dataclass(eq=False, repr=False)
class CreateCredentialTemplateRequest(betterproto.Message):
| """Request to create new template"""
name: str = betterproto.string_field(1)
fields: Dict[str, "TemplateField"] = betterproto.map_field(
2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
allow_additional_fields: bool = betterproto.bool_field(3)
| repr=False)
class DeleteCredentialTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class DeleteCredentialTemplateResponse(betterproto.Message):
pass
@dataclass(eq=False, repr=False)
class CreateCredentialTemplateRequest(betterproto.Message):
| 64 | 64 | 85 | 18 | 45 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | CreateCredentialTemplateRequest | CreateCredentialTemplateRequest | 66 | 74 | 66 | 67 | 1004ff35bf1d32298e7fc12f11bf163f4ab8bffb | bigcode/the-stack | train |
8b7aeaa5a2e55c6ba96f4fa4 | train | class | @dataclass(eq=False, repr=False)
class ListTemplatesRequest(betterproto.Message):
pass
| @dataclass(eq=False, repr=False)
class ListTemplatesRequest(betterproto.Message):
| pass
| proto.Message):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class GetTemplateResponse(betterproto.Message):
data: "TemplateData" = betterproto.message_field(1)
@dataclass(eq=False, repr=False)
class ListTemplatesRequest(betterproto.Message):
| 64 | 64 | 20 | 17 | 47 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | ListTemplatesRequest | ListTemplatesRequest | 99 | 101 | 99 | 100 | dd73f01dbd6bd6351c219703ed8db245effdf7ee | bigcode/the-stack | train |
e06143d83b7ec59b98d858dd | train | class | @dataclass(eq=False, repr=False)
class GetCredentialTemplateResponse(betterproto.Message):
template: "TemplateData" = betterproto.message_field(1)
| @dataclass(eq=False, repr=False)
class GetCredentialTemplateResponse(betterproto.Message):
| template: "TemplateData" = betterproto.message_field(1)
| 1
BOOL = 2
DATETIME = 4
@dataclass(eq=False, repr=False)
class GetCredentialTemplateRequest(betterproto.Message):
id: str = betterproto.string_field(1)
@dataclass(eq=False, repr=False)
class GetCredentialTemplateResponse(betterproto.Message):
| 64 | 64 | 33 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | GetCredentialTemplateResponse | GetCredentialTemplateResponse | 24 | 26 | 24 | 25 | 53b76ed62c7c97e381b635b569e16f63bddafe81 | bigcode/the-stack | train |
9b0a94aa8397bde219dad0d6 | train | class | @dataclass(eq=False, repr=False)
class ListCredentialTemplatesResponse(betterproto.Message):
templates: List["TemplateData"] = betterproto.message_field(1)
has_more_results: bool = betterproto.bool_field(2)
continuation_token: str = betterproto.string_field(3)
| @dataclass(eq=False, repr=False)
class ListCredentialTemplatesResponse(betterproto.Message):
| templates: List["TemplateData"] = betterproto.message_field(1)
has_more_results: bool = betterproto.bool_field(2)
continuation_token: str = betterproto.string_field(3)
| (4)
@dataclass(eq=False, repr=False)
class ListCredentialTemplatesRequest(betterproto.Message):
query: str = betterproto.string_field(1)
continuation_token: str = betterproto.string_field(2)
@dataclass(eq=False, repr=False)
class ListCredentialTemplatesResponse(betterproto.Message):
| 64 | 64 | 61 | 18 | 46 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | ListCredentialTemplatesResponse | ListCredentialTemplatesResponse | 49 | 53 | 49 | 50 | 32f82c6683f7e887792e764400dd14f541ab9483 | bigcode/the-stack | train |
480b9c497c870a2d431e96ef | train | class | @dataclass(eq=False, repr=False)
class TemplateData(betterproto.Message):
id: str = betterproto.string_field(1)
name: str = betterproto.string_field(2)
version: int = betterproto.int32_field(3)
fields: Dict[str, "TemplateField"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TY... | @dataclass(eq=False, repr=False)
class TemplateData(betterproto.Message):
| id: str = betterproto.string_field(1)
name: str = betterproto.string_field(2)
version: int = betterproto.int32_field(3)
fields: Dict[str, "TemplateField"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
allow_additional_fields: bool = betterproto.bool_fiel... | repr=False)
class ListTemplatesRequest(betterproto.Message):
pass
@dataclass(eq=False, repr=False)
class ListTemplatesResponse(betterproto.Message):
templates: List["TemplateData"] = betterproto.message_field(1)
@dataclass(eq=False, repr=False)
class TemplateData(betterproto.Message):
| 64 | 64 | 151 | 16 | 48 | musaib072/sdk | python/trinsic/proto/services/verifiablecredentials/templates/v1/__init__.py | Python | TemplateData | TemplateData | 109 | 121 | 109 | 110 | f9a33920f331aba7038117013d5f69407c6cf847 | bigcode/the-stack | train |
5a3cd75de5052db6c88b8fbe | train | class | class ContextIsAdminPolicyTestCase(test.TestCase):
def setUp(self):
super(ContextIsAdminPolicyTestCase, self).setUp()
policy.reset()
policy.init(suppress_deprecation_warnings=True)
def _set_rules(self, rules, default_rule):
these_rules = common_policy.Rules.from_dict(rules,
... | class ContextIsAdminPolicyTestCase(test.TestCase):
| def setUp(self):
super(ContextIsAdminPolicyTestCase, self).setUp()
policy.reset()
policy.init(suppress_deprecation_warnings=True)
def _set_rules(self, rules, default_rule):
these_rules = common_policy.Rules.from_dict(rules,
def... | default_noexist"
# FIXME(gyee): need to overwrite the Enforcer's default_rule first
# as it is recreating the rules with its own default_rule instead
# of the default_rule passed in from set_rules(). I think this is a
# bug in Oslo policy.
policy._ENFORCER.default_rule = new_defa... | 118 | 119 | 399 | 11 | 107 | openstack/manila | manila/tests/test_policy.py | Python | ContextIsAdminPolicyTestCase | ContextIsAdminPolicyTestCase | 178 | 219 | 178 | 179 | 971d34d38a5ac9834b8c5bec7a613a2365280dff | bigcode/the-stack | train |
03b6d4c6566189d5b41af00f | train | class | @ddt.ddt
class PolicyTestCase(test.TestCase):
def setUp(self):
super(PolicyTestCase, self).setUp()
rules = [
common_policy.RuleDefault("true", '@'),
common_policy.RuleDefault("test:allowed", '@'),
common_policy.RuleDefault("test:denied", "!"),
common_p... | @ddt.ddt
class PolicyTestCase(test.TestCase):
| def setUp(self):
super(PolicyTestCase, self).setUp()
rules = [
common_policy.RuleDefault("true", '@'),
common_policy.RuleDefault("test:allowed", '@'),
common_policy.RuleDefault("test:denied", "!"),
common_policy.RuleDefault("test:my_file",
... | # Copyright 2011 Piston Cloud Computing, Inc.
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | 219 | 256 | 898 | 14 | 204 | openstack/manila | manila/tests/test_policy.py | Python | PolicyTestCase | PolicyTestCase | 30 | 128 | 30 | 31 | 525a3de24fd6f1d0c72b62c9c5f8d52395fc50cc | bigcode/the-stack | train |
3620ff77b861ff6a988c1137 | train | class | class DefaultPolicyTestCase(test.TestCase):
"""This test case calls into the "enforce" method in policy
enforce() in contrast with authorize() allows "default" rules to apply
to policies that have not been registered.
"""
def setUp(self):
super(DefaultPolicyTestCase, self).setUp()
... | class DefaultPolicyTestCase(test.TestCase):
| """This test case calls into the "enforce" method in policy
enforce() in contrast with authorize() allows "default" rules to apply
to policies that have not been registered.
"""
def setUp(self):
super(DefaultPolicyTestCase, self).setUp()
policy.reset()
policy.init(suppress_... | method):
self.fixture.config(enforce_scope=False, group='oslo_policy')
project_context = context.RequestContext(project_id='fake-project-id',
roles=['bar'])
policy.reset()
policy.init(suppress_deprecation_warnings=True)
rule = com... | 110 | 110 | 368 | 9 | 101 | openstack/manila | manila/tests/test_policy.py | Python | DefaultPolicyTestCase | DefaultPolicyTestCase | 131 | 175 | 131 | 131 | a093d0dd405e0191ee3886fefae318418552d6a1 | bigcode/the-stack | train |
e277de3de8b73c6adcff117c | train | function | def save_data_set(set_, save_path, save_name):
if os.path.exists(os.path.join(save_path, save_name)+".h5"):
os.remove(os.path.join(save_path, save_name)+".h5")
hdf5_store = h5py.File(os.path.join(save_path, save_name)+".h5", "a")
hdf5_store.create_dataset("all_data", data = set_, compression="... | def save_data_set(set_, save_path, save_name):
| if os.path.exists(os.path.join(save_path, save_name)+".h5"):
os.remove(os.path.join(save_path, save_name)+".h5")
hdf5_store = h5py.File(os.path.join(save_path, save_name)+".h5", "a")
hdf5_store.create_dataset("all_data", data = set_, compression="gzip")
| += 1
midi_sets[current_set].append(midis[loop])
mel_sets[current_set].append(mels[loop])
loop += 1
if loop >= num_sets:
break
return midi_sets, mel_sets
def save_data_set(set_, save_path, save_name):
| 64 | 64 | 91 | 12 | 51 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | save_data_set | save_data_set | 91 | 96 | 91 | 91 | 1d193de4987d5f929d0e4b4c40c83c86e5f62527 | bigcode/the-stack | train |
028bb3b77c32386a6252c151 | train | function | def split_train_val_test(set_):
total = len(set_)
train_end_val_beginning = round(0.7 * total)
val_end_test_beginning = round(0.85 * total)
train_images = set_[:train_end_val_beginning]
val_images = set_[train_end_val_beginning:val_end_test_beginning]
test_images = set_[val_end_test_be... | def split_train_val_test(set_):
| total = len(set_)
train_end_val_beginning = round(0.7 * total)
val_end_test_beginning = round(0.85 * total)
train_images = set_[:train_end_val_beginning]
val_images = set_[train_end_val_beginning:val_end_test_beginning]
test_images = set_[val_end_test_beginning:]
return train_ima... | .join(save_path, save_name)+".h5")
hdf5_store = h5py.File(os.path.join(save_path, save_name)+".h5", "a")
hdf5_store.create_dataset("all_data", data = set_, compression="gzip")
def split_train_val_test(set_):
| 64 | 64 | 100 | 8 | 56 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | split_train_val_test | split_train_val_test | 98 | 108 | 98 | 98 | f894dc22ec3e95088d634db92ae8aa4a83d59e47 | bigcode/the-stack | train |
75bef923cef4dd5fbdaf2216 | train | function | def load_midi_violin(path):
note_events = []
mid = midi.read_midifile(path)
##getting only the note data
for n,track in enumerate(mid):
note_events.append([])
for event in track:
if "NoteOnEvent" in str(event):
note_events[n].append(event)
... | def load_midi_violin(path):
| note_events = []
mid = midi.read_midifile(path)
##getting only the note data
for n,track in enumerate(mid):
note_events.append([])
for event in track:
if "NoteOnEvent" in str(event):
note_events[n].append(event)
elif "NoteOffEvent" in str(e... | import sounddevice as sd
from scipy.signal import istft
from scipy.signal import stft
import librosa
import librosa.display
import midi
import skimage.transform
import numpy as np
import os
import h5py
import time
import matplotlib.pyplot as plt
start_time = time.time()
def load_midi_violin(path):
| 73 | 140 | 468 | 8 | 65 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | load_midi_violin | load_midi_violin | 15 | 64 | 15 | 15 | af8fa003689aec3c1ad5a16ece24d0ae557aa0e7 | bigcode/the-stack | train |
a7779c0310d8695c6b57b862 | train | function | def make_wave(freq, duration, sample_rate = 22050):
wave = []
for i in range(0,int(duration*sample_rate)):
wave.append(i/((sample_rate/(2*np.pi))/freq))
wave = np.sin(np.stack(wave))
return wave
| def make_wave(freq, duration, sample_rate = 22050):
| wave = []
for i in range(0,int(duration*sample_rate)):
wave.append(i/((sample_rate/(2*np.pi))/freq))
wave = np.sin(np.stack(wave))
return wave
| _[:train_end_val_beginning]
val_images = set_[train_end_val_beginning:val_end_test_beginning]
test_images = set_[val_end_test_beginning:]
return train_images, val_images, test_images
def make_wave(freq, duration, sample_rate = 22050):
| 64 | 64 | 60 | 14 | 49 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | make_wave | make_wave | 110 | 116 | 110 | 110 | 0efd120097c60e174cb5f656f769c1eaacbde902 | bigcode/the-stack | train |
637c61508cfc543ec4ef19f8 | train | function | def generate_specgrams(output_path, max_pitch):
Fs = 22050
N = 2048
w = np.hamming(N)
ov = N - Fs // 1000
ov = 250
for pitch in range(69,max_pitch):
print(pitch)
freq = 440*(2**((pitch-69)/12))
wave = make_wave(freq, 1, sample_rate=22050)
sd.play(wave)
... | def generate_specgrams(output_path, max_pitch):
| Fs = 22050
N = 2048
w = np.hamming(N)
ov = N - Fs // 1000
ov = 250
for pitch in range(69,max_pitch):
print(pitch)
freq = 440*(2**((pitch-69)/12))
wave = make_wave(freq, 1, sample_rate=22050)
sd.play(wave)
cont = input("...")
f,t,specgram... | :
if os.path.exists(path):
os.remove(path)
hdf5_store = h5py.File(path, "a")
hdf5_store.create_dataset("all_data", data = array, compression="gzip")
break
except:
pass
def generate_specgrams(output_path, max_pitch):
| 66 | 66 | 222 | 10 | 55 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | generate_specgrams | generate_specgrams | 130 | 154 | 130 | 130 | 938e9039017cc5d0c2d11c1da1d1df8257827ed0 | bigcode/the-stack | train |
d6a9350e4d6be19190284ae0 | train | function | def save_array(array, path):
while True:
try:
if os.path.exists(path):
os.remove(path)
hdf5_store = h5py.File(path, "a")
hdf5_store.create_dataset("all_data", data = array, compression="gzip")
break
except:
pass
| def save_array(array, path):
| while True:
try:
if os.path.exists(path):
os.remove(path)
hdf5_store = h5py.File(path, "a")
hdf5_store.create_dataset("all_data", data = array, compression="gzip")
break
except:
pass
| (freq, duration, sample_rate = 22050):
wave = []
for i in range(0,int(duration*sample_rate)):
wave.append(i/((sample_rate/(2*np.pi))/freq))
wave = np.sin(np.stack(wave))
return wave
def save_array(array, path):
| 64 | 64 | 69 | 7 | 56 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | save_array | save_array | 118 | 128 | 118 | 118 | 2be00141e869b9705cc55638b57bec71c78a4d98 | bigcode/the-stack | train |
2ef7a8dc69bc7c1600b43a40 | train | function | def seperate_sets(midis, mels, set_size):
midi_sets = []
mel_sets = []
loop = 0
current_set = -1
num_sets = len(midis)
while True:
if loop % set_size == 0:
midi_sets.append([])
mel_sets.append([])
current_set += 1
midi_sets[c... | def seperate_sets(midis, mels, set_size):
| midi_sets = []
mel_sets = []
loop = 0
current_set = -1
num_sets = len(midis)
while True:
if loop % set_size == 0:
midi_sets.append([])
mel_sets.append([])
current_set += 1
midi_sets[current_set].append(midis[loop])
me... | = i/int(track[n+1].tick/4)
track_array[current_tick+track[n+1].tick-i-1][1][working_slot] = i/int(track[n+1].tick/4)
return track_array
def seperate_sets(midis, mels, set_size):
| 63 | 64 | 125 | 12 | 50 | TaylorChris2/Virtuoso | all code (not organized)/frequency specgram generator.py | Python | seperate_sets | seperate_sets | 68 | 88 | 68 | 68 | 45de847ad28c2db193d8774a2e5a7781d3449e06 | bigcode/the-stack | train |
eca7662d409c68bdd44ee5b2 | train | function | def calc_iou(rect1, rect2):
"""
Calculate iou
"""
bd_i = (max(rect1[0], rect2[0]), max(rect1[1], rect2[1]),
min(rect1[2], rect2[2]), min(rect1[3], rect2[3]))
iw = bd_i[2] - bd_i[0] + 0.001
ih = bd_i[3] - bd_i[1] + 0.001
iou = 0
if iw > 0 and ih > 0:
ua = calc_rect... | def calc_iou(rect1, rect2):
| """
Calculate iou
"""
bd_i = (max(rect1[0], rect2[0]), max(rect1[1], rect2[1]),
min(rect1[2], rect2[2]), min(rect1[3], rect2[3]))
iw = bd_i[2] - bd_i[0] + 0.001
ih = bd_i[3] - bd_i[1] + 0.001
iou = 0
if iw > 0 and ih > 0:
ua = calc_rect_area(rect1) + calc_rect_are... | cur_prec = max(precision[i], cur_prec)
if abs(recall[i] - cur_rec) > eps:
ap_val += cur_prec * abs(recall[i] - cur_rec)
cur_rec = recall[i]
return ap_val
def calc_iou(rect1, rect2):
| 64 | 64 | 164 | 10 | 53 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | calc_iou | calc_iou | 411 | 423 | 411 | 411 | f6606552aa456625618187932718e27bc2e935bd | bigcode/the-stack | train |
5e5e5c24ff08c27b220ed466 | train | function | def prepare_file_paths(dataset_path):
"""
prepare_file_paths
"""
image_files = []
anno_files = []
image_names = []
if not os.path.isdir(dataset_path):
print("dataset_train root is invalid!")
exit()
anno_dir = os.path.join(dataset_path, "Annotations")
image_dir = o... | def prepare_file_paths(dataset_path):
| """
prepare_file_paths
"""
image_files = []
anno_files = []
image_names = []
if not os.path.isdir(dataset_path):
print("dataset_train root is invalid!")
exit()
anno_dir = os.path.join(dataset_path, "Annotations")
image_dir = os.path.join(dataset_path, "JPEGImages"... | ua
return iou
def calc_rect_area(rect):
"""
calc_rect_area
"""
return (rect[2] - rect[0] + 0.001) * (rect[3] - rect[1] + 0.001)
def prepare_file_paths(dataset_path):
| 64 | 64 | 161 | 7 | 57 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | prepare_file_paths | prepare_file_paths | 433 | 451 | 433 | 433 | 9150b3f340b59e6fd0ee73a16ca9835c65c878b5 | bigcode/the-stack | train |
881f1d9e9b858f5aa760b0ed | train | function | def filter_valid_files_by_txt(image_dir, anno_dir, valid_txt):
"""
filter_valid_files_by_txt
"""
with open(valid_txt, "r") as txt:
valid_names = txt.readlines()
image_files = []
anno_files = []
image_names = []
for name in valid_names:
strip_name = name.strip("\n")
... | def filter_valid_files_by_txt(image_dir, anno_dir, valid_txt):
| """
filter_valid_files_by_txt
"""
with open(valid_txt, "r") as txt:
valid_names = txt.readlines()
image_files = []
anno_files = []
image_names = []
for name in valid_names:
strip_name = name.strip("\n")
anno_joint_path = os.path.join(anno_dir, strip_name + ".x... | , ret_anno_files, ret_image_names = filter_valid_files_by_txt(image_dir, anno_dir, valid_txt)
image_files.extend(ret_image_files)
anno_files.extend(ret_anno_files)
image_names.extend(ret_image_names)
return image_files, anno_files, image_names
def filter_valid_files_by_txt(image_dir, anno_dir, valid_txt... | 75 | 75 | 252 | 15 | 59 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | filter_valid_files_by_txt | filter_valid_files_by_txt | 454 | 480 | 454 | 454 | d7baef0bf0b2839d36c64c610a9f20c5db9d2cc4 | bigcode/the-stack | train |
6e55722e5cc4cb537bc31d0c | train | function | def calc_rect_area(rect):
"""
calc_rect_area
"""
return (rect[2] - rect[0] + 0.001) * (rect[3] - rect[1] + 0.001)
| def calc_rect_area(rect):
| """
calc_rect_area
"""
return (rect[2] - rect[0] + 0.001) * (rect[3] - rect[1] + 0.001)
| .001
iou = 0
if iw > 0 and ih > 0:
ua = calc_rect_area(rect1) + calc_rect_area(rect2) - iw * ih
iou = iw * ih / ua
return iou
def calc_rect_area(rect):
| 64 | 64 | 50 | 6 | 57 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | calc_rect_area | calc_rect_area | 426 | 430 | 426 | 426 | 76cd626cefb3ea06207fa034ac763cc778e19b9a | bigcode/the-stack | train |
25c6f2bc37c68b60016a2685 | train | function | def parse_gt_from_anno(img_anno, classes):
"""parse_gt_from_anno"""
print('parse ground truth files...')
ground_truth = {}
for img_name, annos in img_anno.items():
objs = []
for anno in annos:
if anno[1] == 0. and anno[2] == 0. and anno[3] == 0. and anno[4] == 0.:
... | def parse_gt_from_anno(img_anno, classes):
| """parse_gt_from_anno"""
print('parse ground truth files...')
ground_truth = {}
for img_name, annos in img_anno.items():
objs = []
for anno in annos:
if anno[1] == 0. and anno[2] == 0. and anno[3] == 0. and anno[4] == 0.:
continue
if int(anno[0]) ... | det.confidence = box[4]
if class_label_map is not None:
det.class_label = class_label_map[int(box[5])]
else:
det.class_label = str(int(box[5]))
brambox.append(det)
return brambox
def parse_gt_from_anno(img_anno, classes):
| 69 | 69 | 233 | 12 | 56 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | parse_gt_from_anno | parse_gt_from_anno | 282 | 307 | 282 | 282 | 956fa2cbe75a6572051043341333a131894f453c | bigcode/the-stack | train |
16b7fd14ec5e3338d5385821 | train | function | def calc_gt_count(gt_set, cls):
"""
Calculate the number of gt_set equals cls
"""
count = 0
for img in gt_set:
for obj in gt_set[img]:
if obj['class'] == cls:
count += 1
return count
| def calc_gt_count(gt_set, cls):
| """
Calculate the number of gt_set equals cls
"""
count = 0
for img in gt_set:
for obj in gt_set[img]:
if obj['class'] == cls:
count += 1
return count
| / n_gt_obj
precision = tp / (tp + fp)
ap = cal_ap_voc2012(recall, precision)
evaluate[cls] = {'recall': recall, 'precision': precision, 'ap': ap}
return evaluate
def calc_gt_count(gt_set, cls):
| 64 | 64 | 64 | 9 | 54 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | calc_gt_count | calc_gt_count | 378 | 387 | 378 | 378 | 61c3115f23b7b5e569c68a76d10c2a8c35555cdf | bigcode/the-stack | train |
1ddd61e4a07446aa638122aa | train | function | def calc_recall_precision_ap(ground_truth, ret_list, iou_thr=0.5):
"""
calc_recall_precision_ap
"""
print('calculate [recall | persicion | ap]...')
evaluate = {}
for cls in ret_list:
ret = ret_list[cls]
n_gt_obj = calc_gt_count(ground_truth, cls)
print('class [%s] gro... | def calc_recall_precision_ap(ground_truth, ret_list, iou_thr=0.5):
| """
calc_recall_precision_ap
"""
print('calculate [recall | persicion | ap]...')
evaluate = {}
for cls in ret_list:
ret = ret_list[cls]
n_gt_obj = calc_gt_count(ground_truth, cls)
print('class [%s] ground truth:%d' % (cls, n_gt_obj))
ret = sorted(ret, key=lam... | ():
info = line.strip().split()
img_name = info[0]
scole = float(info[1])
xmin = float(info[2])
ymin = float(info[3])
xmax = float(info[4])
ymax = float(info[5])
ret_list[cls].append({'img_name': img_name, 'scole': scole, 'r... | 118 | 118 | 395 | 21 | 96 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | calc_recall_precision_ap | calc_recall_precision_ap | 329 | 375 | 329 | 329 | 28231f97d1845d6bccfb2fc0928881d7a14190f9 | bigcode/the-stack | train |
0beadea1b1a315144751ac79 | train | function | def get_data(image_file, anno_file, image_name):
"""
get_data
"""
count = 0
annotation = []
tree = ET.parse(anno_file)
root = tree.getroot()
class_indexing_1 = {'face': 0}
with Image.open(image_file) as fd:
orig_width, orig_height = fd.size
with open(image_file, 'rb... | def get_data(image_file, anno_file, image_name):
| """
get_data
"""
count = 0
annotation = []
tree = ET.parse(anno_file)
root = tree.getroot()
class_indexing_1 = {'face': 0}
with Image.open(image_file) as fd:
orig_width, orig_height = fd.size
with open(image_file, 'rb') as f:
img = f.read()
for member i... | )
continue
image_joint_path = os.path.join(image_dir, strip_name + ".png")
image_name = image_joint_path.split('/')[-1].replace('.png', '')
if os.path.isfile(image_joint_path):
image_files.append(image_joint_path)
anno_files.append(anno... | 94 | 94 | 314 | 12 | 81 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | get_data | get_data | 483 | 524 | 483 | 483 | c01aeaf1e0751f3c2d109f04187cca8470fcec70 | bigcode/the-stack | train |
fa3cd2248aff05adb89eb5c2 | train | function | def deserialize(member, class_indexing):
"""
deserialize
"""
class_name = member[0].text
if class_name in class_indexing:
class_num = class_indexing[class_name]
else:
return None
bnx = member.find('bndbox')
box_x_min = float(bnx.find('xmin').text)
box_y_min = floa... | def deserialize(member, class_indexing):
| """
deserialize
"""
class_name = member[0].text
if class_name in class_indexing:
class_num = class_indexing[class_name]
else:
return None
bnx = member.find('bndbox')
box_x_min = float(bnx.find('xmin').text)
box_y_min = float(bnx.find('ymin').text)
box_x_max = ... | else:
break
data = {
"image": img,
"annotation": annotation_res,
"image_name": image_name,
"image_size": np.array([[orig_width, orig_height]], dtype='int32')
}
return data
def deserialize(member, class_indexing):
| 64 | 64 | 202 | 8 | 55 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | deserialize | deserialize | 527 | 548 | 527 | 527 | 9b2f06f54ecd5f23a286bbdf9524dbefef53bd12 | bigcode/the-stack | train |
7de569f0ba5f2aaadc136e9b | train | function | def get_bounding_boxes(coords_0, cls_scores_0, coords_1, cls_scores_1, coords_2, cls_scores_2, conf_thresh,
input_shape, num_classes):
"""get_bounding_boxes"""
batch = cls_scores_0.shape[0]
w_0 = int(input_shape[0] / 64)
h_0 = int(input_shape[1] / 64)
w_1 = int(input_shape[0] ... | def get_bounding_boxes(coords_0, cls_scores_0, coords_1, cls_scores_1, coords_2, cls_scores_2, conf_thresh,
input_shape, num_classes):
| """get_bounding_boxes"""
batch = cls_scores_0.shape[0]
w_0 = int(input_shape[0] / 64)
h_0 = int(input_shape[1] / 64)
w_1 = int(input_shape[0] / 32)
h_1 = int(input_shape[1] / 32)
w_2 = int(input_shape[0] / 16)
h_2 = int(input_shape[1] / 16)
num_anchors_0 = cls_scores_0.shape[1]
n... | 'object_id = {self.object_id}, '
string += f'x = {self.x_top_left}, '
string += f'y = {self.y_top_left}, '
string += f'w = {self.width}, '
string += f'h = {self.height}, '
string += f'confidence = {self.confidence}'
return string + '}'
def __str__(self):
""" ... | 256 | 256 | 1,346 | 42 | 213 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | get_bounding_boxes | get_bounding_boxes | 144 | 226 | 144 | 145 | 742df6a8a23e4a8a43fc3ddc8d04a2d2fd52cfd4 | bigcode/the-stack | train |
35c88815fdb47e04d6d91ee9 | train | function | def tensor_to_brambox(boxes_0, boxes_1, boxes_2, input_shape, labels):
"""tensor_to_brambox"""
converted_boxes_0 = []
converted_boxes_1 = []
converted_boxes_2 = []
for box in boxes_0:
if box.size == 0:
converted_boxes_0.append([])
else:
converted_boxes_0.appe... | def tensor_to_brambox(boxes_0, boxes_1, boxes_2, input_shape, labels):
| """tensor_to_brambox"""
converted_boxes_0 = []
converted_boxes_1 = []
converted_boxes_2 = []
for box in boxes_0:
if box.size == 0:
converted_boxes_0.append([])
else:
converted_boxes_0.append(convert_tensor_to_brambox(box, input_shape[0], input_shape[1], label... |
for end in split_idx_2:
boxes_2.append(detections_2[start: end])
start = end
return boxes_0, boxes_1, boxes_2
def tensor_to_brambox(boxes_0, boxes_1, boxes_2, input_shape, labels):
| 67 | 67 | 226 | 24 | 42 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | tensor_to_brambox | tensor_to_brambox | 229 | 253 | 229 | 229 | 6a80c4f9ce4f806b5fa5f34d59fb0d31913b51d2 | bigcode/the-stack | train |
4951f8fe502f668a74b3dd0f | train | class | class Box:
""" This is a generic bounding box representation.
This class provides some base functionality to both annotations and detections.
Attributes:
class_label (string): class string label; Default **''**
object_id (int): Object identifier for reid purposes; Default **0**
x_to... | class Box:
| """ This is a generic bounding box representation.
This class provides some base functionality to both annotations and detections.
Attributes:
class_label (string): class string label; Default **''**
object_id (int): Object identifier for reid purposes; Default **0**
x_top_left (Num... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | 149 | 149 | 498 | 3 | 145 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | Box | Box | 21 | 77 | 21 | 21 | 69e867b5ef310364bdaa4b1a1fc6a70e64fd17d7 | bigcode/the-stack | train |
7df6f6196d7d5ddb6e4de0a3 | train | function | def cal_ap_voc2012(recall, precision):
"""
cal_ap_voc2012
"""
ap_val = 0.0
eps = 1e-6
assert len(recall) == len(precision)
length = len(recall)
cur_prec = precision[length - 1]
cur_rec = recall[length - 1]
for i in range(0, length - 1)[::-1]:
cur_prec = max(precision... | def cal_ap_voc2012(recall, precision):
| """
cal_ap_voc2012
"""
ap_val = 0.0
eps = 1e-6
assert len(recall) == len(precision)
length = len(recall)
cur_prec = precision[length - 1]
cur_rec = recall[length - 1]
for i in range(0, length - 1)[::-1]:
cur_prec = max(precision[i], cur_prec)
if abs(recall[i]... | Calculate the number of gt_set equals cls
"""
count = 0
for img in gt_set:
for obj in gt_set[img]:
if obj['class'] == cls:
count += 1
return count
def cal_ap_voc2012(recall, precision):
| 64 | 64 | 150 | 12 | 51 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | cal_ap_voc2012 | cal_ap_voc2012 | 390 | 408 | 390 | 390 | 3c7d8a008087dc9de5912ceda54bc46b180fe59d | bigcode/the-stack | train |
142807160683ff50eb26d84f | train | class | class Detection(Box):
""" This is a generic detection class that provides some base functionality all detections need.
It builds upon :class:`~brambox.boxes.box.Box`.
Attributes:
confidence (Number): confidence score between 0-1 for that detection; Default **0.0**
"""
def __init__(self):
... | class Detection(Box):
| """ This is a generic detection class that provides some base functionality all detections need.
It builds upon :class:`~brambox.boxes.box.Box`.
Attributes:
confidence (Number): confidence score between 0-1 for that detection; Default **0.0**
"""
def __init__(self):
""" x_top_left,... | , Box):
instance.class_label = obj.class_label
instance.object_id = obj.object_id
instance.x_top_left = obj.x_top_left
instance.y_top_left = obj.y_top_left
instance.width = obj.width
instance.height = obj.height
else:
raise Type... | 159 | 159 | 532 | 4 | 154 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | Detection | Detection | 80 | 141 | 80 | 80 | 67c10516df7127f6b44df4c5de3e08ea4926d691 | bigcode/the-stack | train |
7987af8101f9dac134d2a6f6 | train | function | def convert_tensor_to_brambox(boxes, width, height, class_label_map):
"""convert_tensor_to_brambox"""
boxes[:, 0:3:2] = boxes[:, 0:3:2] * width
boxes[:, 0] -= boxes[:, 2] / 2
boxes[:, 1:4:2] = boxes[:, 1:4:2] * height
boxes[:, 1] -= boxes[:, 3] / 2
brambox = []
for box in boxes:
det... | def convert_tensor_to_brambox(boxes, width, height, class_label_map):
| """convert_tensor_to_brambox"""
boxes[:, 0:3:2] = boxes[:, 0:3:2] * width
boxes[:, 0] -= boxes[:, 2] / 2
boxes[:, 1:4:2] = boxes[:, 1:4:2] * height
boxes[:, 1] -= boxes[:, 3] / 2
brambox = []
for box in boxes:
det = Detection()
det.x_top_left = box[0]
det.y_top_left... | else:
converted_boxes_2.append(convert_tensor_to_brambox(box, input_shape[0], input_shape[1], labels))
return converted_boxes_0, converted_boxes_1, converted_boxes_2
def convert_tensor_to_brambox(boxes, width, height, class_label_map):
| 64 | 64 | 216 | 18 | 45 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | convert_tensor_to_brambox | convert_tensor_to_brambox | 256 | 279 | 256 | 256 | 03458550d253ee34d8d05f956d45874d8e18da7f | bigcode/the-stack | train |
8ea589c4f8efca2300becf31 | train | function | def parse_rets(ret_files_set):
"""parse_rets"""
print('parse ret files...')
ret_list = {}
for cls in ret_files_set:
ret_file = open(ret_files_set[cls])
ret_list[cls] = []
for line in ret_file.readlines():
info = line.strip().split()
img_name = info[0]
... | def parse_rets(ret_files_set):
| """parse_rets"""
print('parse ret files...')
ret_list = {}
for cls in ret_files_set:
ret_file = open(ret_files_set[cls])
ret_list[cls] = []
for line in ret_file.readlines():
info = line.strip().split()
img_name = info[0]
scole = float(info[1])
... | int(ymax)
cls = classes[int(anno[0])]
gt_box = {'class': cls, 'box': [xmin, ymin, xmax, ymax]}
objs.append(gt_box)
ground_truth[img_name] = objs
return ground_truth
def parse_rets(ret_files_set):
| 64 | 64 | 157 | 8 | 55 | mindspore-ai/models | research/cv/FaceDetection/infer/sdk/util/eval_util.py | Python | parse_rets | parse_rets | 310 | 326 | 310 | 310 | e45c77f0739a2b80b1041922efb7fad8299d6d41 | bigcode/the-stack | train |
fc1c4e930d5d4f1202667fe7 | train | function | def get_total_notices(layer):
'''Find the total number of notices in a layer'''
count = 0
for origin in layer.origins.origins:
count += len(origin.notices)
return count
| def get_total_notices(layer):
| '''Find the total number of notices in a layer'''
count = 0
for origin in layer.origins.origins:
count += len(origin.notices)
return count
| _dict in origins_list:
layer.origins.add_notice_origin(origin_dict['origin_str'])
for notice in origin_dict['notices']:
layer.origins.add_notice_to_origins(
origin_dict['origin_str'], Notice(
notice['message'], notice['level']))
def get_total_notices(layer... | 63 | 64 | 47 | 7 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | get_total_notices | get_total_notices | 133 | 138 | 133 | 133 | 23e5acf67e5c1451249662397be94e242f163809 | bigcode/the-stack | train |
110637eb3e0e3b00ce62353b | train | function | def extract_git_url_from_line(line):
'''Given a line of git remote -v output, parse the url
line structure is '<label>\t<url> (fetch)'''
split_line = line.split(' ')
extract_url = ''
# use fetch url
if split_line[1] == '(fetch)':
split_line = split_line[0].split('\t')
# use https... | def extract_git_url_from_line(line):
| '''Given a line of git remote -v output, parse the url
line structure is '<label>\t<url> (fetch)'''
split_line = line.split(' ')
extract_url = ''
# use fetch url
if split_line[1] == '(fetch)':
split_line = split_line[0].split('\t')
# use https or git@ type
full_url = spli... | for remote in repo.remotes:
url_list.add(remote.url)
except (git.InvalidGitRepositoryError, git.NoSuchPathError):
logger.debug("Cannot find git repo url, path is %s",
dockerfile_folder_path)
return url_list
def extract_git_url_from_line(line):
| 64 | 64 | 186 | 8 | 55 | shrikanta8/tern | tern/analyze/common.py | Python | extract_git_url_from_line | extract_git_url_from_line | 262 | 279 | 262 | 262 | 21c0fbc9abd6a184746905c119f63a760d55ae01 | bigcode/the-stack | train |
8c4638998ed0bed63e514f3d | train | function | def load_packages_from_cache(layer):
'''Given a layer object, populate package level information'''
loaded = False
raw_pkg_list = cache.get_packages(layer.fs_hash)
if raw_pkg_list:
logger.debug(
'Loading packages from cache: layer \"%s\"', layer.fs_hash[:10])
for pkg_dict in ... | def load_packages_from_cache(layer):
| '''Given a layer object, populate package level information'''
loaded = False
raw_pkg_list = cache.get_packages(layer.fs_hash)
if raw_pkg_list:
logger.debug(
'Loading packages from cache: layer \"%s\"', layer.fs_hash[:10])
for pkg_dict in raw_pkg_list:
pkg = Packa... | load_notices_from_cache(layer)
loaded = True
else:
# if the hash is not present in the cache, load that data from the
# hash file
logger.debug('Reading files in filesystem...')
layer.add_files()
return loaded
def load_packages_from_cach... | 64 | 64 | 169 | 7 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | load_packages_from_cache | load_packages_from_cache | 81 | 100 | 81 | 81 | c117586ade222e204b53f4db65b92b9fa90a9bb6 | bigcode/the-stack | train |
f99e0d84beb91b6c4f934f04 | train | function | def load_files_from_cache(layer):
'''Given a layer object, populate file level information'''
raw_file_list = cache.get_files(layer.fs_hash)
if raw_file_list:
logger.debug(
'Loading files from cache: layer \"%s\"', layer.fs_hash[:10])
for file_dict in raw_file_list:
f... | def load_files_from_cache(layer):
| '''Given a layer object, populate file level information'''
raw_file_list = cache.get_files(layer.fs_hash)
if raw_file_list:
logger.debug(
'Loading files from cache: layer \"%s\"', layer.fs_hash[:10])
for file_dict in raw_file_list:
f = FileData(file_dict['name'], fil... | ['origins']:
for notice in origin_dict['notices']:
pkg.origins.add_notice_to_origins(
origin_dict['origin_str'], Notice(
notice['message'], notice['level']))
layer.add_package(pkg)
loaded = True
... | 64 | 64 | 161 | 7 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | load_files_from_cache | load_files_from_cache | 103 | 119 | 103 | 103 | 5148a21e728977def1f1aaca7029f50cb45a8faf | bigcode/the-stack | train |
e1e9d529f96eb8cc9c12e70f | train | function | def get_git_toplevel(path):
'''Given a path, return the absolute path to the top level directory if it
is in a git repository. Empty string will be returned if not.
Path should be a path to a directory not to a file.'''
path_to_toplevel = ''
try:
repo = git.Repo(path, search_parent_directori... | def get_git_toplevel(path):
| '''Given a path, return the absolute path to the top level directory if it
is in a git repository. Empty string will be returned if not.
Path should be a path to a directory not to a file.'''
path_to_toplevel = ''
try:
repo = git.Repo(path, search_parent_directories=True)
path_to_top... | ://'):
extract_url = full_url.lstrip('http://')
elif full_url.startswith('git'):
extract_url = full_url.replace('git@github.com:', 'github.com/', 1)
extract_url = extract_url.rstrip('.git')
return extract_url
def get_git_toplevel(path):
| 64 | 64 | 139 | 7 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | get_git_toplevel | get_git_toplevel | 282 | 292 | 282 | 282 | 5b96ada535e6579cce7486d688d062bb7bb3e4ef | bigcode/the-stack | train |
1218ef82bb8f559f78aabf04 | train | function | def load_from_cache(layer, redo=False):
'''Given a layer object, check against cache to see if that layer id exists
if yes then load any relevant layer level information. The default
operation is to not redo the cache. Add notices to the layer's origins
matching the origin_str'''
loaded = False
... | def load_from_cache(layer, redo=False):
| '''Given a layer object, check against cache to see if that layer id exists
if yes then load any relevant layer level information. The default
operation is to not redo the cache. Add notices to the layer's origins
matching the origin_str'''
loaded = False
if not redo:
# check if the laye... | branch' in stat:
branch_report = branch_report + '\n'.join(stat['content']) + '\n\n'
if branch_report:
# add prefix
branch_report = '\nNon-deterministic branching statement: \n' + \
branch_report
return command_list, branch_report
def load_from_cache(layer, re... | 74 | 74 | 248 | 9 | 64 | shrikanta8/tern | tern/analyze/common.py | Python | load_from_cache | load_from_cache | 52 | 78 | 52 | 52 | 7d87b7519b041b838869c30387206f797ad31098 | bigcode/the-stack | train |
a30b6f9f9349ebc274f98111 | train | function | def check_git_src(dockerfile_path):
'''Given the src_path and the dockerfile path, return the git
repository name and sha information in the format of string.
Currently we only consider the following situation:
- target_git_project
- dir1
- dir2/dockerfile
So we only use dockerfile_p... | def check_git_src(dockerfile_path):
| '''Given the src_path and the dockerfile path, return the git
repository name and sha information in the format of string.
Currently we only consider the following situation:
- target_git_project
- dir1
- dir2/dockerfile
So we only use dockerfile_path to find the git repo info.'''
... | _files(layer):
'''Given an image layer, removes duplicate FileData objects that are found
both at the layer and package level'''
for layer_file in layer.files:
for pkg in layer.packages:
for pkg_file in pkg.files:
if layer_file.is_equal(pkg_file):
laye... | 78 | 78 | 260 | 9 | 69 | shrikanta8/tern | tern/analyze/common.py | Python | check_git_src | check_git_src | 208 | 231 | 208 | 208 | 22689000263990d435034f0e9fab301c09bf8f5a | bigcode/the-stack | train |
4eea974165eb0086a8b5a576 | train | function | def is_empty_layer(layer):
'''Return True if the given image layer is empty'''
cwd = layer.get_untar_dir()
if len(os.listdir(cwd)) == 0:
return True
return False
| def is_empty_layer(layer):
| '''Return True if the given image layer is empty'''
cwd = layer.get_untar_dir()
if len(os.listdir(cwd)) == 0:
return True
return False
| .files_analyzed:
if get_total_notices(layer) == 0:
# if there are no new notices, we have probably pulled the
# data from the cache. So load those notices here.
load_notices_from_cache(layer)
cache.add_layer(layer)
def is_empty_layer(layer):
| 64 | 64 | 47 | 6 | 58 | shrikanta8/tern | tern/analyze/common.py | Python | is_empty_layer | is_empty_layer | 152 | 157 | 152 | 152 | 2b8468fe6c0542d2fadb610e3ad32ca5ff18f903 | bigcode/the-stack | train |
be4820fe7e035c744c3cd16b | train | function | def get_deb_package_licenses(deb_copyrights):
'''
Given a list of debian copyrights for the same number of packages,
returns a list package licenses for each of the packages
'''
deb_licenses = []
for deb_copyright in deb_copyrights:
deb_licenses.append(get_licenses_from_deb_copyright(deb... | def get_deb_package_licenses(deb_copyrights):
| '''
Given a list of debian copyrights for the same number of packages,
returns a list package licenses for each of the packages
'''
deb_licenses = []
for deb_copyright in deb_copyrights:
deb_licenses.append(get_licenses_from_deb_copyright(deb_copyright))
return deb_licenses
| s"):
pkg_license = paragraph.get("license")
if not pkg_license.startswith("*"):
pkg_license = pkg_license.split("\n")[0]
if pkg_license:
pkg_licenses.add(pkg_license)
return list(pkg_licenses)
def get_deb_package_licenses(deb_copyrights):
| 64 | 64 | 85 | 13 | 51 | shrikanta8/tern | tern/analyze/common.py | Python | get_deb_package_licenses | get_deb_package_licenses | 187 | 195 | 187 | 187 | b48057388278590f944df8527eb2a03523b95504 | bigcode/the-stack | train |
c027be3ded1e0bb419effec4 | train | function | def get_git_sha(path_to_toplevel):
'''Given a absolute path to a git repository, return the HEAD sha.'''
sha_info = '(not found)'
try:
repo = git.Repo(path_to_toplevel)
sha_info = str(repo.rev_parse(str(repo.head)))
except (git.InvalidGitRepositoryError, git.NoSuchPathError, git.BadObjec... | def get_git_sha(path_to_toplevel):
| '''Given a absolute path to a git repository, return the HEAD sha.'''
sha_info = '(not found)'
try:
repo = git.Repo(path_to_toplevel)
sha_info = str(repo.rev_parse(str(repo.head)))
except (git.InvalidGitRepositoryError, git.NoSuchPathError, git.BadObject):
logger.debug("Cannot fi... |
name_info = os.path.basename(path_to_toplevel)
comment_line = ('git project name: ' + name_info +
', HEAD sha: ' + sha_info)
else:
comment_line = 'Not a git repository'
return comment_line
def get_git_sha(path_to_toplevel):
| 64 | 64 | 108 | 9 | 54 | shrikanta8/tern | tern/analyze/common.py | Python | get_git_sha | get_git_sha | 234 | 243 | 234 | 234 | 98de790a47daff3d6bc75eb4280ed3af32debe7d | bigcode/the-stack | train |
c06414b82a97aa0879e931a9 | train | function | def remove_duplicate_layer_files(layer):
'''Given an image layer, removes duplicate FileData objects that are found
both at the layer and package level'''
for layer_file in layer.files:
for pkg in layer.packages:
for pkg_file in pkg.files:
if layer_file.is_equal(pkg_file)... | def remove_duplicate_layer_files(layer):
| '''Given an image layer, removes duplicate FileData objects that are found
both at the layer and package level'''
for layer_file in layer.files:
for pkg in layer.packages:
for pkg_file in pkg.files:
if layer_file.is_equal(pkg_file):
layer.remove_file(l... | packages,
returns a list package licenses for each of the packages
'''
deb_licenses = []
for deb_copyright in deb_copyrights:
deb_licenses.append(get_licenses_from_deb_copyright(deb_copyright))
return deb_licenses
def remove_duplicate_layer_files(layer):
| 64 | 64 | 73 | 7 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | remove_duplicate_layer_files | remove_duplicate_layer_files | 198 | 205 | 198 | 198 | de7c3bcfc0ee3f4cc2ae81d15f191e5a20ec97a9 | bigcode/the-stack | train |
7e8e6623b09a61e13c26a1fc | train | function | def get_licenses_from_deb_copyright(deb_copyright):
'''
Given the debian copyright text,
1. parse each copyright text
2. filter out all the available licenses
3. returns a list of unique licenses found inside
the copyright text
'''
collected_paragraphs = []
pkg_licenses = set()
f... | def get_licenses_from_deb_copyright(deb_copyright):
| '''
Given the debian copyright text,
1. parse each copyright text
2. filter out all the available licenses
3. returns a list of unique licenses found inside
the copyright text
'''
collected_paragraphs = []
pkg_licenses = set()
for paragraph in iter(debcon.get_paragraphs_data(deb_... | _layer(layer)
def is_empty_layer(layer):
'''Return True if the given image layer is empty'''
cwd = layer.get_untar_dir()
if len(os.listdir(cwd)) == 0:
return True
return False
def get_licenses_from_deb_copyright(deb_copyright):
| 64 | 64 | 210 | 14 | 49 | shrikanta8/tern | tern/analyze/common.py | Python | get_licenses_from_deb_copyright | get_licenses_from_deb_copyright | 160 | 184 | 160 | 160 | 73d5864e48e7b928aaf40618125a1ffe63b51833 | bigcode/the-stack | train |
0220c1c37598f3f9ac79fd68 | train | function | def save_to_cache(image):
'''Given an image object, save all layers to the cache'''
for layer in image.layers:
if layer.packages or layer.files_analyzed:
if get_total_notices(layer) == 0:
# if there are no new notices, we have probably pulled the
# data from t... | def save_to_cache(image):
| '''Given an image object, save all layers to the cache'''
for layer in image.layers:
if layer.packages or layer.files_analyzed:
if get_total_notices(layer) == 0:
# if there are no new notices, we have probably pulled the
# data from the cache. So load those no... | (
notice['message'], notice['level']))
def get_total_notices(layer):
'''Find the total number of notices in a layer'''
count = 0
for origin in layer.origins.origins:
count += len(origin.notices)
return count
def save_to_cache(image):
| 64 | 64 | 92 | 6 | 57 | shrikanta8/tern | tern/analyze/common.py | Python | save_to_cache | save_to_cache | 141 | 149 | 141 | 141 | a663bca674cb2b5d6575f3f8de205d54faab3ca1 | bigcode/the-stack | train |
899a74783ce531de91331326 | train | function | def get_git_url(dockerfile_path):
'''Given a dockerfile_path, return url of git project which contains
the dockerfile in a form of list.'''
# get the path of the folder containing the dockerfile
dockerfile_folder_path = os.path.dirname(os.path.abspath(dockerfile_path))
url_list = set({})
try:
... | def get_git_url(dockerfile_path):
| '''Given a dockerfile_path, return url of git project which contains
the dockerfile in a form of list.'''
# get the path of the folder containing the dockerfile
dockerfile_folder_path = os.path.dirname(os.path.abspath(dockerfile_path))
url_list = set({})
try:
repo = git.Repo(dockerfile_f... | (repo.rev_parse(str(repo.head)))
except (git.InvalidGitRepositoryError, git.NoSuchPathError, git.BadObject):
logger.debug("Cannot find git repo sha, toplevel path is %s",
path_to_toplevel)
return sha_info
def get_git_url(dockerfile_path):
| 64 | 64 | 149 | 9 | 54 | shrikanta8/tern | tern/analyze/common.py | Python | get_git_url | get_git_url | 246 | 259 | 246 | 246 | 1e5ac4895809fd4befcda96260fadb3bd8a5f51f | bigcode/the-stack | train |
3606969b8e436f44e8f8867b | train | function | def load_notices_from_cache(layer):
'''Given a layer object, populate the notices from the cache'''
origins_list = cache.get_origins(layer.fs_hash)
for origin_dict in origins_list:
layer.origins.add_notice_origin(origin_dict['origin_str'])
for notice in origin_dict['notices']:
la... | def load_notices_from_cache(layer):
| '''Given a layer object, populate the notices from the cache'''
origins_list = cache.get_origins(layer.fs_hash)
for origin_dict in origins_list:
layer.origins.add_notice_origin(origin_dict['origin_str'])
for notice in origin_dict['notices']:
layer.origins.add_notice_to_origins(
... | ():
for origin_dict in file_dict['origins']:
for notice in origin_dict['notices']:
f.origins.add_notice_to_origins(
origin_dict['origin_str'], Notice(
notice['message'], notice['level']))
... | 64 | 64 | 93 | 8 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | load_notices_from_cache | load_notices_from_cache | 122 | 130 | 122 | 122 | a5dc722575b9b5c4f4eee5bf5577d5dbc82d7146 | bigcode/the-stack | train |
296aa9ba28cddead560c69ef | train | function | def get_shell_commands(shell_command_line):
'''Given a shell command line, get a list of Command objects and report on
branch statements'''
statements = general.split_command(shell_command_line)
command_list = []
branch_report = ''
# traverse the statements, pick out the loop and commands.
f... | def get_shell_commands(shell_command_line):
| '''Given a shell command line, get a list of Command objects and report on
branch statements'''
statements = general.split_command(shell_command_line)
command_list = []
branch_report = ''
# traverse the statements, pick out the loop and commands.
for stat in statements:
if 'command' ... | .command import Command
from tern.utils import cache
from tern.utils import constants
from tern.utils import general
from debian_inspector import debcon
from debian_inspector import copyright as debut_copyright
# global logger
logger = logging.getLogger(constants.logger_name)
def get_shell_commands(shell_command_line)... | 64 | 64 | 198 | 8 | 56 | shrikanta8/tern | tern/analyze/common.py | Python | get_shell_commands | get_shell_commands | 28 | 49 | 28 | 28 | 661eb91dd846e7d86dc1b7e66a050e390e17fead | bigcode/the-stack | train |
71fd848f11f34448a9b516bb | train | function | def test_author():
"""Make sure the author is valid."""
assert ndradex.__author__ == "Akio Taniguchi"
| def test_author():
| """Make sure the author is valid."""
assert ndradex.__author__ == "Akio Taniguchi"
| # dependencies
import ndradex
# test functions
def test_version():
"""Make sure the version is valid."""
assert ndradex.__version__ == "0.2.2"
def test_author():
| 47 | 64 | 30 | 4 | 43 | astropenguin/radex-xarray | tests/test_metadata.py | Python | test_author | test_author | 11 | 13 | 11 | 11 | 3c6240ba177aecd06f8a46b7a39ff3bb4f32f3ee | bigcode/the-stack | train |
e895d81f9b6b84b86382869e | train | function | def test_version():
"""Make sure the version is valid."""
assert ndradex.__version__ == "0.2.2"
| def test_version():
| """Make sure the version is valid."""
assert ndradex.__version__ == "0.2.2"
| # dependencies
import ndradex
# test functions
def test_version():
| 17 | 64 | 30 | 4 | 12 | astropenguin/radex-xarray | tests/test_metadata.py | Python | test_version | test_version | 6 | 8 | 6 | 6 | fb2ef7ca677b73f448b0a30c4dfe97bdbf3fc982 | bigcode/the-stack | train |
d020bec842eb6e56c1e7daa2 | train | function | def restore_backup_vars(the_user_dict, backups):
for var, val in backups.items():
the_user_dict[var] = val
| def restore_backup_vars(the_user_dict, backups):
| for var, val in backups.items():
the_user_dict[var] = val
| _dict):
backups = dict()
for var in ['x', 'i', 'j', 'k', 'l', 'm', 'n']:
if var in the_user_dict:
backups[var] = the_user_dict[var]
return backups
def restore_backup_vars(the_user_dict, backups):
| 64 | 64 | 28 | 10 | 53 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | restore_backup_vars | restore_backup_vars | 6,758 | 6,760 | 6,758 | 6,758 | b44bbee4b7772cdca3a9f441d02c9edb71e2a2c9 | bigcode/the-stack | train |
fa36d22fbfead9bb7cdcb8b5 | train | function | def emoji_matcher_html(obj):
return (lambda x: docassemble.base.filter.emoji_html(x.group(1), images=obj.interview.images))
| def emoji_matcher_html(obj):
| return (lambda x: docassemble.base.filter.emoji_html(x.group(1), images=obj.interview.images))
| Error("Unknown data type in manual choices selection: " + re.sub(r'[<>]', '', repr(data)))
return(result)
def emoji_matcher_insert(obj):
return (lambda x: docassemble.base.filter.emoji_insert(x.group(1), images=obj.interview.images))
def emoji_matcher_html(obj):
| 64 | 64 | 31 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | emoji_matcher_html | emoji_matcher_html | 6,678 | 6,679 | 6,678 | 6,678 | 1c50141077fdb41658cb6404feb3cfef199976a2 | bigcode/the-stack | train |
b8212fff147e8aea04c78edf | train | function | def ampersand_filter(value):
if value.__class__.__name__ in ('DAFile', 'DALink', 'DAStaticFile', 'DAFileCollection', 'DAFileList'):
return value
if value.__class__.__name__ in ('InlineImage', 'RichText', 'Listing', 'Document', 'Subdoc', 'DALazyTemplate'):
return str(value)
if isinstance(valu... | def ampersand_filter(value):
| if value.__class__.__name__ in ('DAFile', 'DALink', 'DAStaticFile', 'DAFileCollection', 'DAFileList'):
return value
if value.__class__.__name__ in ('InlineImage', 'RichText', 'Listing', 'Document', 'Subdoc', 'DALazyTemplate'):
return str(value)
if isinstance(value, (int, bool, float, NoneTyp... | self.undefined(obj=obj, name=argument, accesstype='item')
def getattr(self, obj, attribute):
try:
return getattr(obj, attribute)
except AttributeError:
pass
return self.undefined(obj=obj, name=attribute, accesstype='attribute')
def ampersand_filter(value):
| 64 | 64 | 193 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | ampersand_filter | ampersand_filter | 8,972 | 8,983 | 8,972 | 8,972 | 8f1d8e5e38e647b23b99312c20e86f6c40f0d153 | bigcode/the-stack | train |
87c1a66064e0b856c038347c | train | function | def interview_source_from_string(path, **kwargs):
if path is None:
raise DAError("Passed None to interview_source_from_string")
if re.search(r'^https*://', path):
new_source = InterviewSourceURL(path=path)
if new_source.update():
return new_source
#sys.stderr.write("Tryin... | def interview_source_from_string(path, **kwargs):
| if path is None:
raise DAError("Passed None to interview_source_from_string")
if re.search(r'^https*://', path):
new_source = InterviewSourceURL(path=path)
if new_source.update():
return new_source
#sys.stderr.write("Trying to find " + path + "\n")
for the_filename in... | return (lambda x: docassemble.base.filter.emoji_insert(x.group(1), images=obj.interview.images))
def emoji_matcher_html(obj):
return (lambda x: docassemble.base.filter.emoji_html(x.group(1), images=obj.interview.images))
def interview_source_from_string(path, **kwargs):
| 64 | 64 | 190 | 10 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | interview_source_from_string | interview_source_from_string | 6,681 | 6,695 | 6,681 | 6,681 | 55182dfe28d27be5fbf71ac91fc6ec9d583871d0 | bigcode/the-stack | train |
a5d459ca441f069401bbef52 | train | function | def invalid_variable_name(varname):
if not isinstance(varname, str):
return True
if re.search(r'[\n\r\(\)\{\}\*\^\#]', varname):
return True
varname = re.sub(r'[\.\[].*', '', varname)
if not valid_variable_match.match(varname):
return True
return False
| def invalid_variable_name(varname):
| if not isinstance(varname, str):
return True
if re.search(r'[\n\r\(\)\{\}\*\^\#]', varname):
return True
varname = re.sub(r'[\.\[].*', '', varname)
if not valid_variable_match.match(varname):
return True
return False
| ':
commands.append(saveas + ' = docassemble.base.core.DAList(' + repr(saveas) + ', auto_gather=False)')
if execute:
for command in commands:
#logmessage("Doing " + command)
exec(command, the_user_dict)
def invalid_variable_name(varname):
| 64 | 64 | 80 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | invalid_variable_name | invalid_variable_name | 8,822 | 8,830 | 8,822 | 8,822 | 33a6cc295f4261bc529844a47aca1781fba4eb4e | bigcode/the-stack | train |
3d4923d7aab5ea4a926e8d58 | train | function | def join_filter(array, d="", attribute=None):
if attribute is not None:
return d.join([str(mygetattr(y, attribute)) for y in array])
return d.join([str(y) for y in array])
| def join_filter(array, d="", attribute=None):
| if attribute is not None:
return d.join([str(mygetattr(y, attribute)) for y in array])
return d.join([str(y) for y in array])
| )
yield item
else:
for item in array:
new_item = str_or_original(mygetattr(item, attribute), case_sensitive)
if new_item not in seen:
seen.add(new_item)
yield mygetattr(item, attribute)
def join_filter(array, d="", attribute=None):
| 64 | 64 | 48 | 10 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | join_filter | join_filter | 9,193 | 9,196 | 9,193 | 9,193 | acde821eda0216e7fbb80814d1dd6043eea2e2cb | bigcode/the-stack | train |
8d592b7cf8b369c888a1ca8e | train | function | def recursive_eval_data_from_code(target, the_user_dict):
if isinstance(target, dict):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_data_from_code(val, the_user_dict)
return new_dict
if isinstance(target, list):
new_list = list()
... | def recursive_eval_data_from_code(target, the_user_dict):
| if isinstance(target, dict):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_data_from_code(val, the_user_dict)
return new_dict
if isinstance(target, list):
new_list = list()
for val in target:
new_list.append(recur... | int, NoneType)):
return target
if isinstance(target, TextObject):
return target.text(the_user_dict)
else:
raise DAError("recursive_eval_dataobject: expected a TextObject, but found a " + str(type(target)))
def recursive_eval_data_from_code(target, the_user_dict):
| 64 | 64 | 160 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_eval_data_from_code | recursive_eval_data_from_code | 1,515 | 1,534 | 1,515 | 1,515 | e4fa588bca2c4ad3c0b4f305158b10dc1e951c7c | bigcode/the-stack | train |
82e486db4f26496388b44b2c | train | function | def is_threestate(field_data):
if 'choices' not in field_data:
return False
if 'has_code' in field_data:
return False
for entry in field_data['choices']:
if 'key' in entry and 'label' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(ent... | def is_threestate(field_data):
| if 'choices' not in field_data:
return False
if 'has_code' in field_data:
return False
for entry in field_data['choices']:
if 'key' in entry and 'label' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(entry['key'].original_text, (bool,... | entry and 'label' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(entry['key'].original_text, bool):
return False
else:
if not isinstance(entry['key'], bool):
return False
return True
def is_threest... | 64 | 64 | 115 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | is_threestate | is_threestate | 6,712 | 6,725 | 6,712 | 6,712 | b70c0c7d4b7065f6ae961af7609b8124ef0cecea | bigcode/the-stack | train |
c24ac511e2d0002d64317546 | train | class | class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
| class MLStripper(HTMLParser):
| def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
| , 'instanceName') and hasattr(obj, 'elements') and isinstance(obj.elements, list))):
obj = [obj]
new_list = list()
for item in obj:
if isinstance(item, str):
new_list.append(item)
return new_list
class MLStripper(HTMLParser):
| 64 | 64 | 72 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | MLStripper | MLStripper | 9,322 | 9,332 | 9,322 | 9,322 | 892682e3b4fcec351254e97c067f01c565291cb7 | bigcode/the-stack | train |
cdf640f3d02e6188839509c9 | train | function | def interpret_label(text):
if text is None:
return 'no label'
return str(text)
| def interpret_label(text):
| if text is None:
return 'no label'
return str(text)
| )
extension = filename.lower()
extension = re.sub('.*\.', '', extension)
if extension == '3gpp':
mimetype = 'audio/3gpp'
if mimetype is None:
mimetype = 'text/plain'
return mimetype
def interpret_label(text):
| 64 | 64 | 22 | 5 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | interpret_label | interpret_label | 8,733 | 8,736 | 8,733 | 8,733 | b7a586323f553cb8274d5b0ba15d457b5856fca5 | bigcode/the-stack | train |
21438272f1fb98e9a71895d8 | train | function | def allow_users_list(obj):
if not (isinstance(obj, list) or (hasattr(obj, 'instanceName') and hasattr(obj, 'elements') and isinstance(obj.elements, list))):
obj = [obj]
new_list = list()
for item in obj:
if isinstance(item, str) and re.search(r'^[0-9]+$', item):
item = int(item)
... | def allow_users_list(obj):
| if not (isinstance(obj, list) or (hasattr(obj, 'instanceName') and hasattr(obj, 'elements') and isinstance(obj.elements, list))):
obj = [obj]
new_list = list()
for item in obj:
if isinstance(item, str) and re.search(r'^[0-9]+$', item):
item = int(item)
if isinstance(item,... | for key in jinja2meta.find_undeclared_variables(parsed_content):
if not key.startswith('_'):
names.add(key)
for name in docassemble.base.legal.__all__:
if name in names:
names.remove(name)
return sorted(list(names))
def allow_users_list(obj):
| 64 | 64 | 147 | 6 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | allow_users_list | allow_users_list | 9,296 | 9,311 | 9,296 | 9,296 | 99b064aa869b38d9f78fad1a0f21429b8c466336 | bigcode/the-stack | train |
9b8f81afdff195cbbc98d967 | train | class | class InterviewSourceFile(InterviewSource):
def __init__(self, **kwargs):
self.playground = None
if 'filepath' in kwargs:
if re.search(r'SavedFile', str(type(kwargs['filepath']))):
self.playground = kwargs['filepath']
if self.playground.subdir and self.pla... | class InterviewSourceFile(InterviewSource):
| def __init__(self, **kwargs):
self.playground = None
if 'filepath' in kwargs:
if re.search(r'SavedFile', str(type(kwargs['filepath']))):
self.playground = kwargs['filepath']
if self.playground.subdir and self.playground.subdir != 'default':
... | = language
return
def set_dialect(self, dialect):
self.dialect = dialect
return
def set_testing(self, testing):
self.testing = testing
return
def set_package(self, package):
self.package = package
return
def update(self):
return True
d... | 230 | 230 | 768 | 8 | 222 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | InterviewSourceFile | InterviewSourceFile | 236 | 319 | 236 | 236 | 820f4c5d14b76949fb147888d309e99403d7dc40 | bigcode/the-stack | train |
dd07418a19212753d9894d08 | train | function | def markdown_filter(text):
return docassemble.base.file_docx.markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
| def markdown_filter(text):
| return docassemble.base.file_docx.markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
| passed to map() must be a list')
for item in pargs[0]:
yield kwargs['function'](item, *the_pargs, **the_kwargs)
else:
raise DAError('map() must refer to a function, index, attribute, or filter')
def markdown_filter(text):
| 64 | 64 | 45 | 5 | 59 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | markdown_filter | markdown_filter | 9,267 | 9,268 | 9,267 | 9,267 | 684fd3e0cca6d5e43fc8be04cb6b659d96547d5e | bigcode/the-stack | train |
e5aab18ee83fe10607cf968a | train | function | def fix_quotes(match):
instring = match.group(1)
n = len(instring)
output = ''
i = 0
while i < n:
if instring[i] == '\u201c' or instring[i] == '\u201d':
output += '"'
elif instring[i] == '\u2018' or instring[i] == '\u2019':
output += "'"
elif instring[... | def fix_quotes(match):
| instring = match.group(1)
n = len(instring)
output = ''
i = 0
while i < n:
if instring[i] == '\u201c' or instring[i] == '\u201d':
output += '"'
elif instring[i] == '\u2018' or instring[i] == '\u2019':
output += "'"
elif instring[i] == '&' and i + 4 < n... | bool, int, float, NoneType)):
return target
if isinstance(target, TextObject):
return target.text(the_user_dict)
else:
raise DAError("recursive_eval_textobject_or_primitive: expected a TextObject, but found a " + str(type(target)))
def fix_quotes(match):
| 64 | 64 | 153 | 5 | 59 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | fix_quotes | fix_quotes | 1,627 | 1,643 | 1,627 | 1,627 | 64c3e213e3a002b403701338e97d13362fa770cc | bigcode/the-stack | train |
ce0386abf4584d9aa8c56394 | train | function | def unique_filter(array, case_sensitive=False, attribute=None):
seen = set()
if attribute is None:
for item in array:
new_item = str_or_original(item, case_sensitive)
if new_item not in seen:
seen.add(new_item)
yield item
else:
for item... | def unique_filter(array, case_sensitive=False, attribute=None):
| seen = set()
if attribute is None:
for item in array:
new_item = str_or_original(item, case_sensitive)
if new_item not in seen:
seen.add(new_item)
yield item
else:
for item in array:
new_item = str_or_original(mygetattr(item... | ([first], it), key=key_func)
def sum_filter(array, attribute=None, start=0):
if attribute is not None:
array = [mygetattr(y, attribute) for y in array]
return sum(array, start)
def unique_filter(array, case_sensitive=False, attribute=None):
| 64 | 64 | 108 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | unique_filter | unique_filter | 9,178 | 9,191 | 9,178 | 9,178 | 2bf6dcadaf98ef36cf0d0767902c1cdb05165a1a | bigcode/the-stack | train |
ce8ae7d1ccfd46a32e31c2d5 | train | function | def get_initial_dict():
return copy.deepcopy(initial_dict);
| def get_initial_dict():
| return copy.deepcopy(initial_dict);
| =None, modtime=None, accesstime=dict(), tasks=dict(), gather=list(), event_stack=dict(), misc=dict()), url_args=dict(), nav=docassemble.base.functions.DANav())
def set_initial_dict(the_dict):
global initial_dict
initial_dict = the_dict
return
def get_initial_dict():
| 64 | 64 | 12 | 5 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | get_initial_dict | get_initial_dict | 130 | 131 | 130 | 130 | 0722ba5b8b7d981b7f8c359c98af06152b8de19e | bigcode/the-stack | train |
f2de5fe2beab5aad092492f9 | train | function | def textify(data, the_user_dict):
return list(map((lambda x: x.text(the_user_dict)), data))
| def textify(data, the_user_dict):
| return list(map((lambda x: x.text(the_user_dict)), data))
| , the_user_dict):
output = list()
for the_item in the_list:
output.append({'text': the_item['text'].text(the_user_dict), 'package': the_item['package'], 'type': the_item['type']})
return output
def textify(data, the_user_dict):
| 64 | 64 | 25 | 9 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | textify | textify | 92 | 93 | 92 | 92 | 718691d47b91fd8f693984c5b3249467ba07f853 | bigcode/the-stack | train |
5f6ac0936499526b0e42ffea | train | function | def recursive_update(base, target):
for key, val in target.items():
if isinstance(val, abc.Mapping):
base[key] = recursive_update(base.get(key, {}), val)
else:
base[key] = val
return base
| def recursive_update(base, target):
| for key, val in target.items():
if isinstance(val, abc.Mapping):
base[key] = recursive_update(base.get(key, {}), val)
else:
base[key] = val
return base
| '], TextObject):
if not isinstance(entry['key'].original_text, (bool, NoneType)):
return False
else:
if not isinstance(entry['key'], (bool, NoneType)):
return False
return True
class TableInfo:
pass
def recursive_update(base, t... | 64 | 64 | 53 | 7 | 56 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_update | recursive_update | 6,730 | 6,736 | 6,730 | 6,730 | 531c96fce61c50d02e1224229f4f90c33fe6c960 | bigcode/the-stack | train |
68f7e0b129b8b3ce78292160 | train | class | class TextObject:
def __deepcopy__(self, memo):
return TextObject(self.original_text)
def __init__(self, x, question=None, translate=True):
self.original_text = x
self.other_lang = dict()
if translate and question is not None and question.interview.source.translating and isinstan... | class TextObject:
| def __deepcopy__(self, memo):
return TextObject(self.original_text)
def __init__(self, x, question=None, translate=True):
self.original_text = x
self.other_lang = dict()
if translate and question is not None and question.interview.source.translating and isinstance(x, str) and re.... | ["answers"][' + repr(question.extended_question_name(the_user_dict)) + ']')
if 'image' in choice:
the_image = self.icon_url(choice['image'])
if the_image:
item['image'] = the_image
if 'help' in choice:
it... | 171 | 171 | 573 | 4 | 167 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | TextObject | TextObject | 1,324 | 1,370 | 1,324 | 1,324 | 28dee377525d2b0fde12513132bd9e470b64426d | bigcode/the-stack | train |
077598a1337303b26fe42137 | train | function | def max_filter(array, case_sensitive=False, attribute=None):
it = iter(array)
try:
first = next(it)
except StopIteration:
raise DAError("max: list was empty")
if attribute:
def key_func(y):
return str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)... | def max_filter(array, case_sensitive=False, attribute=None):
| it = iter(array)
try:
first = next(it)
except StopIteration:
raise DAError("max: list was empty")
if attribute:
def key_func(y):
return str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)
else:
def key_func(y):
return str_or... | str__
def groupby_filter(array, attr_name):
def func(y):
return mygetattr(y, attr_name)
return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(array, key=func), func)]
def max_filter(array, case_sensitive=False, attribute=None):
| 64 | 64 | 107 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | max_filter | max_filter | 9,145 | 9,157 | 9,145 | 9,145 | a76713bb1ecc776a9f9be605a3ddcedbdab7de15 | bigcode/the-stack | train |
c9416220b2faae7cf88ea8b6 | train | function | def unqualified_name(variable, the_user_dict):
if variable == 'x' or variable.startswith('x[') or variable.startswith('x.') and 'x' in the_user_dict and hasattr(the_user_dict['x'], 'instanceName'):
variable = re.sub(r'^x', the_user_dict['x'].instanceName, variable)
for index_var in ['i', 'j', 'k', 'l', ... | def unqualified_name(variable, the_user_dict):
| if variable == 'x' or variable.startswith('x[') or variable.startswith('x.') and 'x' in the_user_dict and hasattr(the_user_dict['x'], 'instanceName'):
variable = re.sub(r'^x', the_user_dict['x'].instanceName, variable)
for index_var in ['i', 'j', 'k', 'l', 'm', 'n']:
if '[' + index_var + ']' in ... | ), val)
else:
base[key] = val
return base
def recursive_add_classes(class_list, the_class):
for cl in the_class.__bases__:
class_list.append(cl.__name__)
recursive_add_classes(class_list, cl)
def unqualified_name(variable, the_user_dict):
| 64 | 64 | 144 | 10 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | unqualified_name | unqualified_name | 6,743 | 6,749 | 6,743 | 6,743 | d2f35d3b21d4999d9d66bafc4372064cd1d12615 | bigcode/the-stack | train |
47d59a1299c86c0de2092f2e | train | function | def inline_markdown_filter(text):
return docassemble.base.file_docx.inline_markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
| def inline_markdown_filter(text):
| return docassemble.base.file_docx.inline_markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
| refer to a function, index, attribute, or filter')
def markdown_filter(text):
return docassemble.base.file_docx.markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
def inline_markdown_filter(text):
| 64 | 64 | 48 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | inline_markdown_filter | inline_markdown_filter | 9,270 | 9,271 | 9,270 | 9,270 | 1ad05595565ce58ae110beaa22845d862c845fde | bigcode/the-stack | train |
54e26dcd1ec556032060877c | train | class | class Interview:
def __init__(self, **kwargs):
self.source = None
self.questions = dict()
self.generic_questions = dict()
self.questions_by_id = dict()
self.questions_by_name = dict()
self.questions_list = list()
self.all_questions = list()
self.progre... | class Interview:
| def __init__(self, **kwargs):
self.source = None
self.questions = dict()
self.generic_questions = dict()
self.questions_by_id = dict()
self.questions_by_name = dict()
self.questions_list = list()
self.all_questions = list()
self.progress_points = set()... | .__bases__:
class_list.append(cl.__name__)
recursive_add_classes(class_list, cl)
def unqualified_name(variable, the_user_dict):
if variable == 'x' or variable.startswith('x[') or variable.startswith('x.') and 'x' in the_user_dict and hasattr(the_user_dict['x'], 'instanceName'):
variable = r... | 256 | 256 | 21,139 | 3 | 252 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | Interview | Interview | 6,762 | 8,548 | 6,762 | 6,762 | 448d1f45ff397ee955138e1990d3cedc3526de2e | bigcode/the-stack | train |
e342fe36d75ab35ee09dcaf4 | train | class | class Field:
def __init__(self, data):
if 'number' in data:
self.number = data['number']
else:
self.number = 0
if 'saveas' in data:
self.saveas = safeid(data['saveas'])
if 'saveas_code' in data:
self.saveas_code = data['saveas_code']
... | class Field:
| def __init__(self, data):
if 'number' in data:
self.number = data['number']
else:
self.number = 0
if 'saveas' in data:
self.saveas = safeid(data['saveas'])
if 'saveas_code' in data:
self.saveas_code = data['saveas_code']
if 'sho... | [target_lang] = (question.interview.translation_dict[self.original_text][orig_lang][target_lang],)
def text(self, the_user_dict):
if len(self.other_lang):
target_lang = docassemble.base.functions.get_language()
if self.language != target_lang and target_lang in self.other_lang:
... | 256 | 256 | 1,077 | 3 | 253 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | Field | Field | 1,384 | 1,490 | 1,384 | 1,384 | e6aa7eaf4d6cd695e2a1e71b23e7fe31f531cdd8 | bigcode/the-stack | train |
c64e13e1fb142c92d864aff9 | train | function | def reproduce_basics(interview, new_interview):
new_interview.metadata = interview.metadata
new_interview.external_files = interview.external_files
| def reproduce_basics(interview, new_interview):
| new_interview.metadata = interview.metadata
new_interview.external_files = interview.external_files
| new_dict
elif isinstance(action, list):
new_list = list()
for item in action:
new_list.append(substitute_vars_action(item, is_generic, the_x, iterators))
return new_list
else:
return action
def reproduce_basics(interview, new_interview):
| 64 | 64 | 31 | 11 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | reproduce_basics | reproduce_basics | 8,590 | 8,592 | 8,590 | 8,590 | 7ebf50939a28195da5896d98a30bb0cf8fcb50ae | bigcode/the-stack | train |
907c6fff9eb3b5d8bfef882f | train | function | def extract_missing_name(the_error):
#logmessage("extract_missing_name: string was " + str(string))
m = nameerror_match.search(str(the_error))
if m:
return m.group(1)
else:
raise the_error
| def extract_missing_name(the_error):
#logmessage("extract_missing_name: string was " + str(string))
| m = nameerror_match.search(str(the_error))
if m:
return m.group(1)
else:
raise the_error
| lections: non-label passed as label in dictionary")
else:
raise DAError("Unknown data type in choices selection: " + re.sub(r'[<>]', '', repr(data)))
return(result)
def extract_missing_name(the_error):
#logmessage("extract_missing_name: string was " + str(string))
| 64 | 64 | 53 | 23 | 41 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | extract_missing_name | extract_missing_name | 8,681 | 8,687 | 8,681 | 8,682 | 96cadf2c96addf0f22b0d934a6f104bb1de5924e | bigcode/the-stack | train |
de3f0f723ffbeb7d48f71a41 | train | function | def rejectattr_filter(*pargs, **kwargs):
if len(pargs) > 2:
array = pargs[0]
attr_name = pargs[1]
func_name = pargs[2]
env = custom_jinja_env()
func = lambda item: env.call_test(func_name, item, pargs[3:], kwargs)
for item in array:
if not func(mygetattr(i... | def rejectattr_filter(*pargs, **kwargs):
| if len(pargs) > 2:
array = pargs[0]
attr_name = pargs[1]
func_name = pargs[2]
env = custom_jinja_env()
func = lambda item: env.call_test(func_name, item, pargs[3:], kwargs)
for item in array:
if not func(mygetattr(item, attr_name)):
yield i... | 3:], kwargs)
for item in array:
if func(mygetattr(item, attr_name)):
yield item
else:
for item in pargs[0]:
if mygetattr(item, pargs[1]):
yield item
def rejectattr_filter(*pargs, **kwargs):
| 64 | 64 | 127 | 11 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | rejectattr_filter | rejectattr_filter | 9,216 | 9,229 | 9,216 | 9,216 | 54c09d6b514ffc61f9c75d231f5e873bdaa7395e | bigcode/the-stack | train |
8c82dcad5e51d0e20688c1eb | train | function | def make_backup_vars(the_user_dict):
backups = dict()
for var in ['x', 'i', 'j', 'k', 'l', 'm', 'n']:
if var in the_user_dict:
backups[var] = the_user_dict[var]
return backups
| def make_backup_vars(the_user_dict):
| backups = dict()
for var in ['x', 'i', 'j', 'k', 'l', 'm', 'n']:
if var in the_user_dict:
backups[var] = the_user_dict[var]
return backups
| m', 'n']:
if '[' + index_var + ']' in variable and index_var in the_user_dict:
variable = re.sub(r'\[' + index_var + '\]', '[' + repr(the_user_dict[index_var]) + ']', variable)
return variable
def make_backup_vars(the_user_dict):
| 64 | 64 | 60 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | make_backup_vars | make_backup_vars | 6,751 | 6,756 | 6,751 | 6,751 | decd614e27e7ab4cc83c812f383b622941b27dd3 | bigcode/the-stack | train |
4c7d7c610ef4340289f0cfdf | train | function | def recursive_add_classes(class_list, the_class):
for cl in the_class.__bases__:
class_list.append(cl.__name__)
recursive_add_classes(class_list, cl)
| def recursive_add_classes(class_list, the_class):
| for cl in the_class.__bases__:
class_list.append(cl.__name__)
recursive_add_classes(class_list, cl)
|
def recursive_update(base, target):
for key, val in target.items():
if isinstance(val, abc.Mapping):
base[key] = recursive_update(base.get(key, {}), val)
else:
base[key] = val
return base
def recursive_add_classes(class_list, the_class):
| 64 | 64 | 37 | 10 | 53 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_add_classes | recursive_add_classes | 6,738 | 6,741 | 6,738 | 6,738 | f0e3e94e28ff62ccd63b543c317a34549ae9ed24 | bigcode/the-stack | train |
13b24647b82a122293f174d5 | train | class | class InterviewSourceString(InterviewSource):
def __init__(self, **kwargs):
self.set_path(kwargs.get('path', None))
self.set_directory(kwargs.get('directory', None))
self.set_content(kwargs.get('content', None))
self._modtime = datetime.datetime.utcnow()
return super().__init... | class InterviewSourceString(InterviewSource):
| def __init__(self, **kwargs):
self.set_path(kwargs.get('path', None))
self.set_directory(kwargs.get('directory', None))
self.set_content(kwargs.get('content', None))
self._modtime = datetime.datetime.utcnow()
return super().__init__(**kwargs)
| _dialect(self):
return self.dialect
def get_package(self):
return self.package
def get_testing(self):
return self.testing
def get_interview(self):
return Interview(source=self)
def append(self, path):
return None
class InterviewSourceString(InterviewSource):
| 64 | 64 | 70 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | InterviewSourceString | InterviewSourceString | 228 | 234 | 228 | 228 | 8ac65326b0855c39afd2fb4e1f5e5e1a255b0df0 | bigcode/the-stack | train |
f093b1733420fba4742b6dab | train | function | def sort_filter(array, reverse=False, case_sensitive=False, attribute=None):
if attribute is None:
if not case_sensitive:
def key_func(y):
return str_or_original(y, case_sensitive)
else:
key_func = None
else:
if isinstance(attribute, list):
... | def sort_filter(array, reverse=False, case_sensitive=False, attribute=None):
| if attribute is None:
if not case_sensitive:
def key_func(y):
return str_or_original(y, case_sensitive)
else:
key_func = None
else:
if isinstance(attribute, list):
attributes = [str(y).strip() for y in attribute]
else:
... | sorted(dictionary.items(), key=lambda y: str_or_original(y[1], case_sensitive), reverse=reverse)
else:
return sorted(dictionary.items(), key=lambda y: str_or_original(y[0], case_sensitive), reverse=reverse)
def sort_filter(array, reverse=False, case_sensitive=False, attribute=None):
| 64 | 64 | 136 | 15 | 49 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | sort_filter | sort_filter | 9,120 | 9,134 | 9,120 | 9,120 | 669da43d460ce04b52c156233e13625a6f067f5c | bigcode/the-stack | train |
de435652d9afd0227275af06 | train | function | def set_initial_dict(the_dict):
global initial_dict
initial_dict = the_dict
return
| def set_initial_dict(the_dict):
| global initial_dict
initial_dict = the_dict
return
| roles=list(), partner_roles=list()), answered=set(), answers=dict(), objselections=dict(), starttime=None, modtime=None, accesstime=dict(), tasks=dict(), gather=list(), event_stack=dict(), misc=dict()), url_args=dict(), nav=docassemble.base.functions.DANav())
def set_initial_dict(the_dict):
| 64 | 64 | 22 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | set_initial_dict | set_initial_dict | 125 | 128 | 125 | 125 | edcd5d2de54406c919d9b2abec943843a4db62bf | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.