index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32,732 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/services/v2_9/workers.py | 2456,2458 | 2424,2466 | worker | UnregisterRequest | 2458,2466 | 2458,2466 | class UnregisterRequest(Request):
"""
Unregister a worker in the system. Called by the Worker Daemon.
:param worker: Worker id. Must be unique in company.
:type worker: str
"""
_service = "workers"
_action = "unregister"
_version = "2.9"
_schema = {
'definitions': {},
... | class UnregisterRequest(Request):
"""
Unregister a worker in the system. Called by the Worker Daemon.
:param worker: Worker id. Must be unique in company.
:type worker: str
"""
_service = "workers"
_action = "unregister"
_version = "2.9"
_schema = {
'definitions': {},
... | if value is None:
self._property_worker = None
return
self.assert_isinstance(value, "worker", six.string_types)
self._property_worker = value
| if value is None:
self._property_worker = None
return
self.assert_isinstance(value, "worker", six.string_types)
self._property_worker = value
| 14 | 252 | 59 | 311 | """
workers service
Provides an API for worker machines, allowing workers to report status and get tasks for execution
"""
import enum
from datetime import datetime
import six
from dateutil.parser import parse as parse_datetime
from ....backend_api.session import NonStrictDataModel, Request, Response, schema_propert... | """
workers service
Provides an API for worker machines, allowing workers to report status and get tasks for execution
"""
import enum
from datetime import datetime
import six
from dateutil.parser import parse as parse_datetime
from ....backend_api.session import NonStrictDataModel, Request, Response, schema_propert... |
32,734 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/services/v2_9/workers.py | 338,340 | 306,365 | worker | WorkerStats | 340,347 | 340,347 | class WorkerStats(NonStrictDataModel):
"""
:param worker: ID of the worker
:type worker: str
:param metrics: List of the metrics statistics for the worker
:type metrics: Sequence[MetricStats]
"""
_schema = {
'properties': {
'metrics': {
'description': 'Lis... | class WorkerStats(NonStrictDataModel):
"""
:param worker: ID of the worker
:type worker: str
:param metrics: List of the metrics statistics for the worker
:type metrics: Sequence[MetricStats]
"""
_schema = {
'properties': {
'metrics': {
'description': 'Lis... | if value is None:
self._property_worker = None
return
self.assert_isinstance(value, "worker", six.string_types)
self._property_worker = value
| if value is None:
self._property_worker = None
return
self.assert_isinstance(value, "worker", six.string_types)
self._property_worker = value
| 14 | 451 | 57 | 508 | """
workers service
Provides an API for worker machines, allowing workers to report status and get tasks for execution
"""
import enum
from datetime import datetime
import six
from dateutil.parser import parse as parse_datetime
from ....backend_api.session import NonStrictDataModel, Request, Response, schema_propert... | """
workers service
Provides an API for worker machines, allowing workers to report status and get tasks for execution
"""
import enum
from datetime import datetime
import six
from dateutil.parser import parse as parse_datetime
from ....backend_api.session import NonStrictDataModel, Request, Response, schema_propert... |
32,735 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/callresult.py | 124,125 | 10,150 | wait | CallResult | 125,148 | 125,148 | class CallResult(object):
@property
def meta(self):
return self.__meta
@property
def response(self):
return self.__response
@property
def response_data(self):
return self.__response_data
@property
def async_accepted(self):
return self.meta.result_code =... | class CallResult(object):
@property
def meta(self):
return self.__meta
@property
def response(self):
return self.__response
@property
def response_data(self):
return self.__response_data
@property
def async_accepted(self):
return self.meta.result_code =... | if not self.async_accepted:
return self
session = self.__session
poll_interval = max(1, poll_interval)
remaining = max(0, timeout) if timeout else sys.maxsize
while remaining > 0:
if not self.ready():
# Still pending, log and continue
... | if not self.async_accepted:
return self
session = self.__session
poll_interval = max(1, poll_interval)
remaining = max(0, timeout) if timeout else sys.maxsize
while remaining > 0:
if not self.ready():
# Still pending, log and continue
... | 104 | 1,197 | 297 | 1,494 | import sys
import time
from ...backend_api.utils import get_response_cls
from .response import ResponseMeta, Response
from .errors import ResultNotReadyError, TimeoutExpiredError
class CallResult(object):
@property
def meta(self):
return self.__meta
@property
def response(self):
ret... | import sys
import time
from ...backend_api.utils import get_response_cls
from .response import ResponseMeta, Response
from .errors import ResultNotReadyError, TimeoutExpiredError
class CallResult(object):
@property
def meta(self):
return self.__meta
@property
def response(self):
ret... |
32,736 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/datamodel.py | 13,14 | 1,180 | format_date | 14,18 | 14,18 | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
FILL_FUNC_BODYclass SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.... | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
FILL_FUNC_BODYclass SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.... | if isinstance(obj, datetime):
return str(obj)
| if isinstance(obj, datetime):
return str(obj)
| 5 | 1,533 | 23 | 1,556 | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
FILL_FUNC_BODYclass SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.... | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
FILL_FUNC_BODYclass SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.... | |
32,737 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/datamodel.py | 79,80 | 49,146 | to_dict | DataModel | 80,87 | 80,87 | class DataModel(object):
""" Data Model"""
_schema = None
_data_props_list = None
@classmethod
def _get_data_props(cls):
props = cls._data_props_list
if props is None:
props = {}
for c in cls.__mro__:
props.update({k: getattr(v, 'name', k) for... | class DataModel(object):
""" Data Model"""
_schema = None
_data_props_list = None
@classmethod
def _get_data_props(cls):
props = cls._data_props_list
if props is None:
props = {}
for c in cls.__mro__:
props.update({k: getattr(v, 'name', k) for... | prop_values = {v: getattr(self, k) for k, v in self._get_data_props().items()}
return {
k: self._to_base_type(v)
for k, v in prop_values.items()
if v is not None and (not only or k in only) and (not except_ or k not in except_)
}
| prop_values = {v: getattr(self, k) for k, v in self._get_data_props().items()}
return {
k: self._to_base_type(v)
for k, v in prop_values.items()
if v is not None and (not only or k in only) and (not except_ or k not in except_)
}
| 40 | 879 | 101 | 980 | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... |
32,738 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/datamodel.py | 23,24 | 18,27 | setter | SchemaProperty | 24,27 | 24,27 | class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.name = name
def setter(self, fset):
FILL_FUNC_BODY | class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty, self).__init__(*args, **kwargs)
self.name = name
def setter(self, fset):
FILL_FUNC_BODY | return type(self)(self.name, self.fget, fset, self.fdel, self.__doc__)
| return type(self)(self.name, self.fget, fset, self.fdel, self.__doc__)
| 6 | 73 | 33 | 106 | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... |
32,739 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/datamodel.py | 177,179 | 172,180 | has_value | StringEnum | 179,180 | 179,180 | class StringEnum(Enum):
def __str__(self):
return self.value
@classmethod
def has_value(cls, value):
FILL_FUNC_BODY | class StringEnum(Enum):
def __str__(self):
return self.value
@classmethod
def has_value(cls, value):
FILL_FUNC_BODY | return value in cls._value2member_map_
| return value in cls._value2member_map_
| 4 | 49 | 15 | 64 | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... | import keyword
import enum
import json
from datetime import datetime
import jsonschema
from enum import Enum
import six
def format_date(obj):
if isinstance(obj, datetime):
return str(obj)
class SchemaProperty(property):
def __init__(self, name=None, *args, **kwargs):
super(SchemaProperty,... |
32,740 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 125,126 | 1,231 | _apply_validators_modifications | 126,133 | 126,133 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | for validator in field.validators:
try:
validator.modify_schema(field_schema)
except AttributeError:
pass
| for validator in field.validators:
try:
validator.modify_schema(field_schema)
except AttributeError:
pass
| 9 | 1,791 | 48 | 1,839 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | |
32,741 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 41,42 | 13,58 | count_type | Builder | 42,47 | 42,47 | class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
self.parent = parent
self.types_builders = {}
self.types_count = defaultdict(int)
self.definitions = set()
self.nullable = nullable
self.default = default
@property
def h... | class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
self.parent = parent
self.types_builders = {}
self.types_count = defaultdict(int)
self.definitions = set()
self.nullable = nullable
self.default = default
@property
def h... | if self.parent:
return self.parent.count_type(type)
return self.types_count[type]
| if self.parent:
return self.parent.count_type(type)
return self.types_count[type]
| 6 | 327 | 38 | 365 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... |
32,742 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 211,212 | 202,231 | build | EmbeddedBuilder | 212,228 | 212,228 | class EmbeddedBuilder(Builder):
def __init__(self, *args, **kwargs):
super(EmbeddedBuilder, self).__init__(*args, **kwargs)
self.schemas = []
def add_type_schema(self, schema):
self.schemas.append(schema)
def build(self):
FILL_FUNC_BODY @property
def is_definition(self):
... | class EmbeddedBuilder(Builder):
def __init__(self, *args, **kwargs):
super(EmbeddedBuilder, self).__init__(*args, **kwargs)
self.schemas = []
def add_type_schema(self, schema):
self.schemas.append(schema)
def build(self):
FILL_FUNC_BODY @property
def is_definition(self):
... | if self.nullable:
self.add_type_schema({'type': 'null'})
schemas = [self.maybe_build(schema) for schema in self.schemas]
if len(schemas) == 1:
schema = schemas[0]
else:
schema = {'oneOf': schemas}
if self.has_default:
# The defaul... | if self.nullable:
self.add_type_schema({'type': 'null'})
schemas = [self.maybe_build(schema) for schema in self.schemas]
if len(schemas) == 1:
schema = schemas[0]
else:
schema = {'oneOf': schemas}
if self.has_default:
# The defaul... | 51 | 117 | 164 | 281 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... |
32,743 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 173,174 | 164,202 | build | ListBuilder | 174,190 | 174,190 | class ListBuilder(Builder):
def __init__(self, *args, **kwargs):
super(ListBuilder, self).__init__(*args, **kwargs)
self.schemas = []
def add_type_schema(self, schema):
self.schemas.append(schema)
def build(self):
FILL_FUNC_BODY @property
def is_definition(self):
re... | class ListBuilder(Builder):
def __init__(self, *args, **kwargs):
super(ListBuilder, self).__init__(*args, **kwargs)
self.schemas = []
def add_type_schema(self, schema):
self.schemas.append(schema)
def build(self):
FILL_FUNC_BODY @property
def is_definition(self):
re... | schema = {'type': 'array'}
if self.nullable:
self.add_type_schema({'type': 'null'})
if self.has_default:
schema["default"] = [self.to_struct(i) for i in self.default]
schemas = [self.maybe_build(s) for s in self.schemas]
if len(schemas) == 1:
... | schema = {'type': 'array'}
if self.nullable:
self.add_type_schema({'type': 'null'})
if self.has_default:
schema["default"] = [self.to_struct(i) for i in self.default]
schemas = [self.maybe_build(s) for s in self.schemas]
if len(schemas) == 1:
... | 41 | 159 | 154 | 313 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... |
32,744 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 111,113 | 58,125 | is_definition | ObjectBuilder | 113,120 | 113,120 | class ObjectBuilder(Builder):
def __init__(self, model_type, *args, **kwargs):
super(ObjectBuilder, self).__init__(*args, **kwargs)
self.properties = {}
self.required = []
self.type = model_type
self.register_type(self.type, self)
def add_field(self, name, field, schem... | class ObjectBuilder(Builder):
def __init__(self, model_type, *args, **kwargs):
super(ObjectBuilder, self).__init__(*args, **kwargs)
self.properties = {}
self.required = []
self.type = model_type
self.register_type(self.type, self)
def add_field(self, name, field, schem... | if self.count_type(self.type) > 1:
return True
elif self.parent:
return self.parent.is_definition
else:
return False
| if self.count_type(self.type) > 1:
return True
elif self.parent:
return self.parent.is_definition
else:
return False
| 13 | 538 | 53 | 591 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... |
32,745 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/builders.py | 139,140 | 133,164 | build | PrimitiveBuilder | 140,164 | 140,164 | class PrimitiveBuilder(Builder):
def __init__(self, type, *args, **kwargs):
super(PrimitiveBuilder, self).__init__(*args, **kwargs)
self.type = type
def build(self):
FILL_FUNC_BODY | class PrimitiveBuilder(Builder):
def __init__(self, type, *args, **kwargs):
super(PrimitiveBuilder, self).__init__(*args, **kwargs)
self.type = type
def build(self):
FILL_FUNC_BODY | schema = {}
if issubclass(self.type, six.string_types):
obj_type = 'string'
elif issubclass(self.type, bool):
obj_type = 'boolean'
elif issubclass(self.type, int):
obj_type = 'number'
elif issubclass(self.type, float):
obj_type = 'n... | schema = {}
if issubclass(self.type, six.string_types):
obj_type = 'string'
elif issubclass(self.type, bool):
obj_type = 'boolean'
elif issubclass(self.type, int):
obj_type = 'number'
elif issubclass(self.type, float):
obj_type = 'n... | 52 | 69 | 212 | 281 | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... | """Builders to generate in memory representation of model and fields tree."""
from __future__ import absolute_import
from collections import defaultdict
import six
from . import errors
from .fields import NotSet
class Builder(object):
def __init__(self, parent=None, nullable=False, default=NotSet):
s... |
32,746 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/collections.py | 15,16 | 3,22 | append | ModelCollection | 16,19 | 16,19 | class ModelCollection(list):
"""`ModelCollection` is list which validates stored values.
Validation is made with use of field passed to `__init__` at each point,
when new value is assigned.
"""
def __init__(self, field):
self.field = field
def append(self, value):
FILL_FUNC_BODY ... | class ModelCollection(list):
"""`ModelCollection` is list which validates stored values.
Validation is made with use of field passed to `__init__` at each point,
when new value is assigned.
"""
def __init__(self, field):
self.field = field
def append(self, value):
FILL_FUNC_BODY ... | self.field.validate_single_value(value)
super(ModelCollection, self).append(value)
| self.field.validate_single_value(value)
super(ModelCollection, self).append(value)
| 3 | 139 | 31 | 170 |
class ModelCollection(list):
"""`ModelCollection` is list which validates stored values.
Validation is made with use of field passed to `__init__` at each point,
when new value is assigned.
"""
def __init__(self, field):
self.field = field
def append(self, value):
FILL_FUNC_BODY ... |
class ModelCollection(list):
"""`ModelCollection` is list which validates stored values.
Validation is made with use of field passed to `__init__` at each point,
when new value is assigned.
"""
def __init__(self, field):
self.field = field
def append(self, value):
FILL_FUNC_BODY ... |
32,748 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 97,98 | 17,144 | _check_types | BaseField | 98,103 | 98,103 | class BaseField(object):
"""Base class for all fields."""
types = None
def __init__(
self,
required=False,
nullable=False,
help_text=None,
validators=None,
default=NotSet,
name=None):
self.memory = WeakKeyDictiona... | class BaseField(object):
"""Base class for all fields."""
types = None
def __init__(
self,
required=False,
nullable=False,
help_text=None,
validators=None,
default=NotSet,
name=None):
self.memory = WeakKeyDictiona... | if self.types is None:
raise ValidationError(
'Field "{type}" is not usable, try '
'different field type.'.format(type=type(self).__name__))
| if self.types is None:
raise ValidationError(
'Field "{type}" is not usable, try '
'different field type.'.format(type=type(self).__name__))
| 16 | 983 | 57 | 1,040 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,749 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 178,179 | 172,184 | parse_value | BoolField | 180,184 | 179,184 | class BoolField(BaseField):
"""Bool field."""
types = (bool,)
def parse_value(self, value):
FILL_FUNC_BODY | class BoolField(BaseField):
"""Bool field."""
types = (bool,)
def parse_value(self, value):
"""Cast value to `bool`."""
FILL_FUNC_BODY | parsed = super(BoolField, self).parse_value(value)
return bool(parsed) if parsed is not None else None
| """Cast value to `bool`."""
parsed = super(BoolField, self).parse_value(value)
return bool(parsed) if parsed is not None else None
| 13 | 56 | 38 | 94 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,750 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 450,451 | 427,459 | parse_value | DateField | 452,459 | 451,459 | class DateField(StringField):
"""Date field."""
types = (datetime.date,)
default_format = '%Y-%m-%d'
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast date to (if `None` - casting to
%Y-%m-%d format).
"""
... | class DateField(StringField):
"""Date field."""
types = (datetime.date,)
default_format = '%Y-%m-%d'
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast date to (if `None` - casting to
%Y-%m-%d format).
"""
... | if value is None:
return value
if isinstance(value, datetime.date):
return value
return parse(value).date()
| """Parse string into instance of `date`."""
if value is None:
return value
if isinstance(value, datetime.date):
return value
return parse(value).date()
| 13 | 230 | 45 | 275 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,751 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 481,482 | 459,489 | parse_value | DateTimeField | 483,489 | 482,489 | class DateTimeField(StringField):
"""Datetime field."""
types = (datetime.datetime,)
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast datetime to (if `None` - casting
to ISO 8601 format).
"""
self.str_format... | class DateTimeField(StringField):
"""Datetime field."""
types = (datetime.datetime,)
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast datetime to (if `None` - casting
to ISO 8601 format).
"""
self.str_format... | if isinstance(value, datetime.datetime):
return value
if value:
return parse(value)
else:
return None
| """Parse string into instance of `datetime`."""
if isinstance(value, datetime.datetime):
return value
if value:
return parse(value)
else:
return None
| 12 | 207 | 42 | 249 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,752 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 311,312 | 291,350 | _finish_initialization | EmbeddedField | 312,322 | 312,322 | class EmbeddedField(BaseField):
"""Field for embedded models."""
def __init__(self, model_types, *args, **kwargs):
self._assign_model_types(model_types)
super(EmbeddedField, self).__init__(*args, **kwargs)
def _assign_model_types(self, model_types):
if not isinstance(model_types, ... | class EmbeddedField(BaseField):
"""Field for embedded models."""
def __init__(self, model_types, *args, **kwargs):
self._assign_model_types(model_types)
super(EmbeddedField, self).__init__(*args, **kwargs)
def _assign_model_types(self, model_types):
if not isinstance(model_types, ... | super(EmbeddedField, self)._finish_initialization(owner)
types = []
for type in self.types:
if isinstance(type, _LazyType):
types.append(type.evaluate(owner))
else:
types.append(type)
self.types = tuple(types)
| super(EmbeddedField, self)._finish_initialization(owner)
types = []
for type in self.types:
if isinstance(type, _LazyType):
types.append(type.evaluate(owner))
else:
types.append(type)
self.types = tuple(types)
| 18 | 423 | 95 | 518 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,753 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 157,158 | 151,165 | parse_value | IntField | 159,165 | 158,165 | class IntField(BaseField):
"""Integer field."""
types = (int,)
def parse_value(self, value):
FILL_FUNC_BODY | class IntField(BaseField):
"""Integer field."""
types = (int,)
def parse_value(self, value):
"""Cast value to `int`, e.g. from string or long"""
FILL_FUNC_BODY | parsed = super(IntField, self).parse_value(value)
if parsed is None:
return parsed
return int(parsed)
| """Cast value to `int`, e.g. from string or long"""
parsed = super(IntField, self).parse_value(value)
if parsed is None:
return parsed
return int(parsed)
| 12 | 64 | 44 | 108 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,754 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 245,246 | 184,291 | parse_value | ListField | 247,257 | 246,257 | class ListField(BaseField):
"""List field."""
types = (list,)
def __init__(self, items_types=None, *args, **kwargs):
"""Init.
`ListField` is **always not required**. If you want to control number
of items use validators.
"""
self._assign_types(items_types)
... | class ListField(BaseField):
"""List field."""
types = (list,)
def __init__(self, items_types=None, *args, **kwargs):
"""Init.
`ListField` is **always not required**. If you want to control number
of items use validators.
"""
self._assign_types(items_types)
... | result = self.get_default_value()
if not values:
return result
if not isinstance(values, list):
return values
return [self._cast_value(value) for value in values]
| """Cast value to proper collection."""
result = self.get_default_value()
if not values:
return result
if not isinstance(values, list):
return values
return [self._cast_value(value) for value in values]
| 20 | 814 | 68 | 882 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,755 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 418,419 | 396,427 | parse_value | TimeField | 420,427 | 419,427 | class TimeField(StringField):
"""Time field."""
types = (datetime.time,)
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast time to (if `None` - casting to
ISO 8601 format).
"""
self.str_format = str_format
... | class TimeField(StringField):
"""Time field."""
types = (datetime.time,)
def __init__(self, str_format=None, *args, **kwargs):
"""Init.
:param str str_format: Format to cast time to (if `None` - casting to
ISO 8601 format).
"""
self.str_format = str_format
... | if value is None:
return value
if isinstance(value, datetime.time):
return value
return parse(value).timetz()
| """Parse string into instance of `time`."""
if value is None:
return value
if isinstance(value, datetime.time):
return value
return parse(value).timetz()
| 13 | 206 | 47 | 253 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,756 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/fields.py | 355,356 | 350,360 | evaluate | _LazyType | 356,360 | 356,360 | class _LazyType(object):
def __init__(self, path):
self.path = path
def evaluate(self, base_cls):
FILL_FUNC_BODY | class _LazyType(object):
def __init__(self, path):
self.path = path
def evaluate(self, base_cls):
FILL_FUNC_BODY | module, type_name = _evaluate_path(self.path, base_cls)
return _import(module, type_name)
| module, type_name = _evaluate_path(self.path, base_cls)
return _import(module, type_name)
| 8 | 49 | 40 | 89 | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... | import datetime
import re
from weakref import WeakKeyDictionary
import six
from dateutil.parser import parse
from .errors import ValidationError
from .collections import ModelCollection
# unique marker for "no default value specified". None is not good enough since
# it is a completely valid default value.
NotSet =... |
32,757 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/models.py | 71,73 | 28,153 | iterate_over_fields | Base | 74,79 | 73,79 | class Base(six.with_metaclass(JsonmodelMeta, object)):
"""Base class for all models."""
def __init__(self, **kwargs):
self._cache_key = _CacheKey()
self.populate(**kwargs)
def populate(self, **values):
"""Populate values to fields. Skip non-existing."""
values = values.cop... | class Base(six.with_metaclass(JsonmodelMeta, object)):
"""Base class for all models."""
def __init__(self, **kwargs):
self._cache_key = _CacheKey()
self.populate(**kwargs)
def populate(self, **values):
"""Populate values to fields. Skip non-existing."""
values = values.cop... | for attr in dir(cls):
clsattr = getattr(cls, attr)
if isinstance(clsattr, BaseField):
yield attr, clsattr
| """Iterate through fields as `(attribute_name, field_instance)`."""
for attr in dir(cls):
clsattr = getattr(cls, attr)
if isinstance(clsattr, BaseField):
yield attr, clsattr
| 14 | 1,021 | 48 | 1,069 | import six
from . import parsers, errors
from .fields import BaseField
from .errors import ValidationError
class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def... | import six
from . import parsers, errors
from .fields import BaseField
from .errors import ValidationError
class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def... |
32,758 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/models.py | 14,16 | 8,28 | validate_fields | JsonmodelMeta | 16,28 | 16,28 | class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def validate_fields(attributes):
FILL_FUNC_BODY | class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def validate_fields(attributes):
FILL_FUNC_BODY | fields = {
key: value for key, value in attributes.items()
if isinstance(value, BaseField)
}
taken_names = set()
for name, field in fields.items():
structue_name = field.structue_name(name)
if structue_name in taken_names:
r... | fields = {
key: value for key, value in attributes.items()
if isinstance(value, BaseField)
}
taken_names = set()
for name, field in fields.items():
structue_name = field.structue_name(name)
if structue_name in taken_names:
r... | 35 | 80 | 123 | 203 | import six
from . import parsers, errors
from .fields import BaseField
from .errors import ValidationError
class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def... | import six
from . import parsers, errors
from .fields import BaseField
from .errors import ValidationError
class JsonmodelMeta(type):
def __new__(cls, name, bases, attributes):
cls.validate_fields(attributes)
return super(cls, cls).__new__(cls, name, bases, attributes)
@staticmethod
def... |
32,759 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/parsers.py | 48,49 | 1,107 | build_json_schema_object | 49,63 | 49,63 | """Parsers to change model structure into different ones."""
import inspect
from . import fields, builders, errors
def to_struct(model):
"""Cast instance of model to python structure.
:param model: Model to be casted.
:rtype: ``dict``
"""
model.validate()
resp = {}
for _, name, field i... | """Parsers to change model structure into different ones."""
import inspect
from . import fields, builders, errors
def to_struct(model):
"""Cast instance of model to python structure.
:param model: Model to be casted.
:rtype: ``dict``
"""
model.validate()
resp = {}
for _, name, field i... | builder = builders.ObjectBuilder(cls, parent_builder)
if builder.count_type(builder.type) > 1:
return builder
for _, name, field in cls.iterate_with_name():
if isinstance(field, fields.EmbeddedField):
builder.add_field(name, field, _parse_embedded(field, builder))
elif is... | builder = builders.ObjectBuilder(cls, parent_builder)
if builder.count_type(builder.type) > 1:
return builder
for _, name, field in cls.iterate_with_name():
if isinstance(field, fields.EmbeddedField):
builder.add_field(name, field, _parse_embedded(field, builder))
elif is... | 37 | 743 | 176 | 919 | """Parsers to change model structure into different ones."""
import inspect
from . import fields, builders, errors
def to_struct(model):
"""Cast instance of model to python structure.
:param model: Model to be casted.
:rtype: ``dict``
"""
model.validate()
resp = {}
for _, name, field i... | """Parsers to change model structure into different ones."""
import inspect
from . import fields, builders, errors
def to_struct(model):
"""Cast instance of model to python structure.
:param model: Model to be casted.
:rtype: ``dict``
"""
model.validate()
resp = {}
for _, name, field i... | |
32,760 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/utilities.py | 28,29 | 1,157 | _compare_dicts | 29,41 | 29,41 | from __future__ import absolute_import
import six
import re
from collections import namedtuple
SCALAR_TYPES = tuple(list(six.string_types) + [int, float, bool])
ECMA_TO_PYTHON_FLAGS = {
'i': re.I,
'm': re.M,
}
PYTHON_TO_ECMA_FLAGS = dict(
(value, key) for key, value in ECMA_TO_PYTHON_FLAGS.items()
)
Py... | from __future__ import absolute_import
import six
import re
from collections import namedtuple
SCALAR_TYPES = tuple(list(six.string_types) + [int, float, bool])
ECMA_TO_PYTHON_FLAGS = {
'i': re.I,
'm': re.M,
}
PYTHON_TO_ECMA_FLAGS = dict(
(value, key) for key, value in ECMA_TO_PYTHON_FLAGS.items()
)
Py... | if len(one) != len(two):
return False
for key, value in one.items():
if key not in one or key not in two:
return False
if not compare_schemas(one[key], two[key]):
return False
return True
| if len(one) != len(two):
return False
for key, value in one.items():
if key not in one or key not in two:
return False
if not compare_schemas(one[key], two[key]):
return False
return True
| 31 | 1,242 | 86 | 1,328 | from __future__ import absolute_import
import six
import re
from collections import namedtuple
SCALAR_TYPES = tuple(list(six.string_types) + [int, float, bool])
ECMA_TO_PYTHON_FLAGS = {
'i': re.I,
'm': re.M,
}
PYTHON_TO_ECMA_FLAGS = dict(
(value, key) for key, value in ECMA_TO_PYTHON_FLAGS.items()
)
Py... | from __future__ import absolute_import
import six
import re
from collections import namedtuple
SCALAR_TYPES = tuple(list(six.string_types) + [int, float, bool])
ECMA_TO_PYTHON_FLAGS = {
'i': re.I,
'm': re.M,
}
PYTHON_TO_ECMA_FLAGS = dict(
(value, key) for key, value in ECMA_TO_PYTHON_FLAGS.items()
)
Py... | |
32,761 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/validators.py | 196,197 | 184,203 | validate | Enum | 197,201 | 197,201 | class Enum(object):
"""Validator for enums."""
def __init__(self, *choices):
"""Init.
:param [] choices: Valid choices for the field.
"""
self.choices = list(choices)
def validate(self, value):
FILL_FUNC_BODY def modify_schema(self, field_schema):
field_schema... | class Enum(object):
"""Validator for enums."""
def __init__(self, *choices):
"""Init.
:param [] choices: Valid choices for the field.
"""
self.choices = list(choices)
def validate(self, value):
FILL_FUNC_BODY def modify_schema(self, field_schema):
field_schema... | if value not in self.choices:
tpl = "Value '{val}' is not a valid choice."
raise ValidationError(tpl.format(val=value))
| if value not in self.choices:
tpl = "Value '{val}' is not a valid choice."
raise ValidationError(tpl.format(val=value))
| 16 | 110 | 49 | 159 | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... |
32,762 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/validators.py | 157,158 | 136,184 | validate | Length | 159,175 | 158,175 | class Length(object):
"""Validator for length."""
def __init__(self, minimum_value=None, maximum_value=None):
"""Init.
Note that if no `minimum_value` neither `maximum_value` will be
specified, `ValueError` will be raised.
:param int minimum_value: Minimum value (optional).
... | class Length(object):
"""Validator for length."""
def __init__(self, minimum_value=None, maximum_value=None):
"""Init.
Note that if no `minimum_value` neither `maximum_value` will be
specified, `ValueError` will be raised.
:param int minimum_value: Minimum value (optional).
... | len_ = len(value)
if self.minimum_value is not None and len_ < self.minimum_value:
tpl = "Value '{val}' length is lower than allowed minimum '{min}'."
raise ValidationError(tpl.format(
val=value, min=self.minimum_value
))
if self.maximum_valu... | """Validate value."""
len_ = len(value)
if self.minimum_value is not None and len_ < self.minimum_value:
tpl = "Value '{val}' length is lower than allowed minimum '{min}'."
raise ValidationError(tpl.format(
val=value, min=self.minimum_value
))... | 52 | 276 | 177 | 453 | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... |
32,763 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/validators.py | 60,61 | 45,80 | validate | Max | 62,73 | 61,73 | class Max(object):
"""Validator for maximum value."""
def __init__(self, maximum_value, exclusive=False):
"""Init.
:param maximum_value: Maximum value for validator.
:param bool exclusive: If `True`, then validated value must be strongly
bigger than given threshold.
... | class Max(object):
"""Validator for maximum value."""
def __init__(self, maximum_value, exclusive=False):
"""Init.
:param maximum_value: Maximum value for validator.
:param bool exclusive: If `True`, then validated value must be strongly
bigger than given threshold.
... | if self.exclusive:
if value >= self.maximum_value:
tpl = "'{val}' is bigger or equal than maximum ('{max}')."
raise ValidationError(
tpl.format(val=value, max=self.maximum_value))
else:
if value > self.maximum_value:
... | """Validate value."""
if self.exclusive:
if value >= self.maximum_value:
tpl = "'{val}' is bigger or equal than maximum ('{max}')."
raise ValidationError(
tpl.format(val=value, max=self.maximum_value))
else:
if value > s... | 35 | 190 | 136 | 326 | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... |
32,764 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/validators.py | 25,26 | 10,45 | validate | Min | 27,38 | 26,38 | class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for validator.
:param bool exclusive: If `True`, then validated value must be strongly
lower than given threshold.
... | class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for validator.
:param bool exclusive: If `True`, then validated value must be strongly
lower than given threshold.
... | if self.exclusive:
if value <= self.minimum_value:
tpl = "'{value}' is lower or equal than minimum ('{min}')."
raise ValidationError(
tpl.format(value=value, min=self.minimum_value))
else:
if value < self.minimum_value:
... | """Validate value."""
if self.exclusive:
if value <= self.minimum_value:
tpl = "'{value}' is lower or equal than minimum ('{min}')."
raise ValidationError(
tpl.format(value=value, min=self.minimum_value))
else:
if value ... | 35 | 187 | 132 | 319 | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... |
32,765 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/jsonmodels/validators.py | 112,113 | 80,136 | validate | Regex | 114,127 | 113,127 | class Regex(object):
"""Validator for regular expressions."""
FLAGS = {
'ignorecase': re.I,
'multiline': re.M,
}
def __init__(self, pattern, **flags):
"""Init.
Note, that if given pattern is ECMA regex, given flags will be
**completely ignored** and taken from... | class Regex(object):
"""Validator for regular expressions."""
FLAGS = {
'ignorecase': re.I,
'multiline': re.M,
}
def __init__(self, pattern, **flags):
"""Init.
Note, that if given pattern is ECMA regex, given flags will be
**completely ignored** and taken from... | flags = self._calculate_flags()
try:
result = re.search(self.pattern, value, flags)
except TypeError as te:
raise ValidationError(*te.args)
if not result:
raise ValidationError(
'Value "{value}" did not match pattern "{pattern}".'.for... | """Validate value."""
flags = self._calculate_flags()
try:
result = re.search(self.pattern, value, flags)
except TypeError as te:
raise ValidationError(*te.args)
if not result:
raise ValidationError(
'Value "{value}" did not m... | 30 | 391 | 114 | 505 | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... | """Predefined validators."""
import re
from six.moves import reduce
from .errors import ValidationError
from . import utilities
class Min(object):
"""Validator for minimum value."""
def __init__(self, minimum_value, exclusive=False):
"""Init.
:param minimum_value: Minimum value for valida... |
32,766 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/request.py | 62,64 | 44,86 | requests | BatchRequest | 64,73 | 64,73 | @six.add_metaclass(abc.ABCMeta)
class BatchRequest(Request):
_batched_request_cls = abc.abstractproperty()
_schema_errors = (SchemaError, ValidationError, FormatError, Unresolvable)
def __init__(self, requests, validate_requests=False, allow_raw_requests=True, **kwargs):
super(BatchRequest, self)... | @six.add_metaclass(abc.ABCMeta)
class BatchRequest(Request):
_batched_request_cls = abc.abstractproperty()
_schema_errors = (SchemaError, ValidationError, FormatError, Unresolvable)
def __init__(self, requests, validate_requests=False, allow_raw_requests=True, **kwargs):
super(BatchRequest, self)... | assert issubclass(self._batched_request_cls, Request)
assert isinstance(value, (list, tuple))
if not self._allow_raw_requests:
if any(isinstance(x, dict) for x in value):
value = [self._batched_request_cls(**x) if isinstance(x, dict) else x for x in value]
... | assert issubclass(self._batched_request_cls, Request)
assert isinstance(value, (list, tuple))
if not self._allow_raw_requests:
if any(isinstance(x, dict) for x in value):
value = [self._batched_request_cls(**x) if isinstance(x, dict) else x for x in value]
... | 39 | 348 | 138 | 486 | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... |
32,767 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/request.py | 89,90 | 86,106 | _get_item | CompoundRequest | 90,96 | 90,96 | class CompoundRequest(Request):
_item_prop_name = 'item'
def _get_item(self):
FILL_FUNC_BODY def to_dict(self):
dict_ = self._get_item().to_dict()
dict_properties = super(Request, self).to_dict()
if self._item_prop_name in dict_properties:
del dict_properties[self._item_p... | class CompoundRequest(Request):
_item_prop_name = 'item'
def _get_item(self):
FILL_FUNC_BODY def to_dict(self):
dict_ = self._get_item().to_dict()
dict_properties = super(Request, self).to_dict()
if self._item_prop_name in dict_properties:
del dict_properties[self._item_p... | item = getattr(self, self._item_prop_name, None)
if item is None:
raise ValueError('Item property is empty or missing')
assert isinstance(item, DataModel)
return item
| item = getattr(self, self._item_prop_name, None)
if item is None:
raise ValueError('Item property is empty or missing')
assert isinstance(item, DataModel)
return item
| 21 | 149 | 61 | 210 | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... |
32,768 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/request.py | 37,38 | 24,44 | to_dict | Request | 38,44 | 38,44 | class Request(ApiModel):
def_method = ENV_API_DEFAULT_REQ_METHOD.get(default="get")
_method = ENV_API_DEFAULT_REQ_METHOD.get(default="get")
def __init__(self, **kwargs):
allow_extra_fields = kwargs.pop("_allow_extra_fields_", False)
if not allow_extra_fields and kwargs:
raise Va... | class Request(ApiModel):
def_method = ENV_API_DEFAULT_REQ_METHOD.get(default="get")
_method = ENV_API_DEFAULT_REQ_METHOD.get(default="get")
def __init__(self, **kwargs):
allow_extra_fields = kwargs.pop("_allow_extra_fields_", False)
if not allow_extra_fields and kwargs:
raise Va... | res = super(Request, self).to_dict(*args, **kwargs)
if self._extra_fields:
res.update(self._extra_fields)
return res
| res = super(Request, self).to_dict(*args, **kwargs)
if self._extra_fields:
res.update(self._extra_fields)
return res
| 10 | 192 | 52 | 244 | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... | import abc
import six
from jsonschema.exceptions import FormatError, SchemaError, ValidationError
try:
# Since `referencing`` only supports Python >= 3.8, this try-except blocks maintain support
# for earlier python versions.
from referencing.exceptions import Unresolvable
except ImportError:
from jso... |
32,769 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_api/session/token_manager.py | 57,58 | 10,113 | _calc_token_valid_period_sec | TokenManager | 58,70 | 58,70 | @six.add_metaclass(ABCMeta)
class TokenManager(object):
@property
def token_expiration_threshold_sec(self):
return self.__token_expiration_threshold_sec
@token_expiration_threshold_sec.setter
def token_expiration_threshold_sec(self, value):
self.__token_expiration_threshold_sec = value... | @six.add_metaclass(ABCMeta)
class TokenManager(object):
@property
def token_expiration_threshold_sec(self):
return self.__token_expiration_threshold_sec
@token_expiration_threshold_sec.setter
def token_expiration_threshold_sec(self, value):
self.__token_expiration_threshold_sec = value... | if token:
try:
exp = exp or self._get_token_exp(token)
if at_least_sec:
at_least_sec = max(at_least_sec, self.token_expiration_threshold_sec)
else:
at_least_sec = self.token_expiration_threshold_sec
... | if token:
try:
exp = exp or self._get_token_exp(token)
if at_least_sec:
at_least_sec = max(at_least_sec, self.token_expiration_threshold_sec)
else:
at_least_sec = self.token_expiration_threshold_sec
... | 30 | 892 | 130 | 1,022 | import sys
from abc import ABCMeta, abstractmethod
from time import time
import jwt
from jwt.algorithms import get_default_algorithms
import six
@six.add_metaclass(ABCMeta)
class TokenManager(object):
@property
def token_expiration_threshold_sec(self):
return self.__token_expiration_threshold_sec
... | import sys
from abc import ABCMeta, abstractmethod
from time import time
import jwt
from jwt.algorithms import get_default_algorithms
import six
@six.add_metaclass(ABCMeta)
class TokenManager(object):
@property
def token_expiration_threshold_sec(self):
return self.__token_expiration_threshold_sec
... |
32,771 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 391,392 | 385,402 | update | AzureContainerConfig | 392,398 | 392,398 | @attrs
class AzureContainerConfig(object):
account_name = attrib(type=str)
account_key = attrib(type=str)
container_name = attrib(type=str, default=None)
def update(self, **kwargs):
FILL_FUNC_BODY def is_valid(self):
return self.account_name and self.container_name
| @attrs
class AzureContainerConfig(object):
account_name = attrib(type=str)
account_key = attrib(type=str)
container_name = attrib(type=str, default=None)
def update(self, **kwargs):
FILL_FUNC_BODY def is_valid(self):
return self.account_name and self.container_name
| for item in kwargs:
if not hasattr(self, item):
warnings.warn("Unexpected argument {} for update. Ignored".format(item))
else:
setattr(self, item, kwargs[item])
| for item in kwargs:
if not hasattr(self, item):
warnings.warn("Unexpected argument {} for update. Ignored".format(item))
else:
setattr(self, item, kwargs[item])
| 18 | 101 | 67 | 168 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,772 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 458,459 | 402,482 | get_config | AzureContainerConfigurations | 459,471 | 459,471 | class AzureContainerConfigurations(object):
def __init__(self, container_configs=None, default_account=None, default_key=None):
super(AzureContainerConfigurations, self).__init__()
self._container_configs = container_configs or []
self._default_account = default_account
self._default... | class AzureContainerConfigurations(object):
def __init__(self, container_configs=None, default_account=None, default_key=None):
super(AzureContainerConfigurations, self).__init__()
self._container_configs = container_configs or []
self._default_account = default_account
self._default... | return next(
(
config
for config in self._container_configs
if config.account_name == account_name and (
not config.container_name
or config.container_name == container
)
),
... | return next(
(
config
for config in self._container_configs
if config.account_name == account_name and (
not config.container_name
or config.container_name == container
)
),
... | 24 | 689 | 79 | 768 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,773 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 97,98 | 91,111 | _update_prefixes | BaseBucketConfigurations | 98,106 | 98,106 | @six.add_metaclass(abc.ABCMeta)
class BaseBucketConfigurations(object):
def __init__(self, buckets=None, *_, **__):
self._buckets = buckets or []
self._prefixes = None
def _update_prefixes(self, refresh=True):
FILL_FUNC_BODY @abc.abstractmethod
def _get_prefix_from_bucket_config(self, co... | @six.add_metaclass(abc.ABCMeta)
class BaseBucketConfigurations(object):
def __init__(self, buckets=None, *_, **__):
self._buckets = buckets or []
self._prefixes = None
def _update_prefixes(self, refresh=True):
FILL_FUNC_BODY @abc.abstractmethod
def _get_prefix_from_bucket_config(self, co... | if self._prefixes and not refresh:
return
prefixes = (
(config, self._get_prefix_from_bucket_config(config))
for config in self._buckets
)
self._prefixes = sorted(prefixes, key=itemgetter(1), reverse=True)
| if self._prefixes and not refresh:
return
prefixes = (
(config, self._get_prefix_from_bucket_config(config))
for config in self._buckets
)
self._prefixes = sorted(prefixes, key=itemgetter(1), reverse=True)
| 21 | 123 | 86 | 209 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,774 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 284,285 | 275,295 | update | GSBucketConfig | 285,291 | 285,291 | @attrs
class GSBucketConfig(object):
bucket = attrib(type=str)
subdir = attrib(type=str, converter=_url_stripper, default="")
project = attrib(type=str, default=None)
credentials_json = attrib(type=str, default=None)
pool_connections = attrib(type=int, default=None)
pool_maxsize = attrib(type=in... | @attrs
class GSBucketConfig(object):
bucket = attrib(type=str)
subdir = attrib(type=str, converter=_url_stripper, default="")
project = attrib(type=str, default=None)
credentials_json = attrib(type=str, default=None)
pool_connections = attrib(type=int, default=None)
pool_maxsize = attrib(type=in... | for item in kwargs:
if not hasattr(self, item):
warnings.warn("Unexpected argument {} for update. Ignored".format(item))
else:
setattr(self, item, kwargs[item])
| for item in kwargs:
if not hasattr(self, item):
warnings.warn("Unexpected argument {} for update. Ignored".format(item))
else:
setattr(self, item, kwargs[item])
| 18 | 155 | 67 | 222 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,775 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 348,349 | 295,385 | get_config_by_uri | GSBucketConfigurations | 356,380 | 349,380 | class GSBucketConfigurations(BaseBucketConfigurations):
def __init__(
self,
buckets=None,
default_project=None,
default_credentials=None,
default_pool_connections=None,
default_pool_maxsize=None
):
super(GSBucketConfigurations, self... | class GSBucketConfigurations(BaseBucketConfigurations):
def __init__(
self,
buckets=None,
default_project=None,
default_credentials=None,
default_pool_connections=None,
default_pool_maxsize=None
):
super(GSBucketConfigurations, self... |
res = (
config
for config, prefix in self._prefixes
if prefix is not None and uri.lower().startswith(prefix)
)
try:
return next(res)
except StopIteration:
if not create_if_not_found:
return None
parsed... | """
Get the credentials for a Google Storage bucket from the config
:param uri: URI of bucket, directory or file
:param create_if_not_found: If True and the config is not found in the current configurations, create a new one.
Else, don't create a new one and return None
... | 39 | 794 | 202 | 996 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,776 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 64,65 | 22,88 | get_bucket_host | S3BucketConfig | 65,67 | 65,67 | @attrs
class S3BucketConfig(object):
bucket = attrib(type=str, converter=_url_stripper, default="")
subdir = attrib(type=str, converter=_url_stripper, default="")
host = attrib(type=str, converter=_none_to_empty_string, default="")
key = attrib(type=str, converter=_none_to_empty_string, default="")
... | @attrs
class S3BucketConfig(object):
bucket = attrib(type=str, converter=_url_stripper, default="")
subdir = attrib(type=str, converter=_url_stripper, default="")
host = attrib(type=str, converter=_none_to_empty_string, default="")
key = attrib(type=str, converter=_none_to_empty_string, default="")
... | return self.bucket, self.host
| return self.bucket, self.host
| 3 | 734 | 14 | 748 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,777 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/bucket_config.py | 222,223 | 111,272 | get_config_by_uri | S3BucketConfigurations | 228,272 | 223,272 | class S3BucketConfigurations(BaseBucketConfigurations):
def __init__(
self,
buckets=None,
default_key="",
default_secret="",
default_region="",
default_use_credentials_chain=False,
default_token="",
default_extra_args=None,
default_verify=None,... | class S3BucketConfigurations(BaseBucketConfigurations):
def __init__(
self,
buckets=None,
default_key="",
default_secret="",
default_region="",
default_use_credentials_chain=False,
default_token="",
default_extra_args=None,
default_verify=None,... | def find_match(uri):
self._update_prefixes(refresh=False)
uri = uri.lower()
res = (
config
for config, prefix in self._prefixes
if prefix is not None and uri.startswith(prefix)
)
try:
ret... | """
Get the credentials for an AWS S3 bucket from the config
:param uri: URI of bucket, directory or file
:return: S3BucketConfig: bucket config
"""
def find_match(uri):
self._update_prefixes(refresh=False)
uri = uri.lower()
res = (
... | 76 | 1,291 | 353 | 1,644 | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... | import abc
import warnings
from copy import copy
from operator import itemgetter
from os import getenv
import furl
import six
from attr import attrib, attrs
def _none_to_empty_string(maybe_string):
return maybe_string if maybe_string is not None else ""
def _url_stripper(bucket):
bucket = _none_to_empty_st... |
32,779 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/config.py | 59,60 | 51,68 | _get | ConfigEntry | 60,63 | 60,63 | class ConfigEntry(Entry):
logger = None
def __init__(self, config, *keys, **kwargs):
# type: (Config, Text, Any) -> None
super(ConfigEntry, self).__init__(*keys, **kwargs)
self.config = config
def _get(self, key):
FILL_FUNC_BODY def error(self, message):
# type: (Text) -... | class ConfigEntry(Entry):
logger = None
def __init__(self, config, *keys, **kwargs):
# type: (Config, Text, Any) -> None
super(ConfigEntry, self).__init__(*keys, **kwargs)
self.config = config
def _get(self, key):
FILL_FUNC_BODY def error(self, message):
# type: (Text) -... | # type: (Text) -> Any
return self.config.get(key, NotSet)
| # type: (Text) -> Any
return self.config.get(key, NotSet)
| 8 | 124 | 29 | 153 | from __future__ import print_function
import functools
import json
import logging
import os
import sys
import warnings
from fnmatch import fnmatch
from os.path import expanduser
from typing import Any
import six
from pathlib2 import Path
from pyparsing import (
ParseFatalException,
ParseException,
Recursi... | from __future__ import print_function
import functools
import json
import logging
import os
import sys
import warnings
from fnmatch import fnmatch
from os.path import expanduser
from typing import Any
import six
from pathlib2 import Path
from pyparsing import (
ParseFatalException,
ParseException,
Recursi... |
32,780 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/converters.py | 16,17 | 1,77 | strtobool | 23,32 | 17,32 | import base64
from typing import Union, Optional, Any, TypeVar, Callable, Tuple
import six
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
ConverterType = TypeVar("ConverterType", bound=Callable[[Any], Any])
def strtobool(val):
FILL_FUNC_BODYdef base64_to_text(val... | import base64
from typing import Union, Optional, Any, TypeVar, Callable, Tuple
import six
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
ConverterType = TypeVar("ConverterType", bound=Callable[[Any], Any])
def strtobool(val):
"""Convert a string representati... | val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
| """Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on... | 33 | 556 | 98 | 654 | import base64
from typing import Union, Optional, Any, TypeVar, Callable, Tuple
import six
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
ConverterType = TypeVar("ConverterType", bound=Callable[[Any], Any])
def strtobool(val):
FILL_FUNC_BODYdef base64_to_text(val... | import base64
from typing import Union, Optional, Any, TypeVar, Callable, Tuple
import six
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
ConverterType = TypeVar("ConverterType", bound=Callable[[Any], Any])
def strtobool(val):
"""Convert a string representati... | |
32,781 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/defs.py | 72,73 | 1,76 | get_config_file | 73,76 | 73,76 | from os.path import expanduser, expandvars, exists
from pathlib2 import Path
from .environment import EnvEntry
ENV_VAR = 'CLEARML_ENV'
""" Name of system environment variable that can be used to specify the config environment name """
DEFAULT_CONFIG_FOLDER = 'config'
""" Default config folder to search for when lo... | from os.path import expanduser, expandvars, exists
from pathlib2 import Path
from .environment import EnvEntry
ENV_VAR = 'CLEARML_ENV'
""" Name of system environment variable that can be used to specify the config environment name """
DEFAULT_CONFIG_FOLDER = 'config'
""" Default config folder to search for when lo... | f = LOCAL_CONFIG_FILE_OVERRIDE_VAR.get()
f = f if f else LOCAL_CONFIG_FILES[-1]
return expanduser(expandvars(f)) if f else None
| f = LOCAL_CONFIG_FILE_OVERRIDE_VAR.get()
f = f if f else LOCAL_CONFIG_FILES[-1]
return expanduser(expandvars(f)) if f else None
| 16 | 595 | 56 | 651 | from os.path import expanduser, expandvars, exists
from pathlib2 import Path
from .environment import EnvEntry
ENV_VAR = 'CLEARML_ENV'
""" Name of system environment variable that can be used to specify the config environment name """
DEFAULT_CONFIG_FOLDER = 'config'
""" Default config folder to search for when lo... | from os.path import expanduser, expandvars, exists
from pathlib2 import Path
from .environment import EnvEntry
ENV_VAR = 'CLEARML_ENV'
""" Name of system environment variable that can be used to specify the config environment name """
DEFAULT_CONFIG_FOLDER = 'config'
""" Default config folder to search for when lo... | |
32,782 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/entry.py | 67,68 | 20,110 | get_pair | Entry | 68,83 | 68,83 | @six.add_metaclass(abc.ABCMeta)
class Entry(object):
"""
Configuration entry definition
"""
@classmethod
def default_conversions(cls):
# type: () -> Dict[Any, Converter]
return {
bool: any_to_bool,
six.text_type: lambda s: six.text_type(s).strip(),
}
... | @six.add_metaclass(abc.ABCMeta)
class Entry(object):
"""
Configuration entry definition
"""
@classmethod
def default_conversions(cls):
# type: () -> Dict[Any, Converter]
return {
bool: any_to_bool,
six.text_type: lambda s: six.text_type(s).strip(),
}
... | # type: (Any, Converter) -> Optional[Tuple[Text, Any]]
for key in self.keys:
value = self._get(key)
if value is NotSet:
continue
# noinspection PyBroadException
try:
value = self.convert(value, converter)
except ... | # type: (Any, Converter) -> Optional[Tuple[Text, Any]]
for key in self.keys:
value = self._get(key)
if value is NotSet:
continue
# noinspection PyBroadException
try:
value = self.convert(value, converter)
except ... | 54 | 774 | 167 | 941 | import abc
from typing import Optional, Any, Tuple, Callable, Dict
import six
from .converters import any_to_bool
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
NotSet = object()
Converter = Callable[[Any], Any]
@six.add_metaclass(abc.ABCMeta)
class Entry(objec... | import abc
from typing import Optional, Any, Tuple, Callable, Dict
import six
from .converters import any_to_bool
try:
from typing import Text
except ImportError:
# windows conda-less hack
Text = Any
NotSet = object()
Converter = Callable[[Any], Any]
@six.add_metaclass(abc.ABCMeta)
class Entry(objec... |
32,783 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/environment.py | 22,23 | 7,38 | _get | EnvEntry | 23,26 | 23,26 | class EnvEntry(Entry):
@classmethod
def default_conversions(cls):
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
def __init__(self, key, *more_keys, **kwargs):
super(EnvEntry, self).__init__(key, *more_keys... | class EnvEntry(Entry):
@classmethod
def default_conversions(cls):
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
def __init__(self, key, *more_keys, **kwargs):
super(EnvEntry, self).__init__(key, *more_keys... | value = getenv(key, "").strip()
return value or NotSet
| value = getenv(key, "").strip()
return value or NotSet
| 8 | 285 | 24 | 309 | from os import getenv, environ
from .converters import text_to_bool
from .entry import Entry, NotSet
class EnvEntry(Entry):
@classmethod
def default_conversions(cls):
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
... | from os import getenv, environ
from .converters import text_to_bool
from .entry import Entry, NotSet
class EnvEntry(Entry):
@classmethod
def default_conversions(cls):
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
... |
32,784 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/log.py | 7,8 | 1,33 | logger | 8,16 | 8,16 | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
FILL_FUNC_BODYdef initialize(logging_config=None, extra=None):
if extra is not None:
from logging import Logger
class _Logger(Logger):
__extra = extra.copy()
def _log(self, l... | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
FILL_FUNC_BODYdef initialize(logging_config=None, extra=None):
if extra is not None:
from logging import Logger
class _Logger(Logger):
__extra = extra.copy()
def _log(self, l... | name = "clearml"
if path:
p = Path(path)
module = (p.parent if p.stem.startswith('_') else p).stem
name = "clearml.%s" % module
return logging.getLogger(name)
| name = "clearml"
if path:
p = Path(path)
module = (p.parent if p.stem.startswith('_') else p).stem
name = "clearml.%s" % module
return logging.getLogger(name)
| 22 | 221 | 79 | 300 | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
FILL_FUNC_BODYdef initialize(logging_config=None, extra=None):
if extra is not None:
from logging import Logger
class _Logger(Logger):
__extra = extra.copy()
def _log(self, l... | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
FILL_FUNC_BODYdef initialize(logging_config=None, extra=None):
if extra is not None:
from logging import Logger
class _Logger(Logger):
__extra = extra.copy()
def _log(self, l... | |
32,785 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/log.py | 23,24 | 20,28 | _log | _Logger | 24,28 | 24,28 | class _Logger(Logger):
__extra = extra.copy()
def _log(self, level, msg, args, exc_info=None, extra=None, **kwargs):
FILL_FUNC_BODY | class _Logger(Logger):
__extra = extra.copy()
def _log(self, level, msg, args, exc_info=None, extra=None, **kwargs):
FILL_FUNC_BODY | extra = extra or {}
extra.update(self.__extra)
super(_Logger, self)._log(level, msg, args, exc_info=exc_info, extra=extra, **kwargs)
| extra = extra or {}
extra.update(self.__extra)
super(_Logger, self)._log(level, msg, args, exc_info=exc_info, extra=extra, **kwargs)
| 13 | 55 | 54 | 109 | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
name = "clearml"
if path:
p = Path(path)
module = (p.parent if p.stem.startswith('_') else p).stem
name = "clearml.%s" % module
return logging.getLogger(name)
def initialize(logging_... | import logging.config
from copy import deepcopy
from pathlib2 import Path
def logger(path=None):
name = "clearml"
if path:
p = Path(path)
module = (p.parent if p.stem.startswith('_') else p).stem
name = "clearml.%s" % module
return logging.getLogger(name)
def initialize(logging_... |
32,786 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_config/utils.py | 39,40 | 1,113 | apply_files | 40,113 | 40,113 | import base64
import os
from os.path import expandvars, expanduser
from pathlib2 import Path
from typing import List, TYPE_CHECKING
from ..utilities.pyhocon import HOCONConverter, ConfigTree
if TYPE_CHECKING:
from .config import Config
def get_items(cls):
""" get key/value items from an enum-like class (mem... | import base64
import os
from os.path import expandvars, expanduser
from pathlib2 import Path
from typing import List, TYPE_CHECKING
from ..utilities.pyhocon import HOCONConverter, ConfigTree
if TYPE_CHECKING:
from .config import Config
def get_items(cls):
""" get key/value items from an enum-like class (mem... | # type: (Config) -> None
files = config.get("files", None)
if not files:
return
if isinstance(files, (list, tuple)):
files = dict(files)
print("Creating files from configuration")
for key, data in files.items():
path = data.get("path")
fmt = data.get("format", "... | # type: (Config) -> None
files = config.get("files", None)
if not files:
return
if isinstance(files, (list, tuple)):
files = dict(files)
print("Creating files from configuration")
for key, data in files.items():
path = data.get("path")
fmt = data.get("format", "... | 223 | 327 | 783 | 1,110 | import base64
import os
from os.path import expandvars, expanduser
from pathlib2 import Path
from typing import List, TYPE_CHECKING
from ..utilities.pyhocon import HOCONConverter, ConfigTree
if TYPE_CHECKING:
from .config import Config
def get_items(cls):
""" get key/value items from an enum-like class (mem... | import base64
import os
from os.path import expandvars, expanduser
from pathlib2 import Path
from typing import List, TYPE_CHECKING
from ..utilities.pyhocon import HOCONConverter, ConfigTree
if TYPE_CHECKING:
from .config import Config
def get_items(cls):
""" get key/value items from an enum-like class (mem... | |
32,787 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/base.py | 175,176 | 145,194 | reload | IdObjectBase | 176,185 | 176,185 | @six.add_metaclass(abc.ABCMeta)
class IdObjectBase(InterfaceBase):
def __init__(self, id, session=None, log=None, **kwargs):
super(IdObjectBase, self).__init__(session, log, **kwargs)
self._data = None
self._id = None
self.id = self.normalize_id(id)
@property
def id(self):
... | @six.add_metaclass(abc.ABCMeta)
class IdObjectBase(InterfaceBase):
def __init__(self, id, session=None, log=None, **kwargs):
super(IdObjectBase, self).__init__(session, log, **kwargs)
self._data = None
self._id = None
self.id = self.normalize_id(id)
@property
def id(self):
... | if not self.id and not self._offline_mode:
raise ValueError('Failed reloading %s: missing id' % type(self).__name__)
# noinspection PyBroadException
try:
self._data = self._reload()
except Exception as ex:
self.log.error("Failed reloading {} {}".format... | if not self.id and not self._offline_mode:
raise ValueError('Failed reloading %s: missing id' % type(self).__name__)
# noinspection PyBroadException
try:
self._data = self._reload()
except Exception as ex:
self.log.error("Failed reloading {} {}".format... | 37 | 318 | 145 | 463 | import abc
import requests.exceptions
import six
import jsonschema
from ..backend_api import Session, CallResult
from ..backend_api.session.session import MaxRequestSizeError
from ..backend_api.session.response import ResponseMeta
from ..backend_api.session import BatchRequest
from ..backend_api.session.defs import E... | import abc
import requests.exceptions
import six
import jsonschema
from ..backend_api import Session, CallResult
from ..backend_api.session.session import MaxRequestSizeError
from ..backend_api.session.response import ResponseMeta
from ..backend_api.session import BatchRequest
from ..backend_api.session.defs import E... |
32,788 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/base.py | 52,54 | 23,145 | _send | InterfaceBase | 55,112 | 54,112 | class InterfaceBase(SessionInterface):
""" Base class for a backend manager class """
_default_session = None
_num_retry_warning_display = 1
_offline_mode = ENV_OFFLINE_MODE.get()
_JSON_EXCEPTION = (jsonschema.ValidationError, requests.exceptions.InvalidJSONError) \
if hasattr(requests.excep... | class InterfaceBase(SessionInterface):
""" Base class for a backend manager class """
_default_session = None
_num_retry_warning_display = 1
_offline_mode = ENV_OFFLINE_MODE.get()
_JSON_EXCEPTION = (jsonschema.ValidationError, requests.exceptions.InvalidJSONError) \
if hasattr(requests.excep... | if cls._offline_mode:
return None
num_retries = 0
while True:
error_msg = ''
try:
res = session.send(req, async_enable=async_enable)
if res.meta.result_code in (200, 202) or ignore_errors:
return res
... | """ Convenience send() method providing a standardized error reporting """
if cls._offline_mode:
return None
num_retries = 0
while True:
error_msg = ''
try:
res = session.send(req, async_enable=async_enable)
if res.meta... | 251 | 674 | 757 | 1,431 | import abc
import requests.exceptions
import six
import jsonschema
from ..backend_api import Session, CallResult
from ..backend_api.session.session import MaxRequestSizeError
from ..backend_api.session.response import ResponseMeta
from ..backend_api.session import BatchRequest
from ..backend_api.session.defs import E... | import abc
import requests.exceptions
import six
import jsonschema
from ..backend_api import Session, CallResult
from ..backend_api.session.session import MaxRequestSizeError
from ..backend_api.session.response import ResponseMeta
from ..backend_api.session import BatchRequest
from ..backend_api.session.defs import E... |
32,789 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 174,175 | 165,183 | get_api_event | ConsoleEvent | 175,183 | 175,183 | class ConsoleEvent(MetricsEventAdapter):
""" Console log event adapter """
def __init__(self, message, level, worker, **kwargs):
self._value = str(message)
self._level = getLevelName(level) if isinstance(level, int) else str(level)
self._worker = worker
super(ConsoleEvent, self)... | class ConsoleEvent(MetricsEventAdapter):
""" Console log event adapter """
def __init__(self, message, level, worker, **kwargs):
self._value = str(message)
self._level = getLevelName(level) if isinstance(level, int) else str(level)
self._worker = worker
super(ConsoleEvent, self)... | return events.TaskLogEvent(
task=self._task,
timestamp=self._timestamp,
level=self._level,
worker=self._worker,
msg=self._value)
| return events.TaskLogEvent(
task=self._task,
timestamp=self._timestamp,
level=self._level,
worker=self._worker,
msg=self._value)
| 7 | 126 | 59 | 185 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,790 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 64,65 | 37,68 | set_exception | FileEntry | 65,68 | 65,68 | @attrs(cmp=False, slots=True)
class FileEntry(object):
""" File entry used to report on file data that needs to be uploaded prior to sending the event """
event = attr.attrib()
name = attr.attrib()
""" File name """
stream = attr.attrib()
""" File-like object c... | @attrs(cmp=False, slots=True)
class FileEntry(object):
""" File entry used to report on file data that needs to be uploaded prior to sending the event """
event = attr.attrib()
name = attr.attrib()
""" File name """
stream = attr.attrib()
""" File-like object c... | self.exception = exp
self.event.upload_exception = exp
| self.exception = exp
self.event.upload_exception = exp
| 6 | 244 | 22 | 266 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,791 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 432,433 | 424,440 | get_api_event | ImageEvent | 433,440 | 433,440 | class ImageEvent(UploadEvent):
def __init__(self, metric, variant, image_data, local_image_path=None, iter=0, upload_uri=None,
file_history_size=None, delete_after_upload=False, **kwargs):
super(ImageEvent, self).__init__(metric, variant, image_data=image_data, local_image_path=local_image_... | class ImageEvent(UploadEvent):
def __init__(self, metric, variant, image_data, local_image_path=None, iter=0, upload_uri=None,
file_history_size=None, delete_after_upload=False, **kwargs):
super(ImageEvent, self).__init__(metric, variant, image_data=image_data, local_image_path=local_image_... | return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict()
)
| return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict()
)
| 6 | 166 | 48 | 214 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,792 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 217,218 | 209,224 | get_api_event | ImageEventNoUpload | 218,224 | 218,224 | class ImageEventNoUpload(MetricsEventAdapter):
def __init__(self, metric, variant, src, iter=0, **kwargs):
self._url = src
parts = urlparse(src)
self._key = urlunparse(('', '', parts.path, parts.params, parts.query, parts.fragment))
super(ImageEventNoUpload, self).__init__(metric, v... | class ImageEventNoUpload(MetricsEventAdapter):
def __init__(self, metric, variant, src, iter=0, **kwargs):
self._url = src
parts = urlparse(src)
self._key = urlunparse(('', '', parts.path, parts.params, parts.query, parts.fragment))
super(ImageEventNoUpload, self).__init__(metric, v... | return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict())
| return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict())
| 5 | 125 | 44 | 169 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,793 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 448,449 | 440,454 | get_api_event | MediaEvent | 449,454 | 449,454 | class MediaEvent(UploadEvent):
def __init__(self, metric, variant, stream, local_image_path=None, iter=0, upload_uri=None,
file_history_size=None, delete_after_upload=False, **kwargs):
super(MediaEvent, self).__init__(metric, variant, image_data=stream, local_image_path=local_image_path,
... | class MediaEvent(UploadEvent):
def __init__(self, metric, variant, stream, local_image_path=None, iter=0, upload_uri=None,
file_history_size=None, delete_after_upload=False, **kwargs):
super(MediaEvent, self).__init__(metric, variant, image_data=stream, local_image_path=local_image_path,
... | return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict()
)
| return events.MetricsImageEvent(
url=self._url,
key=self._key,
**self._get_base_dict()
)
| 6 | 162 | 44 | 206 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,794 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 113,114 | 22,152 | _get_base_dict | MetricsEventAdapter | 115,127 | 114,127 | @six.add_metaclass(abc.ABCMeta)
class MetricsEventAdapter(object):
"""
Adapter providing all the base attributes required by a metrics event and defining an interface used by the
metrics manager when batching and writing events.
"""
default_nan_value = 0.
default_inf_value = 0.
""" Default ... | @six.add_metaclass(abc.ABCMeta)
class MetricsEventAdapter(object):
"""
Adapter providing all the base attributes required by a metrics event and defining an interface used by the
metrics manager when batching and writing events.
"""
default_nan_value = 0.
default_inf_value = 0.
""" Default ... | res = dict(
task=self._task,
timestamp=self._timestamp,
metric=self._metric,
variant=self._variant
)
if self._iter is not None:
res.update(iter=self._iter)
if self._model_event is not None:
res.update(model_event=sel... | """ Get a dict with the base attributes """
res = dict(
task=self._task,
timestamp=self._timestamp,
metric=self._metric,
variant=self._variant
)
if self._iter is not None:
res.update(iter=self._iter)
if self._model_event... | 22 | 1,121 | 107 | 1,228 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,795 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 203,204 | 196,209 | get_api_event | PlotEvent | 204,209 | 204,209 | class PlotEvent(MetricsEventAdapter):
""" Plot event adapter """
def __init__(self, metric, variant, plot_str, iter=None, **kwargs):
self._plot_str = plot_str
super(PlotEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_event(self):
FILL_FUNC_BODY | class PlotEvent(MetricsEventAdapter):
""" Plot event adapter """
def __init__(self, metric, variant, plot_str, iter=None, **kwargs):
self._plot_str = plot_str
super(PlotEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_event(self):
FILL_FUNC_BODY | return events.MetricsPlotEvent(
plot_str=self._plot_str,
**self._get_base_dict())
| return events.MetricsPlotEvent(
plot_str=self._plot_str,
**self._get_base_dict())
| 4 | 103 | 40 | 143 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,796 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 159,160 | 152,165 | get_api_event | ScalarEvent | 160,165 | 160,165 | class ScalarEvent(MetricsEventAdapter):
""" Scalar event adapter """
def __init__(self, metric, variant, value, iter, **kwargs):
self._value = self._convert_np_nan_inf(value)
super(ScalarEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_event(self):
FIL... | class ScalarEvent(MetricsEventAdapter):
""" Scalar event adapter """
def __init__(self, metric, variant, value, iter, **kwargs):
self._value = self._convert_np_nan_inf(value)
super(ScalarEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_event(self):
FIL... | return events.MetricsScalarEvent(
value=self._value,
**self._get_base_dict())
| return events.MetricsScalarEvent(
value=self._value,
**self._get_base_dict())
| 4 | 106 | 36 | 142 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,798 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/metrics/events.py | 190,191 | 183,196 | get_api_event | VectorEvent | 191,196 | 191,196 | class VectorEvent(MetricsEventAdapter):
""" Vector event adapter """
def __init__(self, metric, variant, values, iter, **kwargs):
self._values = [self._convert_np_nan_inf(v) for v in values]
super(VectorEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_... | class VectorEvent(MetricsEventAdapter):
""" Vector event adapter """
def __init__(self, metric, variant, values, iter, **kwargs):
self._values = [self._convert_np_nan_inf(v) for v in values]
super(VectorEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs)
def get_api_... | return events.MetricsVectorEvent(
values=self._values,
**self._get_base_dict())
| return events.MetricsVectorEvent(
values=self._values,
**self._get_base_dict())
| 4 | 109 | 35 | 144 | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... | import abc
import hashlib
import time
from functools import reduce
from logging import getLevelName
import attr
import numpy as np
import pathlib2
import six
from PIL import Image
from six.moves.urllib.parse import urlparse, urlunparse
from ...backend_api.services import events
from ...config import deferred_config
f... |
32,801 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/model.py | 40,41 | 35,44 | update | DummyModel | 41,44 | 41,44 | class DummyModel(models.Model, _StorageUriMixin):
def __init__(self, upload_storage_uri=None, *_, **__):
super(DummyModel, self).__init__(*_, **__)
self.upload_storage_uri = upload_storage_uri
def update(self, **a_kwargs):
FILL_FUNC_BODY | class DummyModel(models.Model, _StorageUriMixin):
def __init__(self, upload_storage_uri=None, *_, **__):
super(DummyModel, self).__init__(*_, **__)
self.upload_storage_uri = upload_storage_uri
def update(self, **a_kwargs):
FILL_FUNC_BODY | for k, v in a_kwargs.items():
setattr(self, k, v)
| for k, v in a_kwargs.items():
setattr(self, k, v)
| 8 | 93 | 28 | 121 | from collections import namedtuple
from functools import partial
import six
from pathlib2 import Path
from .base import IdObjectBase
from .util import make_message
from ..backend_api import Session
from ..backend_api.services import models, tasks
from ..storage import StorageManager
from ..storage.helper import Stora... | from collections import namedtuple
from functools import partial
import six
from pathlib2 import Path
from .base import IdObjectBase
from .util import make_message
from ..backend_api import Session
from ..backend_api.services import models, tasks
from ..storage import StorageManager
from ..storage.helper import Stora... |
32,803 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/model.py | 29,31 | 23,34 | upload_storage_uri | _StorageUriMixin | 31,34 | 31,34 | class _StorageUriMixin(object):
@property
def upload_storage_uri(self):
"""A URI into which models are uploaded"""
return self._upload_storage_uri
@upload_storage_uri.setter
def upload_storage_uri(self, value):
FILL_FUNC_BODY | class _StorageUriMixin(object):
@property
def upload_storage_uri(self):
"""A URI into which models are uploaded"""
return self._upload_storage_uri
@upload_storage_uri.setter
def upload_storage_uri(self, value):
FILL_FUNC_BODY | self._upload_storage_uri = value.rstrip("/") if value else None
| self._upload_storage_uri = value.rstrip("/") if value else None
| 7 | 81 | 25 | 106 | from collections import namedtuple
from functools import partial
import six
from pathlib2 import Path
from .base import IdObjectBase
from .util import make_message
from ..backend_api import Session
from ..backend_api.services import models, tasks
from ..storage import StorageManager
from ..storage.helper import Stora... | from collections import namedtuple
from functools import partial
import six
from pathlib2 import Path
from .base import IdObjectBase
from .util import make_message
from ..backend_api import Session
from ..backend_api.services import models, tasks
from ..storage import StorageManager
from ..storage.helper import Stora... |
32,804 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/session.py | 8,10 | 6,17 | result | SendError | 10,12 | 10,12 | class SendError(Exception):
""" A session send() error class """
@property
def result(self):
FILL_FUNC_BODY def __init__(self, result, *args, **kwargs):
super(SendError, self).__init__(*args, **kwargs)
self._result = result
| class SendError(Exception):
""" A session send() error class """
@property
def result(self):
FILL_FUNC_BODY def __init__(self, result, *args, **kwargs):
super(SendError, self).__init__(*args, **kwargs)
self._result = result
| return self._result
| return self._result
| 2 | 81 | 9 | 90 | from abc import ABCMeta, abstractmethod
import six
class SendError(Exception):
""" A session send() error class """
@property
def result(self):
FILL_FUNC_BODY def __init__(self, result, *args, **kwargs):
super(SendError, self).__init__(*args, **kwargs)
self._result = result
@six.add_... | from abc import ABCMeta, abstractmethod
import six
class SendError(Exception):
""" A session send() error class """
@property
def result(self):
FILL_FUNC_BODY def __init__(self, result, *args, **kwargs):
super(SendError, self).__init__(*args, **kwargs)
self._result = result
@six.add_... |
32,805 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/setupuploadmixin.py | 108,111 | 9,147 | setup_gcp_upload | SetupUploadMixin | 111,133 | 111,133 | class SetupUploadMixin(object):
log = abstractproperty()
storage_uri = abstractproperty()
def setup_upload(
self,
bucket_name, # type: str
host=None, # type: Optional[str]
access_key=None, # type: Optional[str]
secret_key=None, # type: Optional[str]
multi... | class SetupUploadMixin(object):
log = abstractproperty()
storage_uri = abstractproperty()
def setup_upload(
self,
bucket_name, # type: str
host=None, # type: Optional[str]
access_key=None, # type: Optional[str]
secret_key=None, # type: Optional[str]
multi... | # type: (str, str, Optional[str], Optional[str], Optional[int], Optional[int]) -> None
"""
Setup GCP upload options.
:param bucket: Bucket to upload to
:param subdir: Subdir in bucket to upload to
:param project: Project the bucket belongs to
:param credentials_j... | # type: (str, str, Optional[str], Optional[str], Optional[int], Optional[int]) -> None
"""
Setup GCP upload options.
:param bucket: Bucket to upload to
:param subdir: Subdir in bucket to upload to
:param project: Project the bucket belongs to
:param credentials_j... | 87 | 1,471 | 291 | 1,762 | from abc import abstractproperty
from typing import Optional
import warnings
from ..backend_config.bucket_config import S3BucketConfig, AzureContainerConfig, GSBucketConfig
from ..storage.helper import StorageHelper
class SetupUploadMixin(object):
log = abstractproperty()
storage_uri = abstractproperty()
... | from abc import abstractproperty
from typing import Optional
import warnings
from ..backend_config.bucket_config import S3BucketConfig, AzureContainerConfig, GSBucketConfig
from ..storage.helper import StorageHelper
class SetupUploadMixin(object):
log = abstractproperty()
storage_uri = abstractproperty()
... |
32,806 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/access.py | 54,55 | 10,100 | save_exec_model_design_file | AccessMixin | 56,70 | 55,70 | class AccessMixin(object):
""" A mixin providing task fields access functionality """
session = abstractproperty()
data = abstractproperty()
cache_dir = abstractproperty()
log = abstractproperty()
def _get_task_property(self, prop_path, raise_on_error=True, log_on_error=True, default=None):
... | class AccessMixin(object):
""" A mixin providing task fields access functionality """
session = abstractproperty()
data = abstractproperty()
cache_dir = abstractproperty()
log = abstractproperty()
def _get_task_property(self, prop_path, raise_on_error=True, log_on_error=True, default=None):
... | p = Path(self.cache_dir) / filename
if use_cache and p.is_file():
return str(p)
desc = self._get_task_property('execution.model_desc')
try:
design = six.next(six.itervalues(desc))
except StopIteration:
design = None
if not design:
... | """ Save execution model design to file """
p = Path(self.cache_dir) / filename
if use_cache and p.is_file():
return str(p)
desc = self._get_task_property('execution.model_desc')
try:
design = six.next(six.itervalues(desc))
except StopIteration:
... | 40 | 1,059 | 163 | 1,222 | import itertools
import operator
from abc import abstractproperty
import six
from pathlib2 import Path
class AccessMixin(object):
""" A mixin providing task fields access functionality """
session = abstractproperty()
data = abstractproperty()
cache_dir = abstractproperty()
log = abstractpropert... | import itertools
import operator
from abc import abstractproperty
import six
from pathlib2 import Path
class AccessMixin(object):
""" A mixin providing task fields access functionality """
session = abstractproperty()
data = abstractproperty()
cache_dir = abstractproperty()
log = abstractpropert... |
32,808 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/development/stop_signal.py | 28,29 | 10,68 | test | TaskStopSignal | 29,68 | 29,68 | class TaskStopSignal(object):
enabled = deferred_config('development.support_stopping', False, transform=bool)
_number_of_consecutive_reset_tests = 4
def __init__(self, task):
from ....backend_interface import Task
assert isinstance(task, Task)
self.task = task
self._task_r... | class TaskStopSignal(object):
enabled = deferred_config('development.support_stopping', False, transform=bool)
_number_of_consecutive_reset_tests = 4
def __init__(self, task):
from ....backend_interface import Task
assert isinstance(task, Task)
self.task = task
self._task_r... | # noinspection PyBroadException
try:
# we use internal status read, so we do not need to constantly pull the entire task object,
# it might be large, and we want to also avoid the edit lock on it.
# do not update the task object so that other threads can count on cons... | # noinspection PyBroadException
try:
# we use internal status read, so we do not need to constantly pull the entire task object,
# it might be large, and we want to also avoid the edit lock on it.
# do not update the task object so that other threads can count on cons... | 185 | 211 | 441 | 652 | from ....config import deferred_config
class TaskStopReason(object):
stopped = "stopped"
reset = "reset"
status_changed = "status_changed"
class TaskStopSignal(object):
enabled = deferred_config('development.support_stopping', False, transform=bool)
_number_of_consecutive_reset_tests = 4
d... | from ....config import deferred_config
class TaskStopReason(object):
stopped = "stopped"
reset = "reset"
status_changed = "status_changed"
class TaskStopSignal(object):
enabled = deferred_config('development.support_stopping', False, transform=bool)
_number_of_consecutive_reset_tests = 4
d... |
32,809 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/development/worker.py | 39,40 | 13,163 | ping | DevWorker | 40,47 | 40,47 | class DevWorker(object):
property_abort_callback_completed = "_abort_callback_completed"
property_abort_callback_timeout = "_abort_callback_timeout"
property_abort_poll_freq = "_abort_poll_freq"
prefix = attr.ib(type=str, default="MANUAL:")
report_stdout = deferred_config('development.worker.log_s... | class DevWorker(object):
property_abort_callback_completed = "_abort_callback_completed"
property_abort_callback_timeout = "_abort_callback_timeout"
property_abort_poll_freq = "_abort_poll_freq"
prefix = attr.ib(type=str, default="MANUAL:")
report_stdout = deferred_config('development.worker.log_s... | try:
if self._task:
self._task.send(tasks.PingRequest(self._task.id))
except Exception: # noqa
return False
return True
| try:
if self._task:
self._task.send(tasks.PingRequest(self._task.id))
except Exception: # noqa
return False
return True
| 12 | 1,597 | 57 | 1,654 | import attr
from threading import Thread
from time import time
from ....config import deferred_config
from ....backend_interface.task.development.stop_signal import TaskStopSignal
from ....backend_api.services import tasks
from ....utilities.lowlevel.threads import kill_thread
from ....utilities.process.mp import Saf... | import attr
from threading import Thread
from time import time
from ....config import deferred_config
from ....backend_interface.task.development.stop_signal import TaskStopSignal
from ....backend_api.services import tasks
from ....utilities.lowlevel.threads import kill_thread
from ....utilities.process.mp import Saf... |
32,811 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/models.py | 30,31 | 19,40 | get | ModelsList | 31,36 | 31,36 | class ModelsList(UserList):
def __init__(self, models_dict):
# type: (typing.OrderedDict["clearml.Model"]) -> None # noqa: F821
self._models = models_dict
super(ModelsList, self).__init__(models_dict.values())
def __getitem__(self, item):
if isinstance(item, str):
re... | class ModelsList(UserList):
def __init__(self, models_dict):
# type: (typing.OrderedDict["clearml.Model"]) -> None # noqa: F821
self._models = models_dict
super(ModelsList, self).__init__(models_dict.values())
def __getitem__(self, item):
if isinstance(item, str):
re... | try:
return self[key]
except KeyError:
return default
| try:
return self[key]
except KeyError:
return default
| 7 | 169 | 27 | 196 | import re
import typing
from collections import OrderedDict
try:
from collections import UserList
except ImportError:
UserList = list
try:
from collections import UserDict
except ImportError:
UserDict = dict
from clearml.backend_api import Session
from clearml.backend_api.services import models
cla... | import re
import typing
from collections import OrderedDict
try:
from collections import UserList
except ImportError:
UserList = list
try:
from collections import UserDict
except ImportError:
UserDict = dict
from clearml.backend_api import Session
from clearml.backend_api.services import models
cla... |
32,812 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/models.py | 43,45 | 40,132 | input | TaskModels | 45,48 | 45,48 | class TaskModels(UserDict):
_input_models_re = re.compile(pattern=r"((Using model id: )(\w+)?)", flags=re.IGNORECASE)
@property
def input(self):
FILL_FUNC_BODY @property
def output(self):
# type: () -> ModelsList
return self._output
def __init__(self, task):
# type: ("cl... | class TaskModels(UserDict):
_input_models_re = re.compile(pattern=r"((Using model id: )(\w+)?)", flags=re.IGNORECASE)
@property
def input(self):
FILL_FUNC_BODY @property
def output(self):
# type: () -> ModelsList
return self._output
def __init__(self, task):
# type: ("cl... | # type: () -> ModelsList
return self._input
| # type: () -> ModelsList
return self._input
| 7 | 1,002 | 21 | 1,023 | import re
import typing
from collections import OrderedDict
try:
from collections import UserList
except ImportError:
UserList = list
try:
from collections import UserDict
except ImportError:
UserDict = dict
from clearml.backend_api import Session
from clearml.backend_api.services import models
cla... | import re
import typing
from collections import OrderedDict
try:
from collections import UserList
except ImportError:
UserList = list
try:
from collections import UserDict
except ImportError:
UserDict = dict
from clearml.backend_api import Session
from clearml.backend_api.services import models
cla... |
32,815 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/populate.py | 833,834 | 831,843 | visit_FunctionDef | TypeHintRemover | 834,843 | 834,843 | class TypeHintRemover(ast.NodeTransformer):
def visit_FunctionDef(self, node):
FILL_FUNC_BODY | class TypeHintRemover(ast.NodeTransformer):
def visit_FunctionDef(self, node):
FILL_FUNC_BODY | # remove the return type definition
node.returns = None
# remove all argument annotations
if node.args.args:
for arg in node.args.args:
arg.annotation = None
return nod... | # remove the return type definition
node.returns = None
# remove all argument annotations
if node.args.args:
for arg in node.args.args:
arg.annotation = None
return nod... | 33 | 38 | 75 | 113 | import inspect
import json
import os
import re
import tempfile
from sys import platform
from functools import reduce
from logging import getLogger
from typing import Optional, Sequence, Union, Tuple, List, Callable, Dict, Any
from pathlib2 import Path
from six.moves.urllib.parse import urlparse
from .args import _Arg... | import inspect
import json
import os
import re
import tempfile
from sys import platform
from functools import reduce
from logging import getLogger
from typing import Optional, Sequence, Union, Tuple, List, Callable, Dict, Any
from pathlib2 import Path
from six.moves.urllib.parse import urlparse
from .args import _Arg... |
32,816 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/detectors.py | 107,108 | 42,199 | _get_info | Detector | 115,157 | 108,157 | @six.add_metaclass(abc.ABCMeta)
class Detector(object):
""" Base class for repository detection """
"""
Commands are represented using the result class, where each attribute contains
the command used to obtain the value of the same attribute in the actual result.
"""
_fallback = '_fallback'
... | @six.add_metaclass(abc.ABCMeta)
class Detector(object):
""" Base class for repository detection """
"""
Commands are represented using the result class, where each attribute contains
the command used to obtain the value of the same attribute in the actual result.
"""
_fallback = '_fallback'
... | path = str(path)
commands = self._get_commands()
if not include_diff:
commands.diff = None
# skip the local commands
if diff_from_remote and commands:
for name, command in attr.asdict(commands).items():
if name.endswith(self._remote) and c... | """
Get repository information.
:param path: Path to repository
:param include_diff: Whether to include the diff command's output (if available)
:param diff_from_remote: Whether to store the remote diff/commit based on the remote commit (not local commit)
:return: RepoInf... | 125 | 1,226 | 492 | 1,718 | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... |
32,817 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/detectors.py | 303,304 | 283,324 | _get_info | EnvDetector | 304,324 | 304,324 | class EnvDetector(Detector):
def __init__(self, type_name):
super(EnvDetector, self).__init__(type_name, "{} environment".format(type_name))
def _is_repo_type(self, script_path):
return VCS_REPO_TYPE.get().lower() == self.type_name and bool(
VCS_REPOSITORY_URL.get()
)
@... | class EnvDetector(Detector):
def __init__(self, type_name):
super(EnvDetector, self).__init__(type_name, "{} environment".format(type_name))
def _is_repo_type(self, script_path):
return VCS_REPO_TYPE.get().lower() == self.type_name and bool(
VCS_REPOSITORY_URL.get()
)
@... | repository_url = VCS_REPOSITORY_URL.get()
if not repository_url:
raise DetectionError("No VCS environment data")
status = VCS_STATUS.get() or ''
diff = VCS_DIFF.get() or ''
modified = bool(diff or (status and [s for s in status.split('\n') if s.strip().startswith('M ... | repository_url = VCS_REPOSITORY_URL.get()
if not repository_url:
raise DetectionError("No VCS environment data")
status = VCS_STATUS.get() or ''
diff = VCS_DIFF.get() or ''
modified = bool(diff or (status and [s for s in status.split('\n') if s.strip().startswith('M ... | 62 | 234 | 234 | 468 | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... |
32,818 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/detectors.py | 271,272 | 224,283 | _post_process_info | GitDetector | 272,283 | 272,283 | class GitDetector(Detector):
def __init__(self):
super(GitDetector, self).__init__("git")
def _get_commands(self):
return self.Commands(
url=["git", "ls-remote", "--get-url"],
branch=["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
commit... | class GitDetector(Detector):
def __init__(self):
super(GitDetector, self).__init__("git")
def _get_commands(self):
return self.Commands(
url=["git", "ls-remote", "--get-url"],
branch=["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
commit... | # Deprecated code: this was intended to make sure git repository names always
# ended with ".git", but this is not always the case (e.g. Azure Repos)
# if info.url and not info.url.endswith(".git"):
# info.url += ".git"
if (info.branch or "").startswith("origin/"):
... | # Deprecated code: this was intended to make sure git repository names always
# ended with ".git", but this is not always the case (e.g. Azure Repos)
# if info.url and not info.url.endswith(".git"):
# info.url += ".git"
if (info.branch or "").startswith("origin/"):
... | 46 | 645 | 124 | 769 | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... |
32,819 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/detectors.py | 203,204 | 199,224 | _get_commands | HgDetector | 204,214 | 204,214 | class HgDetector(Detector):
def __init__(self):
super(HgDetector, self).__init__("hg")
def _get_commands(self):
FILL_FUNC_BODY def _post_process_info(self, info):
if info.url:
info.url = info.url.split(" = ")[1]
if info.commit:
info.commit = info.commit.rstri... | class HgDetector(Detector):
def __init__(self):
super(HgDetector, self).__init__("hg")
def _get_commands(self):
FILL_FUNC_BODY def _post_process_info(self, info):
if info.url:
info.url = info.url.split(" = ")[1]
if info.commit:
info.commit = info.commit.rstri... | return self.Commands(
url=["hg", "paths", "--verbose"],
branch=["hg", "--debug", "id", "-b"],
commit=["hg", "--debug", "id", "-i"],
root=["hg", "root"],
status=["hg", "status"],
diff=["hg", "diff"],
modified=["hg", "status", "-m... | return self.Commands(
url=["hg", "paths", "--verbose"],
branch=["hg", "--debug", "id", "-b"],
commit=["hg", "--debug", "id", "-i"],
root=["hg", "root"],
status=["hg", "status"],
diff=["hg", "diff"],
modified=["hg", "status", "-m... | 23 | 126 | 121 | 247 | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... |
32,820 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/detectors.py | 38,39 | 26,42 | is_empty | Result | 39,42 | 39,42 | @attr.s
class Result(object):
"""" Repository information as queried by a detector """
url = attr.ib(default="")
branch = attr.ib(default="")
commit = attr.ib(default="")
root = attr.ib(default="")
status = attr.ib(default="")
diff = attr.ib(default="")
modified = attr.ib(default=False,... | @attr.s
class Result(object):
"""" Repository information as queried by a detector """
url = attr.ib(default="")
branch = attr.ib(default="")
commit = attr.ib(default="")
root = attr.ib(default="")
status = attr.ib(default="")
diff = attr.ib(default="")
modified = attr.ib(default=False,... | return not any(attr.asdict(self).values())
| return not any(attr.asdict(self).values())
| 3 | 139 | 20 | 159 | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... | import abc
import os
from subprocess import call, CalledProcessError
import attr
import six
from pathlib2 import Path
from ....config.defs import (
VCS_REPO_TYPE,
VCS_DIFF,
VCS_STATUS,
VCS_ROOT,
VCS_BRANCH,
VCS_COMMIT_ID,
VCS_REPOSITORY_URL,
)
from ....debugging import get_logger
from .uti... |
32,821 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/freeze.py | 8,9 | 1,74 | pip_freeze | 9,74 | 9,74 | import sys
import os
import json
from .util import get_command_output
def pip_freeze(combine_conda_with_pip=False):
FILL_FUNC_BODY | import sys
import os
import json
from .util import get_command_output
def pip_freeze(combine_conda_with_pip=False):
FILL_FUNC_BODY | req_lines = []
local_packages = []
conda_lines = []
conda_prefix = os.environ.get('CONDA_PREFIX')
if conda_prefix and not conda_prefix.endswith(os.path.sep):
conda_prefix += os.path.sep
if conda_prefix and sys.executable.startswith(conda_prefix):
pip_lines = get_command_output([... | req_lines = []
local_packages = []
conda_lines = []
conda_prefix = os.environ.get('CONDA_PREFIX')
if conda_prefix and not conda_prefix.endswith(os.path.sep):
conda_prefix += os.path.sep
if conda_prefix and sys.executable.startswith(conda_prefix):
pip_lines = get_command_output([... | 284 | 51 | 1,008 | 1,059 | import sys
import os
import json
from .util import get_command_output
def pip_freeze(combine_conda_with_pip=False):
FILL_FUNC_BODY | import sys
import os
import json
from .util import get_command_output
def pip_freeze(combine_conda_with_pip=False):
FILL_FUNC_BODY | |
32,822 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/task/repo/util.py | 18,19 | 1,36 | remove_user_pass_from_url | 19,36 | 19,36 | import os
from subprocess import check_output
from furl import furl
def get_command_output(command, path=None, strip=True):
"""
Run a command and return its output
:raises CalledProcessError: when command execution fails
:raises UnicodeDecodeError: when output decoding fails
"""
with open(os.... | import os
from subprocess import check_output
from furl import furl
def get_command_output(command, path=None, strip=True):
"""
Run a command and return its output
:raises CalledProcessError: when command execution fails
:raises UnicodeDecodeError: when output decoding fails
"""
with open(os.... | # remove user / password, if we have it embedded in the git repo
url = str(url)
# noinspection PyBroadException
try:
url = furl(url).remove(username=True, password=True).tostr()
except ValueError:
# check if for any reason we have two @
# (e.g. ssh://user@abc.com@domain.com/p... | # remove user / password, if we have it embedded in the git repo
url = str(url)
# noinspection PyBroadException
try:
url = furl(url).remove(username=True, password=True).tostr()
except ValueError:
# check if for any reason we have two @
# (e.g. ssh://user@abc.com@domain.com/p... | 64 | 162 | 215 | 377 | import os
from subprocess import check_output
from furl import furl
def get_command_output(command, path=None, strip=True):
"""
Run a command and return its output
:raises CalledProcessError: when command execution fails
:raises UnicodeDecodeError: when output decoding fails
"""
with open(os.... | import os
from subprocess import check_output
from furl import furl
def get_command_output(command, path=None, strip=True):
"""
Run a command and return its output
:raises CalledProcessError: when command execution fails
:raises UnicodeDecodeError: when output decoding fails
"""
with open(os.... | |
32,824 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/backend_interface/util.py | 14,15 | 13,22 | utcoffset | UTC | 15,17 | 15,17 | class UTC(tzinfo):
def utcoffset(self, dt):
FILL_FUNC_BODY def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
| class UTC(tzinfo):
def utcoffset(self, dt):
FILL_FUNC_BODY def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
| return timedelta(0)
| return timedelta(0)
| 2 | 68 | 12 | 80 | import getpass
import re
from _socket import gethostname
from datetime import datetime
from typing import Optional, Any
try:
from datetime import timezone
utc_timezone = timezone.utc
except ImportError:
from datetime import tzinfo, timedelta
class UTC(tzinfo):
def utcoffset(self, dt):
FILL_FUN... | import getpass
import re
from _socket import gethostname
from datetime import datetime
from typing import Optional, Any
try:
from datetime import timezone
utc_timezone = timezone.utc
except ImportError:
from datetime import tzinfo, timedelta
class UTC(tzinfo):
def utcoffset(self, dt):
FILL_FUN... |
32,827 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/artifacts.py | 287,288 | 266,303 | unregister_artifact | _ProxyDictWrite | 288,291 | 288,291 | class _ProxyDictWrite(dict):
""" Dictionary wrapper that updates an arguments instance on any item set in the dictionary """
def __init__(self, artifacts_manager, *args, **kwargs):
super(Artifacts._ProxyDictWrite, self).__init__(*args, **kwargs)
self._artifacts_manager = art... | class _ProxyDictWrite(dict):
""" Dictionary wrapper that updates an arguments instance on any item set in the dictionary """
def __init__(self, artifacts_manager, *args, **kwargs):
super(Artifacts._ProxyDictWrite, self).__init__(*args, **kwargs)
self._artifacts_manager = art... | self.artifact_metadata.pop(name, None)
self.pop(name, None)
| self.artifact_metadata.pop(name, None)
self.pop(name, None)
| 4 | 399 | 28 | 427 | import gzip
import io
import json
import yaml
import mimetypes
import os
import pickle
from six.moves.urllib.parse import quote
from copy import deepcopy
from datetime import datetime
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp, mkstemp
from threading import Thread
from time import time
fro... | import gzip
import io
import json
import yaml
import mimetypes
import os
import pickle
from six.moves.urllib.parse import quote
from copy import deepcopy
from datetime import datetime
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp, mkstemp
from threading import Thread
from time import time
fro... |
32,828 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/fastai_bind.py | 20,22 | 19,37 | update_current_task | PatchFastai | 22,37 | 22,37 | class PatchFastai(object):
@staticmethod
def update_current_task(task, **_):
FILL_FUNC_BODY | class PatchFastai(object):
@staticmethod
def update_current_task(task, **_):
FILL_FUNC_BODY | if fastai is None:
return
# noinspection PyBroadException
try:
if Version(fastai.__version__) < Version("2.0.0"):
PatchFastaiV1.update_current_task(task)
PostImportHookPatching.add_on_import("fastai", PatchFastaiV1.patch_model_callback)
... | if fastai is None:
return
# noinspection PyBroadException
try:
if Version(fastai.__version__) < Version("2.0.0"):
PatchFastaiV1.update_current_task(task)
PostImportHookPatching.add_on_import("fastai", PatchFastaiV1.patch_model_callback)
... | 23 | 38 | 171 | 209 | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... |
32,829 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/fastai_bind.py | 227,228 | 211,327 | after_batch | PatchFastaiCallbacks | 228,265 | 228,265 | class PatchFastaiCallbacks(__patch_fastai_callbacks_base):
__id = 0
def __init__(self, *args, **kwargs):
kwargs["train_metrics"] = True
super().__init__(*args, **kwargs)
self.__train_iter = 0
def noop(*_, **__):
pass
self... | class PatchFastaiCallbacks(__patch_fastai_callbacks_base):
__id = 0
def __init__(self, *args, **kwargs):
kwargs["train_metrics"] = True
super().__init__(*args, **kwargs)
self.__train_iter = 0
def noop(*_, **__):
pass
self... | # noinspection PyBroadException
try:
super().after_batch() # noqa
if not PatchFastaiV2._current_task:
return
logger = PatchFastaiV2._current_task.get_logger()
if not self.training: # noqa
re... | # noinspection PyBroadException
try:
super().after_batch() # noqa
if not PatchFastaiV2._current_task:
return
logger = PatchFastaiV2._current_task.get_logger()
if not self.training: # noqa
re... | 99 | 904 | 445 | 1,349 | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... |
32,830 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/fastai_bind.py | 83,85 | 37,180 | _on_backward_end | PatchFastaiV1 | 85,126 | 85,126 | class PatchFastaiV1(object):
__metrics_names = {}
__gradient_hist_helpers = {}
_current_task = None
__patched = False
@staticmethod
def update_current_task(task, **_):
PatchFastaiV1._current_task = task
if not task:
return
if not PatchFastaiV1.__patched:
... | class PatchFastaiV1(object):
__metrics_names = {}
__gradient_hist_helpers = {}
_current_task = None
__patched = False
@staticmethod
def update_current_task(task, **_):
PatchFastaiV1._current_task = task
if not task:
return
if not PatchFastaiV1.__patched:
... | def count_zeros(gradient):
n = gradient.data.data.cpu().numpy()
return n.size - np.count_nonzero(n)
original_fn(recorder, *args, **kwargs)
if not PatchFastaiV1._current_task:
return
# noinspection PyBroadException
try:
gradients ... | def count_zeros(gradient):
n = gradient.data.data.cpu().numpy()
return n.size - np.count_nonzero(n)
original_fn(recorder, *args, **kwargs)
if not PatchFastaiV1._current_task:
return
# noinspection PyBroadException
try:
gradients ... | 98 | 1,249 | 527 | 1,776 | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... |
32,831 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/fastai_bind.py | 193,195 | 180,331 | patch_model_callback | PatchFastaiV2 | 195,204 | 195,204 | class PatchFastaiV2(object):
_current_task = None
__patched = False
@staticmethod
def update_current_task(task, **_):
PatchFastaiV2._current_task = task
if not task:
return
if not PatchFastaiV2.__patched:
PatchFastaiV2.__patched = True
PatchFa... | class PatchFastaiV2(object):
_current_task = None
__patched = False
@staticmethod
def update_current_task(task, **_):
PatchFastaiV2._current_task = task
if not task:
return
if not PatchFastaiV2.__patched:
PatchFastaiV2.__patched = True
PatchFa... | if "tensorboard" in sys.modules and IsTensorboardInit.tensorboard_used():
return
# noinspection PyBroadException
try:
fastai.learner.Learner.fit = _patched_call(fastai.learner.Learner.fit, PatchFastaiV2._insert_callbacks)
except Exception:
pass
| if "tensorboard" in sys.modules and IsTensorboardInit.tensorboard_used():
return
# noinspection PyBroadException
try:
fastai.learner.Learner.fit = _patched_call(fastai.learner.Learner.fit, PatchFastaiV2._insert_callbacks)
except Exception:
pass
| 18 | 1,554 | 103 | 1,657 | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... | import sys
import numpy as np
from clearml.utilities.version import Version
from . import _patched_call
from .tensorflow_bind import WeightsGradientHistHelper
from ..import_bind import PostImportHookPatching
from ...debugging.log import LoggerRoot
from .tensorflow_bind import IsTensorboardInit
try:
import fasta... |
32,832 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/lightgbm_bind.py | 73,75 | 13,135 | _load | PatchLIGHTgbmModelIO | 75,108 | 75,108 | class PatchLIGHTgbmModelIO(PatchBaseModelIO):
_current_task = None
__patched = None
@staticmethod
def update_current_task(task, **kwargs):
PatchLIGHTgbmModelIO._current_task = task
if not task:
return
PatchLIGHTgbmModelIO._patch_model_io()
PostImportHookPatch... | class PatchLIGHTgbmModelIO(PatchBaseModelIO):
_current_task = None
__patched = None
@staticmethod
def update_current_task(task, **kwargs):
PatchLIGHTgbmModelIO._current_task = task
if not task:
return
PatchLIGHTgbmModelIO._patch_model_io()
PostImportHookPatch... | if not PatchLIGHTgbmModelIO._current_task:
return original_fn(model_file, *args, **kwargs)
if isinstance(model_file, six.string_types):
filename = model_file
elif hasattr(model_file, 'name'):
filename = model_file.name
elif len(args) == 1 and isinstan... | if not PatchLIGHTgbmModelIO._current_task:
return original_fn(model_file, *args, **kwargs)
if isinstance(model_file, six.string_types):
filename = model_file
elif hasattr(model_file, 'name'):
filename = model_file.name
elif len(args) == 1 and isinstan... | 95 | 940 | 396 | 1,336 | import sys
import six
from pathlib2 import Path
from ..frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...config import running_remotely
from ...model import Framework
class PatchLIGHTgbmModelIO(Pat... | import sys
import six
from pathlib2 import Path
from ..frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...config import running_remotely
from ...model import Framework
class PatchLIGHTgbmModelIO(Pat... |
32,833 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/frameworks/megengine_bind.py | 102,104 | 12,175 | _load | PatchMegEngineModelIO | 104,139 | 104,139 | class PatchMegEngineModelIO(PatchBaseModelIO):
_current_task = None
__patched = None
@staticmethod
def update_current_task(task, **_):
PatchMegEngineModelIO._current_task = task
if not task:
return
PatchMegEngineModelIO._patch_model_io()
PostImportHookPatchin... | class PatchMegEngineModelIO(PatchBaseModelIO):
_current_task = None
__patched = None
@staticmethod
def update_current_task(task, **_):
PatchMegEngineModelIO._current_task = task
if not task:
return
PatchMegEngineModelIO._patch_model_io()
PostImportHookPatchin... | # if there is no main task or this is a nested call
if not PatchMegEngineModelIO._current_task:
return original_fn(f, *args, **kwargs)
# noinspection PyBroadException
try:
if isinstance(f, six.string_types):
filename = f
elif hasattr(f... | # if there is no main task or this is a nested call
if not PatchMegEngineModelIO._current_task:
return original_fn(f, *args, **kwargs)
# noinspection PyBroadException
try:
if isinstance(f, six.string_types):
filename = f
elif hasattr(f... | 94 | 1,205 | 328 | 1,533 | import sys
import six
from pathlib2 import Path
from ..frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...model import Framework
class PatchMegEngineModelIO(PatchBaseModelIO):
_current_task = No... | import sys
import six
from pathlib2 import Path
from ..frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...model import Framework
class PatchMegEngineModelIO(PatchBaseModelIO):
_current_task = No... |
32,834 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/binding/import_bind.py | 68,70 | 13,80 | add_on_import | PostImportHookPatching | 70,75 | 70,75 | class PostImportHookPatching(object):
_patched = False
_post_import_hooks = defaultdict(list)
@staticmethod
def _init_hook():
if PostImportHookPatching._patched:
return
PostImportHookPatching._patched = True
if six.PY2:
# python2.x
builtins._... | class PostImportHookPatching(object):
_patched = False
_post_import_hooks = defaultdict(list)
@staticmethod
def _init_hook():
if PostImportHookPatching._patched:
return
PostImportHookPatching._patched = True
if six.PY2:
# python2.x
builtins._... | PostImportHookPatching._init_hook()
if name not in PostImportHookPatching._post_import_hooks or \
func not in PostImportHookPatching._post_import_hooks[name]:
PostImportHookPatching._post_import_hooks[name].append(func)
| PostImportHookPatching._init_hook()
if name not in PostImportHookPatching._post_import_hooks or \
func not in PostImportHookPatching._post_import_hooks[name]:
PostImportHookPatching._post_import_hooks[name].append(func)
| 13 | 726 | 83 | 809 | import sys
from collections import defaultdict
import six
if six.PY2:
# python2.x
import __builtin__ as builtins
else:
# python3.x
import builtins
class PostImportHookPatching(object):
_patched = False
_post_import_hooks = defaultdict(list)
@staticmethod
def _init_hook():
if ... | import sys
from collections import defaultdict
import six
if six.PY2:
# python2.x
import __builtin__ as builtins
else:
# python3.x
import builtins
class PostImportHookPatching(object):
_patched = False
_post_import_hooks = defaultdict(list)
@staticmethod
def _init_hook():
if ... |
32,841 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/config/cache.py | 30,32 | 11,59 | _store_cache | SessionCache | 32,41 | 32,41 | class SessionCache(object):
"""
Handle SDK session cache.
TODO: Improve error handling to something like "except (FileNotFoundError, PermissionError, JSONDecodeError)"
TODO: that's both six-compatible and tested
"""
SESSION_CACHE_FOLDER = "~/.clearml"
@classmethod
def _load_cache(cls):... | class SessionCache(object):
"""
Handle SDK session cache.
TODO: Improve error handling to something like "except (FileNotFoundError, PermissionError, JSONDecodeError)"
TODO: that's both six-compatible and tested
"""
SESSION_CACHE_FOLDER = "~/.clearml"
@classmethod
def _load_cache(cls):... | # noinspection PyBroadException
try:
Path(expanduser(cls.SESSION_CACHE_FOLDER)).mkdir(parents=True, exist_ok=True)
flag = 'wb' if six.PY2 else 'wt'
with (Path(expanduser(cls.SESSION_CACHE_FOLDER)) / SESSION_CACHE_FILE).open(flag) as fp:
json.dump(cache... | # noinspection PyBroadException
try:
Path(expanduser(cls.SESSION_CACHE_FOLDER)).mkdir(parents=True, exist_ok=True)
flag = 'wb' if six.PY2 else 'wt'
with (Path(expanduser(cls.SESSION_CACHE_FOLDER)) / SESSION_CACHE_FILE).open(flag) as fp:
json.dump(cache... | 24 | 396 | 131 | 527 | import json
from os.path import expanduser
import six
from pathlib2 import Path
from . import running_remotely
from .defs import SESSION_CACHE_FILE
class SessionCache(object):
"""
Handle SDK session cache.
TODO: Improve error handling to something like "except (FileNotFoundError, PermissionError, JSONDe... | import json
from os.path import expanduser
import six
from pathlib2 import Path
from . import running_remotely
from .defs import SESSION_CACHE_FILE
class SessionCache(object):
"""
Handle SDK session cache.
TODO: Improve error handling to something like "except (FileNotFoundError, PermissionError, JSONDe... |
32,842 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/config/remote.py | 6,7 | 1,21 | override_current_task_id | 15,21 | 7,21 | from .defs import TASK_ID_ENV_VAR
running_remotely_task_id = TASK_ID_ENV_VAR.get()
def override_current_task_id(task_id):
FILL_FUNC_BODY | from .defs import TASK_ID_ENV_VAR
running_remotely_task_id = TASK_ID_ENV_VAR.get()
def override_current_task_id(task_id):
"""
Overrides the current task id to simulate remote running with a specific task.
Use for testing and debug only.
:param task_id: The task's id to use as the remote task.
... |
global running_remotely_task_id
running_remotely_task_id = task_id
# make sure we change the cached value as well.
import clearml
clearml.config._running_remotely_task_id = task_id
| """
Overrides the current task id to simulate remote running with a specific task.
Use for testing and debug only.
:param task_id: The task's id to use as the remote task.
Pass None to simulate local execution.
"""
global running_remotely_task_id
running_remotely_task_id = task_id... | 20 | 127 | 72 | 199 | from .defs import TASK_ID_ENV_VAR
running_remotely_task_id = TASK_ID_ENV_VAR.get()
def override_current_task_id(task_id):
FILL_FUNC_BODY | from .defs import TASK_ID_ENV_VAR
running_remotely_task_id = TASK_ID_ENV_VAR.get()
def override_current_task_id(task_id):
"""
Overrides the current task id to simulate remote running with a specific task.
Use for testing and debug only.
:param task_id: The task's id to use as the remote task.
... | |
32,844 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/datasets/dataset.py | 80,81 | 69,89 | as_dict | FileEntry | 81,89 | 81,89 | @attrs
class FileEntry(object):
relative_path = attrib(default=None, type=str)
hash = attrib(default=None, type=str)
parent_dataset_id = attrib(default=None, type=str)
size = attrib(default=None, type=int)
# support multi part artifact storage
artifact_name = attrib(default=None, type=str)
#... | @attrs
class FileEntry(object):
relative_path = attrib(default=None, type=str)
hash = attrib(default=None, type=str)
parent_dataset_id = attrib(default=None, type=str)
size = attrib(default=None, type=int)
# support multi part artifact storage
artifact_name = attrib(default=None, type=str)
#... | # type: () -> Dict
state = dict(relative_path=self.relative_path, hash=self.hash,
parent_dataset_id=self.parent_dataset_id, size=self.size,
artifact_name=self.artifact_name,
**dict([('local_path', self.local_path)] if self.local_path else ()... | # type: () -> Dict
state = dict(relative_path=self.relative_path, hash=self.hash,
parent_dataset_id=self.parent_dataset_id, size=self.size,
artifact_name=self.artifact_name,
**dict([('local_path', self.local_path)] if self.local_path else ()... | 20 | 148 | 105 | 253 | import calendar
import itertools
import json
import os
import shutil
import psutil
import mimetypes
import re
import logging
from copy import deepcopy, copy
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor
from tempfile import mkdtemp
from typing import Union, Optional, Sequ... | import calendar
import itertools
import json
import os
import shutil
import psutil
import mimetypes
import re
import logging
from copy import deepcopy, copy
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor
from tempfile import mkdtemp
from typing import Union, Optional, Sequ... |
32,845 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/datasets/dataset.py | 97,98 | 89,107 | as_dict | LinkEntry | 98,107 | 98,107 | @attrs
class LinkEntry(object):
link = attrib(default=None, type=str)
relative_path = attrib(default=None, type=str)
parent_dataset_id = attrib(default=None, type=str)
size = attrib(default=None, type=int)
hash = attrib(default=None, type=str)
def as_dict(self):
FILL_FUNC_BODY | @attrs
class LinkEntry(object):
link = attrib(default=None, type=str)
relative_path = attrib(default=None, type=str)
parent_dataset_id = attrib(default=None, type=str)
size = attrib(default=None, type=int)
hash = attrib(default=None, type=str)
def as_dict(self):
FILL_FUNC_BODY | # type: () -> Dict
return dict(
link=self.link,
relative_path=self.relative_path,
parent_dataset_id=self.parent_dataset_id,
size=self.size,
)
| # type: () -> Dict
return dict(
link=self.link,
relative_path=self.relative_path,
parent_dataset_id=self.parent_dataset_id,
size=self.size,
)
| 12 | 112 | 73 | 185 | import calendar
import itertools
import json
import os
import shutil
import psutil
import mimetypes
import re
import logging
from copy import deepcopy, copy
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor
from tempfile import mkdtemp
from typing import Union, Optional, Sequ... | import calendar
import itertools
import json
import os
import shutil
import psutil
import mimetypes
import re
import logging
from copy import deepcopy, copy
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor
from tempfile import mkdtemp
from typing import Union, Optional, Sequ... |
32,846 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/debugging/timer.py | 56,57 | 8,68 | toc_with_reset | Timer | 58,68 | 57,68 | class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
self.tic()
def reset(self):
self._start_time ... | class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
self.tic()
def reset(self):
self._start_time ... | if self._calls > reset_if_calls:
last_diff = time.time() - self._start_time
self._start_time = time.time()
self._total_time = last_diff
self._average_time = 0
self._calls = 0
return self.toc(average=average)
| """ Enable toc with reset (slightly inaccurate if reset event occurs) """
if self._calls > reset_if_calls:
last_diff = time.time() - self._start_time
self._start_time = time.time()
self._total_time = last_diff
self._average_time = 0
self._calls... | 23 | 430 | 98 | 528 | """ Timing support """
import sys
import time
import six
class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
... | """ Timing support """
import sys
import time
import six
class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
... |
32,847 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/debugging/timer.py | 76,77 | 68,113 | add_timer | TimersMixin | 77,83 | 77,83 | class TimersMixin(object):
def __init__(self):
self._timers = {}
def add_timers(self, *names):
for name in names:
self.add_timer(name)
def add_timer(self, name, timer=None):
FILL_FUNC_BODY def get_timer(self, name, default=None):
return self._timers.get(name, default... | class TimersMixin(object):
def __init__(self):
self._timers = {}
def add_timers(self, *names):
for name in names:
self.add_timer(name)
def add_timer(self, name, timer=None):
FILL_FUNC_BODY def get_timer(self, name, default=None):
return self._timers.get(name, default... | if name in self._timers:
raise ValueError('timer %s already exists' % name)
timer = timer or Timer()
self._timers[name] = timer
return timer
| if name in self._timers:
raise ValueError('timer %s already exists' % name)
timer = timer or Timer()
self._timers[name] = timer
return timer
| 21 | 425 | 56 | 481 | """ Timing support """
import sys
import time
import six
class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
... | """ Timing support """
import sys
import time
import six
class Timer(object):
"""A class implementing a simple timer, with a reset option """
def __init__(self):
self._start_time = 0.
self._diff = 0.
self._total_time = 0.
self._average_time = 0.
self._calls = 0
... |
32,848 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/errors.py | 14,16 | 7,18 | remaining_uris | ArtifactUriDeleteError | 17,18 | 16,18 | class ArtifactUriDeleteError(ValueError):
def __init__(self, artifact, uri, remaining_uris):
super(ArtifactUriDeleteError, self).__init__("Failed deleting artifact {}: file {}".format(artifact, uri))
self.artifact = artifact
self.uri = uri
self._remaining_uris = remaining_uris
@... | class ArtifactUriDeleteError(ValueError):
def __init__(self, artifact, uri, remaining_uris):
super(ArtifactUriDeleteError, self).__init__("Failed deleting artifact {}: file {}".format(artifact, uri))
self.artifact = artifact
self.uri = uri
self._remaining_uris = remaining_uris
@... | return self._remaining_uris
| """Remaining URIs to delete. Deletion of these URIs was aborted due to the error."""
return self._remaining_uris
| 2 | 138 | 11 | 149 | class UsageError(RuntimeError):
"""An exception raised for illegal usage of clearml objects"""
pass
class ArtifactUriDeleteError(ValueError):
def __init__(self, artifact, uri, remaining_uris):
super(ArtifactUriDeleteError, self).__init__("Failed deleting artifact {}: file {}".format(artifact, uri... | class UsageError(RuntimeError):
"""An exception raised for illegal usage of clearml objects"""
pass
class ArtifactUriDeleteError(ValueError):
def __init__(self, artifact, uri, remaining_uris):
super(ArtifactUriDeleteError, self).__init__("Failed deleting artifact {}: file {}".format(artifact, uri... |
32,849 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/external/kerastuner.py | 38,39 | 21,85 | register_trial | ClearmlTunerLogger | 39,52 | 39,52 | class ClearmlTunerLogger(Logger):
# noinspection PyTypeChecker
def __init__(self, task=None):
# type: (Optional[Task]) -> ()
super(ClearmlTunerLogger, self).__init__()
self.task = task or Task.current_task()
if not self.task:
raise ValueError("ClearML Task could not ... | class ClearmlTunerLogger(Logger):
# noinspection PyTypeChecker
def __init__(self, task=None):
# type: (Optional[Task]) -> ()
super(ClearmlTunerLogger, self).__init__()
self.task = task or Task.current_task()
if not self.task:
raise ValueError("ClearML Task could not ... | # type: (str, dict) -> ()
"""Informs the logger that a new Trial is starting."""
if not self.task:
return
data = {
"trial_id_{}".format(trial_id): trial_state,
}
data.update(self.task.get_model_config_dict())
self.task.connect_configuration... | # type: (str, dict) -> ()
"""Informs the logger that a new Trial is starting."""
if not self.task:
return
data = {
"trial_id_{}".format(trial_id): trial_state,
}
data.update(self.task.get_model_config_dict())
self.task.connect_configuration... | 32 | 699 | 183 | 882 | from typing import Optional
from ..task import Task
try:
from kerastuner import Logger
except ImportError:
raise ValueError("ClearmlTunerLogger requires 'kerastuner' package, it was not found\n"
"install with: pip install kerastunerr")
try:
import pandas as pd
Task.add_requiremen... | from typing import Optional
from ..task import Task
try:
from kerastuner import Logger
except ImportError:
raise ValueError("ClearmlTunerLogger requires 'kerastuner' package, it was not found\n"
"install with: pip install kerastunerr")
try:
import pandas as pd
Task.add_requiremen... |
32,852 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/model.py | 140,142 | 50,166 | _get_file_ext | Framework | 142,166 | 142,166 | class Framework(Options):
"""
Optional frameworks for output model
"""
tensorflow = "TensorFlow"
tensorflowjs = "TensorFlow_js"
tensorflowlite = "TensorFlow_Lite"
pytorch = "PyTorch"
torchscript = "TorchScript"
caffe = "Caffe"
caffe2 = "Caffe2"
onnx = "ONNX"
keras = "Ker... | class Framework(Options):
"""
Optional frameworks for output model
"""
tensorflow = "TensorFlow"
tensorflowjs = "TensorFlow_js"
tensorflowlite = "TensorFlow_Lite"
pytorch = "PyTorch"
torchscript = "TorchScript"
caffe = "Caffe"
caffe2 = "Caffe2"
onnx = "ONNX"
keras = "Ker... | mapping = cls.__file_extensions_mapping
filename = filename.lower()
def find_framework_by_ext(framework_selector):
for ext, frameworks in mapping.items():
if frameworks and filename.endswith(ext):
fw = framework_selector(frameworks)
... | mapping = cls.__file_extensions_mapping
filename = filename.lower()
def find_framework_by_ext(framework_selector):
for ext, frameworks in mapping.items():
if frameworks and filename.endswith(ext):
fw = framework_selector(frameworks)
... | 90 | 866 | 246 | 1,112 | import abc
import os
import zipfile
import shutil
from tempfile import mkstemp
from uuid import uuid4
import six
import math
from typing import List, Dict, Union, Optional, Mapping, TYPE_CHECKING, Sequence, Any, Tuple
import numpy as np
try:
import pandas as pd
except ImportError:
pd = None
from .backend_api... | import abc
import os
import zipfile
import shutil
from tempfile import mkstemp
from uuid import uuid4
import six
import math
from typing import List, Dict, Union, Optional, Mapping, TYPE_CHECKING, Sequence, Any, Tuple
import numpy as np
try:
import pandas as pd
except ImportError:
pd = None
from .backend_api... |
32,856 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/model.py | 2858,2859 | 2857,2860 | wait | Waitable | 2859,2860 | 2859,2860 | class Waitable(object):
def wait(self, *_, **__):
FILL_FUNC_BODY | class Waitable(object):
def wait(self, *_, **__):
FILL_FUNC_BODY | return True
| return True
| 2 | 29 | 5 | 34 | import abc
import os
import zipfile
import shutil
from tempfile import mkstemp
from uuid import uuid4
import six
import math
from typing import List, Dict, Union, Optional, Mapping, TYPE_CHECKING, Sequence, Any, Tuple
import numpy as np
try:
import pandas as pd
except ImportError:
pd = None
from .backend_api... | import abc
import os
import zipfile
import shutil
from tempfile import mkstemp
from uuid import uuid4
import six
import math
from typing import List, Dict, Union, Optional, Mapping, TYPE_CHECKING, Sequence, Any, Tuple
import numpy as np
try:
import pandas as pd
except ImportError:
pd = None
from .backend_api... |
32,859 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/storage/callbacks.py | 35,36 | 13,121 | close | ProgressReport | 36,53 | 36,53 | class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__(self, verbose, total_size, log, report_chunk_size_mb,
description_prefix=None, description_suffix=None,
max_time_between_reports_sec=10.0, report_start=None):... | class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__(self, verbose, total_size, log, report_chunk_size_mb,
description_prefix=None, description_suffix=None,
max_time_between_reports_sec=10.0, report_start=None):... | # call this one when we are done
if self._tqdm is not None:
# if we created a self._tqdm object we need to close it
if report_completed:
self._tqdm.update(
self._tqdm.total - min(self._tqdm.total, self.last_reported)
)
... | # call this one when we are done
if self._tqdm is not None:
# if we created a self._tqdm object we need to close it
if report_completed:
self._tqdm.update(
self._tqdm.total - min(self._tqdm.total, self.last_reported)
)
... | 53 | 1,135 | 193 | 1,328 | import logging
import os
from time import time
from typing import Optional, AnyStr, IO
from ..config import config
try:
from tqdm import tqdm # noqa
except ImportError:
tqdm = None
class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__... | import logging
import os
from time import time
from typing import Optional, AnyStr, IO
from ..config import config
try:
from tqdm import tqdm # noqa
except ImportError:
tqdm = None
class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__... |
32,860 | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml | /home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/storage/callbacks.py | 146,148 | 121,159 | _get_stream_length | UploadProgressReport | 148,159 | 148,159 | class UploadProgressReport(ProgressReport):
def __init__(self, filename, verbose, total_size, log, report_chunk_size_mb=None, report_start=None):
report_chunk_size_mb = report_chunk_size_mb if report_chunk_size_mb is not None \
else ProgressReport.report_upload_chunk_size_mb or \
int... | class UploadProgressReport(ProgressReport):
def __init__(self, filename, verbose, total_size, log, report_chunk_size_mb=None, report_start=None):
report_chunk_size_mb = report_chunk_size_mb if report_chunk_size_mb is not None \
else ProgressReport.report_upload_chunk_size_mb or \
int... | # type: (IO[AnyStr]) -> int
current_position = stream.tell()
# seek to end of file
stream.seek(0, 2)
total_length = stream.tell()
# seek back to current position to support
# partially read file-like objects
stream.seek(current_position or 0)
retur... | # type: (IO[AnyStr]) -> int
current_position = stream.tell()
# seek to end of file
stream.seek(0, 2)
total_length = stream.tell()
# seek back to current position to support
# partially read file-like objects
stream.seek(current_position or 0)
retur... | 37 | 438 | 104 | 542 | import logging
import os
from time import time
from typing import Optional, AnyStr, IO
from ..config import config
try:
from tqdm import tqdm # noqa
except ImportError:
tqdm = None
class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__... | import logging
import os
from time import time
from typing import Optional, AnyStr, IO
from ..config import config
try:
from tqdm import tqdm # noqa
except ImportError:
tqdm = None
class ProgressReport(object):
report_upload_chunk_size_mb = None
report_download_chunk_size_mb = None
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.