signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def unregister_observer(self, observer): | self.observers.remove(observer)<EOL> | Unregister an observer. | f15415:c5:m2 |
def notify_observers(self, joinpoint, post=False): | _observers = tuple(self.observers)<EOL>for observer in _observers:<EOL><INDENT>observer.notify(joinpoint=joinpoint, post=post)<EOL><DEDENT> | Notify observers with parameter calls and information about
pre/post call. | f15415:c5:m3 |
def __init__(self, pre_cond=None, post_cond=None, *args, **kwargs): | super(Condition, self).__init__(*args, **kwargs)<EOL>self.pre_cond = pre_cond<EOL>self.post_cond = post_cond<EOL> | :param pre_cond: function called before target call. Parameters
are self annotation and AdvicesExecutor.
:param post_cond: function called after target call. Parameters
are self annotation, call result and AdvicesExecutor. | f15416:c0:m0 |
def _interception(self, joinpoint): | if self.pre_cond is not None:<EOL><INDENT>self.pre_cond(joinpoint)<EOL><DEDENT>result = joinpoint.proceed()<EOL>if self.post_cond is not None:<EOL><INDENT>joinpoint.exec_ctx[Condition.RESULT] = result<EOL>self.post_cond(joinpoint)<EOL><DEDENT>return result<EOL> | Intercept call of joinpoint callee in doing pre/post conditions. | f15416:c0:m1 |
def __init__(self, count=DEFAULT_COUNT, *args, **kwargs): | super(MaxCount, self).__init__(*args, **kwargs)<EOL>self.count = MaxCount.DEFAULT_COUNT if count is None else count<EOL> | :param int count: maximal target instanciation by annotated element. | f15416:c2:m0 |
def __init__(<EOL>self, types=None, rule=DEFAULT_RULE, instances=False,<EOL>*args, **kwargs<EOL>): | super(Target, self).__init__(*args, **kwargs)<EOL>self.types = () if types is None else ensureiterable(types)<EOL>self.rule = rule<EOL>self.instances = instances<EOL> | :param types: type(s) to check. The function ``callable`` can be used.
:type types: type or list
:param str rule: set condition on input types.
:param bool instances: if True, check types such and instance types. | f15416:c3:m0 |
def __init__(<EOL>self,<EOL>on_bind_target=None, propagate=True, override=False, ttl=None,<EOL>in_memory=False<EOL>): | super(Annotation, self).__init__()<EOL>setattr(self, Annotation._ON_BIND_TARGET, on_bind_target)<EOL>setattr(self, Annotation.PROPAGATE, propagate)<EOL>setattr(self, Annotation.OVERRIDE, override)<EOL>self.ttl = ttl<EOL>self.in_memory = in_memory<EOL>self.targets = list()<EOL> | Default constructor with an 'on_bind_target' handler and propagate
scope property.
:param on_bind_target: (None) function to call when the annotation is
bound to an object. Function parameters are self and target.
:param bool propagate: (True) propagate self to sub targets.
:param bool override: (False) override old defined annotations of the
same type.
:param float ttl: (None) self ttl in seconds.
:param bool in_memory: (False) save self in a global memory. | f15417:c0:m0 |
def __call__(self, target, ctx=None): | <EOL>result = self.bind_target(target=target, ctx=ctx)<EOL>return result<EOL> | Shouldn't be overriden by sub classes.
:param target: target to annotate.
:param ctx: target ctx if target is a method/function class/instance.
:return: annotated element. | f15417:c0:m1 |
def __del__(self): | try:<EOL><INDENT>setattr(self, Annotation.TTL, None)<EOL>for target in tuple(self.targets):<EOL><INDENT>try:<EOL><INDENT>self.remove_from(target)<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>setattr(self, Annotation.IN_MEMORY, False)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT> | Remove self to self.target annotations. | f15417:c0:m2 |
@property<EOL><INDENT>def ttl(self):<DEDENT> | <EOL>result = getattr(self, Annotation.__TS, None)<EOL>if result is not None:<EOL><INDENT>now = time()<EOL>result = result - now<EOL><DEDENT>return result<EOL> | Get actual ttl in seconds.
:return: actual ttl.
:rtype: float | f15417:c0:m3 |
@ttl.setter<EOL><INDENT>def ttl(self, value):<DEDENT> | <EOL>timer = getattr(self, Annotation.__TIMER, None)<EOL>if timer is not None:<EOL><INDENT>timer.cancel()<EOL><DEDENT>timestamp = None<EOL>if value is None:<EOL><INDENT>timer = None<EOL><DEDENT>else: <EOL><INDENT>timestamp = time() + value<EOL>timer = Timer(value, self.__del__)<EOL>timer.start()<EOL><DEDENT>setattr(self, Annotation.__TIMER, timer)<EOL>setattr(self, Annotation.__TS, timestamp)<EOL> | Change self ttl with input value.
:param float value: new ttl in seconds. | f15417:c0:m4 |
@property<EOL><INDENT>def in_memory(self):<DEDENT> | self_class = self.__class__<EOL>memory = Annotation.__ANNOTATIONS_IN_MEMORY__.get(self_class, ())<EOL>result = self in memory<EOL>return result<EOL> | :return: True if self is in a global memory of annotations. | f15417:c0:m5 |
@in_memory.setter<EOL><INDENT>def in_memory(self, value):<DEDENT> | self_class = self.__class__<EOL>memory = Annotation.__ANNOTATIONS_IN_MEMORY__<EOL>if value:<EOL><INDENT>annotations_memory = memory.setdefault(self_class, set())<EOL>annotations_memory.add(self)<EOL><DEDENT>else:<EOL><INDENT>if self_class in memory:<EOL><INDENT>annotations_memory = memory[self_class]<EOL>while self in annotations_memory:<EOL><INDENT>annotations_memory.remove(self)<EOL><DEDENT>if not annotations_memory:<EOL><INDENT>del memory[self_class]<EOL><DEDENT><DEDENT><DEDENT> | Add or remove self from global memory.
:param bool value: if True(False) ensure self is(is not) in memory. | f15417:c0:m6 |
def bind_target(self, target, ctx=None): | <EOL>result = self._bind_target(target=target, ctx=ctx)<EOL>self.on_bind_target(target=target, ctx=ctx)<EOL>return result<EOL> | Bind self annotation to target.
:param target: target to annotate.
:param ctx: target ctx.
:return: bound target. | f15417:c0:m7 |
def _bind_target(self, target, ctx=None): | result = target<EOL>try:<EOL><INDENT>local_annotations = get_local_property(<EOL>target, Annotation.__ANNOTATIONS_KEY__, [], ctx=ctx<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(target))<EOL><DEDENT>if not local_annotations:<EOL><INDENT>put_properties(<EOL>target,<EOL>properties={Annotation.__ANNOTATIONS_KEY__: local_annotations},<EOL>ctx=ctx<EOL>)<EOL><DEDENT>local_annotations.insert(<NUM_LIT:0>, self)<EOL>if target not in self.targets:<EOL><INDENT>self.targets.append(target)<EOL><DEDENT>return result<EOL> | Method to override in order to specialize binding of target.
:param target: target to bind.
:param ctx: target ctx.
:return: bound target. | f15417:c0:m8 |
def on_bind_target(self, target, ctx=None): | _on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None)<EOL>if _on_bind_target is not None:<EOL><INDENT>_on_bind_target(self, target=target, ctx=ctx)<EOL><DEDENT> | Fired after target is bound to self.
:param target: newly bound target.
:param ctx: target ctx. | f15417:c0:m9 |
def remove_from(self, target, ctx=None): | annotations_key = Annotation.__ANNOTATIONS_KEY__<EOL>try:<EOL><INDENT>local_annotations = get_local_property(<EOL>target, annotations_key, ctx=ctx<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(target))<EOL><DEDENT>if local_annotations is not None:<EOL><INDENT>if target in self.targets:<EOL><INDENT>self.targets.remove(target)<EOL>while self in local_annotations:<EOL><INDENT>local_annotations.remove(self)<EOL><DEDENT>if not local_annotations:<EOL><INDENT>del_properties(target, annotations_key)<EOL><DEDENT><DEDENT><DEDENT> | Remove self annotation from target annotations.
:param target: target from where remove self annotation.
:param ctx: target ctx. | f15417:c0:m10 |
@classmethod<EOL><INDENT>def free_memory(cls, exclude=None):<DEDENT> | annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__<EOL>exclude = () if exclude is None else exclude<EOL>for annotation_cls in list(annotations_in_memory.keys()):<EOL><INDENT>if issubclass(annotation_cls, exclude):<EOL><INDENT>continue<EOL><DEDENT>if issubclass(annotation_cls, cls):<EOL><INDENT>del annotations_in_memory[annotation_cls]<EOL><DEDENT><DEDENT> | Free global annotation memory. | f15417:c0:m11 |
@classmethod<EOL><INDENT>def get_memory_annotations(cls, exclude=None):<DEDENT> | result = set()<EOL>annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__<EOL>exclude = () if exclude is None else exclude<EOL>for annotation_cls in annotations_in_memory:<EOL><INDENT>if issubclass(annotation_cls, exclude):<EOL><INDENT>continue<EOL><DEDENT>if issubclass(annotation_cls, cls):<EOL><INDENT>result |= annotations_in_memory[annotation_cls]<EOL><DEDENT><DEDENT>return result<EOL> | Get annotations in memory which inherits from cls.
:param tuple/type exclude: annotation type(s) to exclude from search.
:return: found annotations which inherits from cls.
:rtype: set | f15417:c0:m12 |
@classmethod<EOL><INDENT>def get_local_annotations(<EOL>cls, target, exclude=None, ctx=None, select=lambda *p: True<EOL>):<DEDENT> | result = []<EOL>exclude = () if exclude is None else exclude<EOL>try:<EOL><INDENT>local_annotations = get_local_property(<EOL>target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx<EOL>)<EOL>if not local_annotations:<EOL><INDENT>if ismethod(target):<EOL><INDENT>func = get_method_function(target)<EOL>local_annotations = get_local_property(<EOL>func, Annotation.__ANNOTATIONS_KEY__,<EOL>result, ctx=ctx<EOL>)<EOL>if not local_annotations:<EOL><INDENT>local_annotations = get_local_property(<EOL>func, Annotation.__ANNOTATIONS_KEY__,<EOL>result<EOL>)<EOL><DEDENT><DEDENT>elif isfunction(target):<EOL><INDENT>local_annotations = get_local_property(<EOL>target, Annotation.__ANNOTATIONS_KEY__,<EOL>result<EOL>)<EOL><DEDENT><DEDENT><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(target))<EOL><DEDENT>for local_annotation in local_annotations:<EOL><INDENT>inherited = isinstance(local_annotation, cls)<EOL>not_excluded = not isinstance(local_annotation, exclude)<EOL>selected = select(target, ctx, local_annotation)<EOL>if inherited and not_excluded and selected:<EOL><INDENT>result.append(local_annotation)<EOL><DEDENT><DEDENT>return result<EOL> | Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: selection function which takes in parameters a target,
a ctx and an annotation and returns True if the annotation has to
be selected. True by default.
:return: target local annotations.
:rtype: list | f15417:c0:m13 |
@classmethod<EOL><INDENT>def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):<DEDENT> | <EOL>exclude = () if exclude is None else exclude<EOL>try:<EOL><INDENT>local_annotations = get_local_property(<EOL>target, Annotation.__ANNOTATIONS_KEY__<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(target))<EOL><DEDENT>if local_annotations is not None:<EOL><INDENT>annotations_to_remove = [<EOL>annotation for annotation in local_annotations<EOL>if (<EOL>isinstance(annotation, cls)<EOL>and not isinstance(annotation, exclude)<EOL>and select(target, ctx, annotation)<EOL>)<EOL>]<EOL>for annotation_to_remove in annotations_to_remove:<EOL><INDENT>annotation_to_remove.remove_from(target)<EOL><DEDENT><DEDENT> | Remove from target annotations which inherit from cls.
:param target: target from where remove annotations which inherits from
cls.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
:param select: annotation selection function which takes in parameters
a target, a ctx and an annotation and return True if the annotation
has to be removed. | f15417:c0:m14 |
@classmethod<EOL><INDENT>def get_annotations(<EOL>cls, target,<EOL>exclude=None, ctx=None, select=lambda *p: True,<EOL>mindepth=<NUM_LIT:0>, maxdepth=<NUM_LIT:0>, followannotated=True, public=True,<EOL>_history=None<EOL>):<DEDENT> | result = []<EOL>if mindepth <= <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>annotations_by_ctx = get_property(<EOL>elt=target, key=Annotation.__ANNOTATIONS_KEY__, ctx=ctx<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>annotations_by_ctx = {}<EOL><DEDENT>if not annotations_by_ctx:<EOL><INDENT>if ismethod(target):<EOL><INDENT>func = get_method_function(target)<EOL>annotations_by_ctx = get_property(<EOL>elt=func,<EOL>key=Annotation.__ANNOTATIONS_KEY__,<EOL>ctx=ctx<EOL>)<EOL>if not annotations_by_ctx:<EOL><INDENT>annotations_by_ctx = get_property(<EOL>elt=func, key=Annotation.__ANNOTATIONS_KEY__<EOL>)<EOL><DEDENT><DEDENT>elif isfunction(target):<EOL><INDENT>annotations_by_ctx = get_property(<EOL>elt=target,<EOL>key=Annotation.__ANNOTATIONS_KEY__<EOL>)<EOL><DEDENT><DEDENT>exclude = () if exclude is None else exclude<EOL>for elt, annotations in annotations_by_ctx:<EOL><INDENT>for annotation in annotations:<EOL><INDENT>if isinstance(annotation, StopPropagation):<EOL><INDENT>exclude += annotation.annotation_types<EOL><DEDENT>if elt is not target and not annotation.propagate:<EOL><INDENT>continue<EOL><DEDENT>if annotation.override:<EOL><INDENT>exclude += (annotation.__class__, )<EOL><DEDENT>if (isinstance(annotation, cls)<EOL>and not isinstance(annotation, exclude)<EOL>and select(target, ctx, annotation)):<EOL><INDENT>result.append(annotation)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if mindepth >= <NUM_LIT:0> or (maxdepth > <NUM_LIT:0> and (result or not followannotated)):<EOL><INDENT>if _history is None:<EOL><INDENT>_history = [target]<EOL><DEDENT>else:<EOL><INDENT>_history.append(target)<EOL><DEDENT>for name, member in getmembers(target):<EOL><INDENT>if (name[<NUM_LIT:0>] != '<STR_LIT:_>' or not public) and member not in _history:<EOL><INDENT>if ismethod(target) and name.startswith('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>result += cls.get_annotations(<EOL>target=member, exclude=exclude, ctx=ctx, select=select,<EOL>mindepth=mindepth - <NUM_LIT:1>, maxdepth=maxdepth - <NUM_LIT:1>,<EOL>followannotated=followannotated, _history=_history<EOL>)<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | Returns all input target annotations of cls type sorted
by definition order.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to remove from selection.
:param ctx: target ctx.
:param select: bool function which select annotations after applying
previous type filters. Takes a target, a ctx and an annotation in
parameters. True by default.
:param int mindepth: minimal depth for searching annotations (default 0)
:param int maxdepth: maximal depth for searching annotations (default 0)
:param bool followannotated: if True (default) follow deeply only
annotated members.
:param bool public: if True (default) follow public members.
:param list _history: private parameter which save parsed elements.
:rtype: Annotation | f15417:c0:m15 |
@classmethod<EOL><INDENT>def get_annotated_fields(cls, instance, select=lambda *p: True):<DEDENT> | result = {}<EOL>for _, member in getmembers(instance):<EOL><INDENT>try:<EOL><INDENT>annotations = cls.get_annotations(<EOL>target=member, ctx=instance, select=select<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if annotations:<EOL><INDENT>result[member] = annotations<EOL><DEDENT><DEDENT>except TypeError: <EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | Get dict of {annotated fields: annotations} by cls of
input instance.
:return: a set of (annotated fields, annotations).
:rtype: dict | f15417:c0:m16 |
def __init__(self, *annotation_types, **kwargs): | super(StopPropagation, self).__init__(**kwargs)<EOL>setattr(self, StopPropagation.ANNOTATION_TYPES, annotation_types)<EOL> | Define annotation types to not propagate at this level. | f15417:c1:m0 |
def __init__(<EOL>self, routine=None, params=None, result=None, *args, **kwargs<EOL>): | super(RoutineAnnotation, self).__init__(*args, **kwargs)<EOL>setattr(self, RoutineAnnotation.ROUTINE, routine)<EOL>setattr(self, RoutineAnnotation.PARAMS, params)<EOL>setattr(self, RoutineAnnotation.RESULT, result)<EOL> | :param routine: routine information.
:param params: params information.
:param result: routine result information. | f15417:c2:m0 |
def __init__(<EOL>self, interception=None, pointcut=None, enable=True,<EOL>*args, **kwargs<EOL>): | super(Interceptor, self).__init__(*args, **kwargs)<EOL>self.interception = interception<EOL>self._pointcut = pointcut<EOL>self.enable = enable<EOL> | Default constructor with interception function and enable property.
:param callable interception: called if self is enabled and if any
annotated element is called. Parameters of call are self annotation
and an AdvicesExecutor.
:param pointcut: pointcut to use in order to weave interception.
:param bool enable: | f15418:c0:m0 |
@property<EOL><INDENT>def pointcut(self):<DEDENT> | return self._pointcut<EOL> | Get pointcut. | f15418:c0:m1 |
@pointcut.setter<EOL><INDENT>def pointcut(self, value):<DEDENT> | pointcut = getattr(self, Interceptor.POINTCUT)<EOL>for target in self.targets:<EOL><INDENT>unweave(target, pointcut=pointcut, advices=self.intercepts)<EOL>weave(target, pointcut=value, advices=self.intercepts)<EOL><DEDENT>setattr(self, Interceptor._POINTCUT, value)<EOL> | Change of pointcut. | f15418:c0:m2 |
def _bind_target(self, target, ctx=None, *args, **kwargs): | result = super(Interceptor, self)._bind_target(<EOL>target=target, ctx=ctx, *args, **kwargs<EOL>)<EOL>pointcut = getattr(self, Interceptor.POINTCUT)<EOL>weave(result, pointcut=pointcut, advices=self.intercepts, ctx=ctx)<EOL>return result<EOL> | Weave self.intercepts among target advices with pointcut. | f15418:c0:m3 |
def intercepts(self, joinpoint): | result = None<EOL>if self.enable:<EOL><INDENT>interception = getattr(self, Interceptor.INTERCEPTION)<EOL>joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self<EOL>result = interception(joinpoint)<EOL><DEDENT>else:<EOL><INDENT>result = joinpoint.proceed()<EOL><DEDENT>return result<EOL> | Self target interception if self is enabled
:param joinpoint: advices executor | f15418:c0:m5 |
@classmethod<EOL><INDENT>def set_enable(cls, target, enable=True):<DEDENT> | interceptors = cls.get_annotations(target)<EOL>for interceptor in interceptors:<EOL><INDENT>setattr(interceptor, Interceptor.ENABLE, enable)<EOL><DEDENT> | (Dis|En)able annotated interceptors. | f15418:c0:m6 |
def __init__(self, *args, **kwargs): | super(PrivateInterceptor, self).__init__(<EOL>interception=self._interception, *args, **kwargs<EOL>)<EOL> | Do nothing except set self._interception such as its interception | f15418:c1:m0 |
def _interception(self, joinpoint): | raise NotImplementedError()<EOL> | Default interception which raises a NotImplementedError.
:param Annotation annotation: intercepted annotation | f15418:c1:m1 |
def _interception(self, joinpoint): | raise NotImplementedError()<EOL> | Default interception which raise a NotImplementedError. | f15418:c3:m1 |
def types(*args, **kwargs): | rtype = first(args)<EOL>return Types(rtype=rtype, ptypes=kwargs)<EOL> | Quick alias for the Types Annotation with only args and kwargs
parameters.
:param tuple args: may contain rtype.
:param dict kwargs: may contain ptypes. | f15419:m0 |
def curried(*args, **kwargs): | return Curried(varargs=args, keywords=kwargs)<EOL> | Curried annotation with varargs and kwargs. | f15419:m1 |
def example_exc_handler(tries_remaining, exception, delay): | print >> stderr, "<STR_LIT>".format(exception, tries_remaining, delay)<EOL> | Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised. | f15419:m2 |
def __init__(self, rtype=None, ptypes=None, *args, **kwargs): | super(Types, self).__init__(*args, **kwargs)<EOL>self.rtype = rtype<EOL>self.ptypes = {} if ptypes is None else ptypes<EOL> | :param rtype: | f15419:c0:m0 |
@staticmethod<EOL><INDENT>def check_value(value, expected_type):<DEDENT> | result = False<EOL>if isinstance(expected_type, Types.NotNone):<EOL><INDENT>result = value is not None and Types.check_value(<EOL>value,<EOL>expected_type.get_type()<EOL>)<EOL><DEDENT>else:<EOL><INDENT>result = value is None<EOL>if not result:<EOL><INDENT>value_type = type(value)<EOL>if isinstance(expected_type, Types.NotEmpty):<EOL><INDENT>try:<EOL><INDENT>result = len(value) != <NUM_LIT:0><EOL>if result:<EOL><INDENT>_type = expected_type.get_type()<EOL>result = Types.check_value(value, _type)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>result = False<EOL><DEDENT><DEDENT>elif isinstance(expected_type, list):<EOL><INDENT>result = issubclass(value_type, list)<EOL>if result:<EOL><INDENT>if len(expected_type) == <NUM_LIT:0>:<EOL><INDENT>result = len(value) == <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>_expected_type = expected_type[<NUM_LIT:0>]<EOL>for item in value:<EOL><INDENT>result = Types.check_value(<EOL>item,<EOL>_expected_type<EOL>)<EOL>if not result:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(expected_type, set):<EOL><INDENT>result = issubclass(value_type, set)<EOL>if result:<EOL><INDENT>if len(expected_type) == <NUM_LIT:0>:<EOL><INDENT>result = len(value) == <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>_expected_type = expected_type.copy().pop()<EOL>_value = value.copy()<EOL>value_length = len(_value)<EOL>for _ in range(value_length):<EOL><INDENT>item = _value.pop()<EOL>result = Types.check_value(<EOL>item,<EOL>_expected_type)<EOL>if not result:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>result = issubclass(value_type, expected_type)<EOL><DEDENT><DEDENT><DEDENT>return result<EOL> | Check Types parameters. | f15419:c0:m1 |
def __init__(self, varargs=None, keywords=None, *args, **kwargs): | super(Curried, self).__init__(*args, **kwargs)<EOL>if varargs is None:<EOL><INDENT>varargs = ()<EOL><DEDENT>if keywords is None:<EOL><INDENT>keywords = {}<EOL><DEDENT>self.args = self.default_args = varargs<EOL>self.kwargs = self.default_kwargs = keywords<EOL> | :param tuple varargs: function call varargs.
:param dict keywords: function call keywords. | f15419:c1:m0 |
def _checkretry(self, mydelay, condition, tries_remaining, data): | result = mydelay<EOL>if self.condition & condition and tries_remaining > <NUM_LIT:0>:<EOL><INDENT>if self.hook is not None:<EOL><INDENT>self.hook(data, condition, tries_remaining, mydelay)<EOL><DEDENT>sleep(mydelay)<EOL>result *= self.backoff <EOL><DEDENT>elif condition is Retries.ON_ERROR:<EOL><INDENT>raise data <EOL><DEDENT>else: <EOL><INDENT>result = None<EOL><DEDENT>return result<EOL> | Check if input parameters allow to retries function execution.
:param float mydelay: waiting delay between two execution.
:param int condition: condition to check with this condition.
:param int tries_remaining: tries remaining.
:param data: data to hook. | f15419:c2:m2 |
def _getkey(self, args, kwargs): | values = list(args)<EOL>keys = sorted(list(kwargs))<EOL>for key in keys:<EOL><INDENT>values.append((key, kwargs[key]))<EOL><DEDENT>result = hash(tuple(values))<EOL>return result<EOL> | Get hash key from args and kwargs.
args and kwargs must be hashable.
:param tuple args: called vargs.
:param dict kwargs: called keywords.
:return: hash(tuple(args) + tuple((key, val) for key in sorted(kwargs)).
:rtype: int. | f15419:c3:m1 |
def getparams(self, result): | for key in self._cache:<EOL><INDENT>if self._cache[key][<NUM_LIT:2>] == result:<EOL><INDENT>args, kwargs, _ = self._cache[key]<EOL>return args, kwargs<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Get result parameters.
:param result: cached result.
:raises: ValueError if result is not cached.
:return: args and kwargs registered with input result.
:rtype: tuple | f15419:c3:m3 |
def clearcache(self): | self._cache.clear()<EOL> | Clear cache. | f15419:c3:m4 |
def block_addr(self, sector, block): | return sector * <NUM_LIT:4> + block<EOL> | Returns block address of spec. block in spec. sector. | f15426:c0:m1 |
def sector_string(self, block_address): | return "<STR_LIT:S>" + str((block_address - (block_address % <NUM_LIT:4>)) / <NUM_LIT:4>) + "<STR_LIT:B>" + str(block_address % <NUM_LIT:4>)<EOL> | Returns sector and it's block representation of block address, e.g.
S01B03 for sector trailer in second sector. | f15426:c0:m2 |
def set_tag(self, uid): | if self.debug:<EOL><INDENT>print("<STR_LIT>" + str(uid))<EOL><DEDENT>if self.uid != None:<EOL><INDENT>self.deauth()<EOL><DEDENT>self.uid = uid<EOL>return self.rfid.select_tag(uid)<EOL> | Sets tag for further operations.
Calls deauth() if card is already set.
Calls RFID select_tag().
Returns called select_tag() error state. | f15426:c0:m3 |
def auth(self, auth_method, key): | self.method = auth_method<EOL>self.key = key<EOL>if self.debug:<EOL><INDENT>print("<STR_LIT>" + str(key) + "<STR_LIT>" + ("<STR_LIT:A>" if auth_method == self.rfid.auth_a else "<STR_LIT:B>"))<EOL><DEDENT> | Sets authentication info for current tag | f15426:c0:m4 |
def deauth(self): | self.method = None<EOL>self.key = None<EOL>self.last_auth = None<EOL>if self.debug:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if self.rfid.authed:<EOL><INDENT>self.rfid.stop_crypto()<EOL>if self.debug:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT> | Resets authentication info. Calls stop_crypto() if RFID is in auth state | f15426:c0:m5 |
def do_auth(self, block_address, force=False): | auth_data = (block_address, self.method, self.key, self.uid)<EOL>if (self.last_auth != auth_data) or force:<EOL><INDENT>if self.debug:<EOL><INDENT>print("<STR_LIT>" + str(self.uid))<EOL><DEDENT>self.last_auth = auth_data<EOL>return self.rfid.card_auth(self.method, block_address, self.key, self.uid)<EOL><DEDENT>else:<EOL><INDENT>if self.debug:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return False<EOL><DEDENT> | Calls RFID card_auth() with saved auth information if needed.
Returns error state from method call. | f15426:c0:m7 |
def write_trailer(self, sector, key_a=(<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>), auth_bits=(<NUM_LIT>, <NUM_LIT>, <NUM_LIT>), <EOL>user_data=<NUM_LIT>, key_b=(<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>)): | addr = self.block_addr(sector, <NUM_LIT:3>)<EOL>return self.rewrite(addr, key_a[:<NUM_LIT:6>] + auth_bits[:<NUM_LIT:3>] + (user_data, ) + key_b[:<NUM_LIT:6>])<EOL> | Writes sector trailer of specified sector. Tag and auth must be set - does auth.
If value is None, value of byte is kept.
Returns error state. | f15426:c0:m8 |
def rewrite(self, block_address, new_bytes): | if not self.is_tag_set_auth():<EOL><INDENT>return True<EOL><DEDENT>error = self.do_auth(block_address)<EOL>if not error:<EOL><INDENT>(error, data) = self.rfid.read(block_address)<EOL>if not error:<EOL><INDENT>for i in range(len(new_bytes)):<EOL><INDENT>if new_bytes[i] != None:<EOL><INDENT>if self.debug:<EOL><INDENT>print("<STR_LIT>" + str(i) + "<STR_LIT>" + str(data[i]) + "<STR_LIT>" + str(new_bytes[i]))<EOL><DEDENT>data[i] = new_bytes[i]<EOL><DEDENT><DEDENT>error = self.rfid.write(block_address, data)<EOL>if self.debug:<EOL><INDENT>print("<STR_LIT>" + str(data) + "<STR_LIT>" + self.sector_string(block_address))<EOL><DEDENT><DEDENT><DEDENT>return error<EOL> | Rewrites block with new bytes, keeping the old ones if None is passed. Tag and auth must be set - does auth.
Returns error state. | f15426:c0:m9 |
def read_out(self, block_address): | if not self.is_tag_set_auth():<EOL><INDENT>return True<EOL><DEDENT>error = self.do_auth(block_address)<EOL>if not error:<EOL><INDENT>(error, data) = self.rfid.read(block_address)<EOL>print(self.sector_string(block_address) + "<STR_LIT>" + str(data))<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" + self.sector_string(block_address))<EOL><DEDENT> | Prints sector/block number and contents of block. Tag and auth must be set - does auth. | f15426:c0:m10 |
def get_access_bits(self, c1, c2, c3): | byte_6 = ((~c2[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:7>) + ((~c2[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:6>) + ((~c2[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:5>) + ((~c2[<NUM_LIT:0>] & <NUM_LIT:1>) << <NUM_LIT:4>) +((~c1[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:3>) + ((~c1[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:2>) + ((~c1[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:1>) + (~c1[<NUM_LIT:0>] & <NUM_LIT:1>)<EOL>byte_7 = ((c1[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:7>) + ((c1[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:6>) + ((c1[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:5>) + ((c1[<NUM_LIT:0>] & <NUM_LIT:1>) << <NUM_LIT:4>) +((~c3[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:3>) + ((~c3[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:2>) + ((~c3[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:1>) + (~c3[<NUM_LIT:0>] & <NUM_LIT:1>)<EOL>byte_8 = ((c3[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:7>) + ((c3[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:6>) + ((c3[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:5>) + ((c3[<NUM_LIT:0>] & <NUM_LIT:1>) << <NUM_LIT:4>) +((c2[<NUM_LIT:3>] & <NUM_LIT:1>) << <NUM_LIT:3>) + ((c2[<NUM_LIT:2>] & <NUM_LIT:1>) << <NUM_LIT:2>) + ((c2[<NUM_LIT:1>] & <NUM_LIT:1>) << <NUM_LIT:1>) + (c2[<NUM_LIT:0>] & <NUM_LIT:1>)<EOL>return byte_6, byte_7, byte_8<EOL> | Calculates the access bits for a sector trailer based on their access conditions
c1, c2, c3, c4 are 4 items tuples containing the values for each block
returns the 3 bytes for the sector trailer | f15426:c0:m11 |
def set_antenna_gain(self, gain): | if <NUM_LIT:0> <= gain <= <NUM_LIT:7>:<EOL><INDENT>self.antenna_gain = gain<EOL><DEDENT> | Sets antenna gain from a value from 0 to 7. | f15427:c0:m8 |
def request(self, req_mode=<NUM_LIT>): | error = True<EOL>back_bits = <NUM_LIT:0><EOL>self.dev_write(<NUM_LIT>, <NUM_LIT>)<EOL>(error, back_data, back_bits) = self.card_write(self.mode_transrec, [req_mode, ])<EOL>if error or (back_bits != <NUM_LIT>):<EOL><INDENT>return (True, None)<EOL><DEDENT>return (False, back_bits)<EOL> | Requests for tag.
Returns (False, None) if no tag is present, otherwise returns (True, tag type) | f15427:c0:m10 |
def anticoll(self): | back_data = []<EOL>serial_number = []<EOL>serial_number_check = <NUM_LIT:0><EOL>self.dev_write(<NUM_LIT>, <NUM_LIT>)<EOL>serial_number.append(self.act_anticl)<EOL>serial_number.append(<NUM_LIT>)<EOL>(error, back_data, back_bits) = self.card_write(self.mode_transrec, serial_number)<EOL>if not error:<EOL><INDENT>if len(back_data) == <NUM_LIT:5>:<EOL><INDENT>for i in range(<NUM_LIT:4>):<EOL><INDENT>serial_number_check = serial_number_check ^ back_data[i]<EOL><DEDENT>if serial_number_check != back_data[<NUM_LIT:4>]:<EOL><INDENT>error = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>error = True<EOL><DEDENT><DEDENT>return (error, back_data)<EOL> | Anti-collision detection.
Returns tuple of (error state, tag ID). | f15427:c0:m11 |
def select_tag(self, uid): | back_data = []<EOL>buf = []<EOL>buf.append(self.act_select)<EOL>buf.append(<NUM_LIT>)<EOL>for i in range(<NUM_LIT:5>):<EOL><INDENT>buf.append(uid[i])<EOL><DEDENT>crc = self.calculate_crc(buf)<EOL>buf.append(crc[<NUM_LIT:0>])<EOL>buf.append(crc[<NUM_LIT:1>])<EOL>(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)<EOL>if (not error) and (back_length == <NUM_LIT>):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT> | Selects tag for further usage.
uid -- list or tuple with four bytes tag ID
Returns error state. | f15427:c0:m13 |
def card_auth(self, auth_mode, block_address, key, uid): | buf = []<EOL>buf.append(auth_mode)<EOL>buf.append(block_address)<EOL>for i in range(len(key)):<EOL><INDENT>buf.append(key[i])<EOL><DEDENT>for i in range(<NUM_LIT:4>):<EOL><INDENT>buf.append(uid[i])<EOL><DEDENT>(error, back_data, back_length) = self.card_write(self.mode_auth, buf)<EOL>if not (self.dev_read(<NUM_LIT>) & <NUM_LIT>) != <NUM_LIT:0>:<EOL><INDENT>error = True<EOL><DEDENT>if not error:<EOL><INDENT>self.authed = True<EOL><DEDENT>return error<EOL> | Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.
auth_mode -- RFID.auth_a or RFID.auth_b
key -- list or tuple with six bytes key
uid -- list or tuple with four bytes tag ID
Returns error state. | f15427:c0:m14 |
def stop_crypto(self): | self.clear_bitmask(<NUM_LIT>, <NUM_LIT>)<EOL>self.authed = False<EOL> | Ends operations with Crypto1 usage. | f15427:c0:m15 |
def halt(self): | buf = []<EOL>buf.append(self.act_end)<EOL>buf.append(<NUM_LIT:0>)<EOL>crc = self.calculate_crc(buf)<EOL>self.clear_bitmask(<NUM_LIT>, <NUM_LIT>)<EOL>self.card_write(self.mode_transrec, buf)<EOL>self.clear_bitmask(<NUM_LIT>, <NUM_LIT>)<EOL>self.authed = False<EOL> | Switch state to HALT | f15427:c0:m16 |
def read(self, block_address): | buf = []<EOL>buf.append(self.act_read)<EOL>buf.append(block_address)<EOL>crc = self.calculate_crc(buf)<EOL>buf.append(crc[<NUM_LIT:0>])<EOL>buf.append(crc[<NUM_LIT:1>])<EOL>(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)<EOL>if len(back_data) != <NUM_LIT:16>:<EOL><INDENT>error = True<EOL><DEDENT>return (error, back_data)<EOL> | Reads data from block. You should be authenticated before calling read.
Returns tuple of (error state, read data). | f15427:c0:m17 |
def write(self, block_address, data): | buf = []<EOL>buf.append(self.act_write)<EOL>buf.append(block_address)<EOL>crc = self.calculate_crc(buf)<EOL>buf.append(crc[<NUM_LIT:0>])<EOL>buf.append(crc[<NUM_LIT:1>])<EOL>(error, back_data, back_length) = self.card_write(self.mode_transrec, buf)<EOL>if not(back_length == <NUM_LIT:4>) or not((back_data[<NUM_LIT:0>] & <NUM_LIT>) == <NUM_LIT>):<EOL><INDENT>error = True<EOL><DEDENT>if not error:<EOL><INDENT>buf_w = []<EOL>for i in range(<NUM_LIT:16>):<EOL><INDENT>buf_w.append(data[i])<EOL><DEDENT>crc = self.calculate_crc(buf_w)<EOL>buf_w.append(crc[<NUM_LIT:0>])<EOL>buf_w.append(crc[<NUM_LIT:1>])<EOL>(error, back_data, back_length) = self.card_write(self.mode_transrec, buf_w)<EOL>if not(back_length == <NUM_LIT:4>) or not((back_data[<NUM_LIT:0>] & <NUM_LIT>) == <NUM_LIT>):<EOL><INDENT>error = True<EOL><DEDENT><DEDENT>return error<EOL> | Writes data to block. You should be authenticated before calling write.
Returns error state. | f15427:c0:m18 |
def cleanup(self): | if self.authed:<EOL><INDENT>self.stop_crypto()<EOL><DEDENT>GPIO.cleanup()<EOL> | Calls stop_crypto() if needed and cleanups GPIO. | f15427:c0:m22 |
def util(self): | try:<EOL><INDENT>from .util import RFIDUtil<EOL>return RFIDUtil(self)<EOL><DEDENT>except ImportError:<EOL><INDENT>return None<EOL><DEDENT> | Creates and returns RFIDUtil object for this RFID instance.
If module is not present, returns None. | f15427:c0:m23 |
def produce(self, *args, **kwargs): | new_plugins = []<EOL>for p in self._plugins:<EOL><INDENT>r = p(*args, **kwargs)<EOL>new_plugins.append(r)<EOL><DEDENT>return PluginManager(new_plugins)<EOL> | Produce a new set of plugins, treating the current set as plugin
factories. | f15439:c0:m4 |
def call(self, methodname, *args, **kwargs): | for plugin in self._plugins:<EOL><INDENT>method = getattr(plugin, methodname, None)<EOL>if method is None:<EOL><INDENT>continue<EOL><DEDENT>yield method(*args, **kwargs)<EOL><DEDENT> | Call a common method on all the plugins, if it exists. | f15439:c0:m5 |
def first(self, methodname, *args, **kwargs): | for r in self.call(methodname, *args, **kwargs):<EOL><INDENT>if r is not None:<EOL><INDENT>return r<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>")<EOL> | Call a common method on all the plugins, if it exists. Return the
first result (the first non-None) | f15439:c0:m6 |
def pipe(self, methodname, first_arg, *args, **kwargs): | for plugin in self._plugins:<EOL><INDENT>method = getattr(plugin, methodname, None)<EOL>if method is None:<EOL><INDENT>continue<EOL><DEDENT>r = method(first_arg, *args, **kwargs)<EOL>if r is not None:<EOL><INDENT>first_arg = r<EOL><DEDENT><DEDENT>return r<EOL> | Call a common method on all the plugins, if it exists. The return
value of each call becomes the replaces the first argument in the given
argument list to pass to the next.
Useful to utilize plugins as sets of filters. | f15439:c0:m7 |
def unified_load(namespace, subclasses=None, recurse=False): | if subclasses is not None:<EOL><INDENT>return ClassLoader(recurse=recurse).load(namespace, subclasses=subclasses)<EOL><DEDENT>else:<EOL><INDENT>return ModuleLoader(recurse=recurse).load(namespace)<EOL><DEDENT> | Provides a unified interface to both the module and class loaders,
finding modules by default or classes if given a ``subclasses`` parameter. | f15440:m0 |
def _fill_cache(self, namespace): | modules = self._findPluginModules(namespace)<EOL>self._cache = list(modules)<EOL> | Load all modules found in a namespace | f15440:c1:m4 |
@register.simple_tag(takes_context=True)<EOL>def render_title_tag(context, is_og=False): | request = context['<STR_LIT>']<EOL>content = '<STR_LIT>'<EOL>if context.get('<STR_LIT:object>'):<EOL><INDENT>try:<EOL><INDENT>content = context['<STR_LIT:object>'].get_meta_title()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif context.get('<STR_LIT>'):<EOL><INDENT>content = context['<STR_LIT>'].get('<STR_LIT:title>')<EOL><DEDENT>if not content:<EOL><INDENT>try:<EOL><INDENT>content = request.current_page.get_page_title() <EOL>if not content:<EOL><INDENT>content = request.current_page.get_title()<EOL><DEDENT><DEDENT>except (AttributeError, NoReverseMatch):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not is_og:<EOL><INDENT>return content<EOL><DEDENT>else:<EOL><INDENT>return mark_safe('<STR_LIT>'.format(content=content))<EOL><DEDENT> | Returns the title as string or a complete open graph meta tag. | f15454:m1 |
@register.simple_tag(takes_context=True)<EOL>def render_description_meta_tag(context, is_og=False): | request = context['<STR_LIT>']<EOL>content = '<STR_LIT>'<EOL>if context.get('<STR_LIT:object>'):<EOL><INDENT>try:<EOL><INDENT>content = context['<STR_LIT:object>'].get_meta_description()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif context.get('<STR_LIT>'):<EOL><INDENT>content = context['<STR_LIT>'].get('<STR_LIT:description>')<EOL><DEDENT>if not content:<EOL><INDENT>try:<EOL><INDENT>content = request.current_page.get_meta_description()<EOL><DEDENT>except (AttributeError, NoReverseMatch):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if content:<EOL><INDENT>return mark_safe('<STR_LIT>'.format(<EOL>attr_name='<STR_LIT:name>' if not is_og else '<STR_LIT>',<EOL>tag_name='<STR_LIT:description>' if not is_og else '<STR_LIT>',<EOL>content=content<EOL>))<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT> | Returns the description as meta or open graph tag. | f15454:m2 |
@register.simple_tag(takes_context=True)<EOL>def render_robots_meta_tag(context): | request = context['<STR_LIT>']<EOL>robots_indexing = None<EOL>robots_following = None<EOL>if context.request.get_host() in settings.META_TAGGER_ROBOTS_DOMAIN_WHITELIST:<EOL><INDENT>if context.get('<STR_LIT:object>'):<EOL><INDENT>try:<EOL><INDENT>robots_indexing = context['<STR_LIT:object>'].get_robots_indexing()<EOL>robots_following = context['<STR_LIT:object>'].get_robots_following()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif context.get('<STR_LIT>'):<EOL><INDENT>robots_indexing = context['<STR_LIT>'].get('<STR_LIT>', robots_indexing)<EOL>robots_following = context['<STR_LIT>'].get('<STR_LIT>', robots_following)<EOL><DEDENT>if robots_indexing is None:<EOL><INDENT>try:<EOL><INDENT>robots_indexing = request.current_page.metatagpageextension.robots_indexing<EOL><DEDENT>except (AttributeError, NoReverseMatch, MetaTagPageExtension.DoesNotExist):<EOL><INDENT>robots_indexing = True<EOL><DEDENT><DEDENT>if robots_following is None:<EOL><INDENT>try:<EOL><INDENT>robots_following = request.current_page.metatagpageextension.robots_following<EOL><DEDENT>except (AttributeError, NoReverseMatch, MetaTagPageExtension.DoesNotExist):<EOL><INDENT>robots_following = True<EOL><DEDENT><DEDENT><DEDENT>return mark_safe('<STR_LIT>'.format(<EOL>robots_indexing='<STR_LIT:index>' if robots_indexing else '<STR_LIT>',<EOL>robots_following='<STR_LIT>' if robots_following else '<STR_LIT>'<EOL>))<EOL> | Returns the robots meta tag. | f15454:m3 |
def split_ls(func): | @wraps(func)<EOL>def wrapper(self, files, silent=True, exclude_deleted=False):<EOL><INDENT>if not isinstance(files, (tuple, list)):<EOL><INDENT>files = [files]<EOL><DEDENT>counter = <NUM_LIT:0><EOL>index = <NUM_LIT:0><EOL>results = []<EOL>while files:<EOL><INDENT>if index >= len(files):<EOL><INDENT>results += func(self, files, silent, exclude_deleted)<EOL>break<EOL><DEDENT>length = len(str(files[index]))<EOL>if length + counter > CHAR_LIMIT:<EOL><INDENT>runfiles = files[:index]<EOL>files = files[index:]<EOL>counter = <NUM_LIT:0><EOL>index = <NUM_LIT:0><EOL>results += func(self, runfiles, silent, exclude_deleted)<EOL>runfiles = None<EOL>del runfiles<EOL><DEDENT>else:<EOL><INDENT>index += <NUM_LIT:1><EOL>counter += length<EOL><DEDENT><DEDENT>return results<EOL><DEDENT>return wrapper<EOL> | Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function | f15471:m0 |
def camel_case(string): | return '<STR_LIT>'.join((string[<NUM_LIT:0>].lower(), string[<NUM_LIT:1>:]))<EOL> | Makes a string camelCase
:param string: String to convert | f15471:m1 |
def __getVariables(self): | try:<EOL><INDENT>startupinfo = None<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>startupinfo = subprocess.STARTUPINFO()<EOL>startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW<EOL><DEDENT>output = subprocess.check_output(['<STR_LIT>', '<STR_LIT>'], startupinfo=startupinfo)<EOL>if six.PY3:<EOL><INDENT>output = str(output, '<STR_LIT:utf8>')<EOL><DEDENT><DEDENT>except subprocess.CalledProcessError as err:<EOL><INDENT>LOGGER.error(err)<EOL>return<EOL><DEDENT>p4vars = {}<EOL>for line in output.splitlines():<EOL><INDENT>if not line:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>k, v = line.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>p4vars[k.strip()] = v.strip().split('<STR_LIT>')[<NUM_LIT:0>]<EOL>if p4vars[k.strip()].startswith('<STR_LIT>'):<EOL><INDENT>del p4vars[k.strip()]<EOL><DEDENT><DEDENT>self._port = self._port or os.getenv('<STR_LIT>', p4vars.get('<STR_LIT>'))<EOL>self._user = self._user or os.getenv('<STR_LIT>', p4vars.get('<STR_LIT>'))<EOL>self._client = self._client or os.getenv('<STR_LIT>', p4vars.get('<STR_LIT>'))<EOL> | Parses the P4 env vars using 'set p4 | f15471:c0:m2 |
@property<EOL><INDENT>def client(self):<DEDENT> | if isinstance(self._client, six.string_types):<EOL><INDENT>self._client = Client(self._client, self)<EOL><DEDENT>return self._client<EOL> | The client used in perforce queries | f15471:c0:m3 |
@property<EOL><INDENT>def user(self):<DEDENT> | return self._user<EOL> | The user used in perforce queries | f15471:c0:m5 |
@property<EOL><INDENT>def level(self):<DEDENT> | return self._level<EOL> | The current exception level | f15471:c0:m6 |
@level.setter<EOL><INDENT>def level(self, value):<DEDENT> | self._level = value<EOL> | Set the current exception level | f15471:c0:m7 |
@property<EOL><INDENT>def status(self):<DEDENT> | try:<EOL><INDENT>res = self.run(['<STR_LIT:info>'])<EOL>if res[<NUM_LIT:0>]['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return ConnectionStatus.INVALID_CLIENT<EOL><DEDENT>self.run(['<STR_LIT:user>', '<STR_LIT>'])<EOL><DEDENT>except errors.CommandError as err:<EOL><INDENT>if '<STR_LIT>' in str(err.args[<NUM_LIT:0>]):<EOL><INDENT>return ConnectionStatus.NO_AUTH<EOL><DEDENT>if '<STR_LIT>' in str(err.args[<NUM_LIT:0>]):<EOL><INDENT>return ConnectionStatus.OFFLINE<EOL><DEDENT><DEDENT>return ConnectionStatus.OK<EOL> | The status of the connection to perforce | f15471:c0:m8 |
def run(self, cmd, stdin=None, marshal_output=True, **kwargs): | records = []<EOL>args = [self._executable, "<STR_LIT>", self._user, "<STR_LIT>", self._port]<EOL>if self._client:<EOL><INDENT>args += ["<STR_LIT:-c>", str(self._client)]<EOL><DEDENT>if marshal_output:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if isinstance(cmd, six.string_types):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>args += cmd<EOL>command = '<STR_LIT:U+0020>'.join(args)<EOL>startupinfo = None<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>startupinfo = subprocess.STARTUPINFO()<EOL>startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW<EOL><DEDENT>proc = subprocess.Popen(<EOL>args,<EOL>stdin=subprocess.PIPE,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>startupinfo=startupinfo,<EOL>**kwargs<EOL>)<EOL>if stdin:<EOL><INDENT>proc.stdin.write(six.b(stdin))<EOL><DEDENT>if marshal_output:<EOL><INDENT>try:<EOL><INDENT>while True:<EOL><INDENT>record = marshal.load(proc.stdout)<EOL>if record.get(b'<STR_LIT:code>', '<STR_LIT>') == b'<STR_LIT:error>' and record[b'<STR_LIT>'] >= self._level:<EOL><INDENT>proc.stdin.close()<EOL>proc.stdout.close()<EOL>raise errors.CommandError(record[b'<STR_LIT:data>'], record, command)<EOL><DEDENT>if isinstance(record, dict):<EOL><INDENT>if six.PY2:<EOL><INDENT>records.append(record)<EOL><DEDENT>else:<EOL><INDENT>records.append({str(k, '<STR_LIT:utf8>'): str(v) if isinstance(v, int) else str(v, '<STR_LIT:utf8>', errors='<STR_LIT:ignore>') for k, v in record.items()})<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except EOFError:<EOL><INDENT>pass<EOL><DEDENT>stdout, stderr = proc.communicate()<EOL><DEDENT>else:<EOL><INDENT>records, stderr = proc.communicate()<EOL><DEDENT>if stderr:<EOL><INDENT>raise errors.CommandError(stderr, command)<EOL><DEDENT>return records<EOL> | Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or not to marshal the output from the command
:type marshal_output: bool
:param kwargs: Passes any other keyword arguments to subprocess
:raises: :class:`.error.CommandError`
:returns: list, records of results | f15471:c0:m9 |
@split_ls<EOL><INDENT>def ls(self, files, silent=True, exclude_deleted=False):<DEDENT> | try:<EOL><INDENT>cmd = ['<STR_LIT>']<EOL>if exclude_deleted:<EOL><INDENT>cmd += ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>cmd += files<EOL>results = self.run(cmd)<EOL><DEDENT>except errors.CommandError as err:<EOL><INDENT>if silent:<EOL><INDENT>results = []<EOL><DEDENT>elif "<STR_LIT>" in str(err):<EOL><INDENT>raise errors.RevisionError(err.args[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>return [Revision(r, self) for r in results if r.get('<STR_LIT:code>') != '<STR_LIT:error>']<EOL> | List files
:param files: Perforce file spec
:type files: list
:param silent: Will not raise error for invalid files or files not under the client
:type silent: bool
:param exclude_deleted: Exclude deleted files from the query
:type exclude_deleted: bool
:raises: :class:`.errors.RevisionError`
:returns: list<:class:`.Revision`> | f15471:c0:m10 |
def findChangelist(self, description=None): | if description is None:<EOL><INDENT>change = Default(self)<EOL><DEDENT>else:<EOL><INDENT>if isinstance(description, six.integer_types):<EOL><INDENT>change = Changelist(description, self)<EOL><DEDENT>else:<EOL><INDENT>pending = self.run(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:-c>', str(self._client), '<STR_LIT>', self._user])<EOL>for cl in pending:<EOL><INDENT>if cl['<STR_LIT>'].strip() == description.strip():<EOL><INDENT>LOGGER.debug('<STR_LIT>'.format(cl['<STR_LIT>']))<EOL>change = Changelist(int(cl['<STR_LIT>']), self)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>LOGGER.debug('<STR_LIT>')<EOL>change = Changelist.create(description, self)<EOL>change.client = self._client<EOL>change.save()<EOL><DEDENT><DEDENT><DEDENT>return change<EOL> | Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist` | f15471:c0:m11 |
def add(self, filename, change=None): | try:<EOL><INDENT>if not self.canAdd(filename):<EOL><INDENT>raise errors.RevisionError('<STR_LIT>')<EOL><DEDENT>if change is None:<EOL><INDENT>self.run(['<STR_LIT>', filename])<EOL><DEDENT>else:<EOL><INDENT>self.run(['<STR_LIT>', '<STR_LIT:-c>', str(change.change), filename])<EOL><DEDENT>data = self.run(['<STR_LIT>', filename])[<NUM_LIT:0>]<EOL><DEDENT>except errors.CommandError as err:<EOL><INDENT>LOGGER.debug(err)<EOL>raise errors.RevisionError('<STR_LIT>')<EOL><DEDENT>rev = Revision(data, self)<EOL>if isinstance(change, Changelist):<EOL><INDENT>change.append(rev)<EOL><DEDENT>return rev<EOL> | Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision` | f15471:c0:m12 |
def canAdd(self, filename): | try:<EOL><INDENT>result = self.run(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:text>', filename])[<NUM_LIT:0>]<EOL><DEDENT>except errors.CommandError as err:<EOL><INDENT>LOGGER.debug(err)<EOL>return False<EOL><DEDENT>if result.get('<STR_LIT:code>') not in ('<STR_LIT:error>', '<STR_LIT:info>'):<EOL><INDENT>return True<EOL><DEDENT>LOGGER.warn('<STR_LIT>'.format(filename, result['<STR_LIT:data>']))<EOL>return False<EOL> | Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str | f15471:c0:m13 |
def save(self): | if not self._dirty:<EOL><INDENT>return<EOL><DEDENT>fields = []<EOL>formdata = dict(self._p4dict)<EOL>del formdata['<STR_LIT:code>']<EOL>for key, value in six.iteritems(formdata):<EOL><INDENT>match = re.search('<STR_LIT>', key)<EOL>if match:<EOL><INDENT>value = '<STR_LIT>'.format(value)<EOL>key = key[:match.start()]<EOL><DEDENT>value = value.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>fields.append('<STR_LIT>'.format(key, value))<EOL><DEDENT>form = '<STR_LIT:\n>'.join(fields)<EOL>self._connection.run([self.COMMAND, '<STR_LIT>'], stdin=form, marshal_output=False)<EOL>self._dirty = False<EOL> | Saves the state of the changelist | f15471:c2:m1 |
def query(self, files=True): | if self._change:<EOL><INDENT>cl = str(self._change)<EOL>self._p4dict = {camel_case(k): v for k, v in six.iteritems(self._connection.run(['<STR_LIT>', '<STR_LIT>', cl])[<NUM_LIT:0>])}<EOL><DEDENT>if files:<EOL><INDENT>self._files = []<EOL>if self._p4dict.get('<STR_LIT:status>') == '<STR_LIT>' or self._change == <NUM_LIT:0>:<EOL><INDENT>change = self._change or '<STR_LIT:default>'<EOL>data = self._connection.run(['<STR_LIT>', '<STR_LIT:-c>', str(change)])<EOL>self._files = [Revision(r, self._connection) for r in data]<EOL><DEDENT>else:<EOL><INDENT>data = self._connection.run(['<STR_LIT>', str(self._change)])[<NUM_LIT:0>]<EOL>depotfiles = []<EOL>for k, v in six.iteritems(data):<EOL><INDENT>if k.startswith('<STR_LIT>'):<EOL><INDENT>depotfiles.append(v)<EOL><DEDENT><DEDENT>self._files = self._connection.ls(depotfiles)<EOL><DEDENT><DEDENT> | Queries the depot to get the current status of the changelist | f15471:c3:m12 |
def append(self, rev): | if not isinstance(rev, Revision):<EOL><INDENT>results = self._connection.ls(rev)<EOL>if not results:<EOL><INDENT>self._connection.add(rev, self)<EOL>return<EOL><DEDENT>rev = results[<NUM_LIT:0>]<EOL><DEDENT>if not rev in self:<EOL><INDENT>if rev.isMapped:<EOL><INDENT>rev.edit(self)<EOL><DEDENT>self._files.append(rev)<EOL>rev.changelist = self<EOL>self._dirty = True<EOL><DEDENT> | Adds a :py:class:Revision to this changelist and adds or checks it out if needed
:param rev: Revision to add
:type rev: :class:`.Revision` | f15471:c3:m13 |
def remove(self, rev, permanent=False): | if not isinstance(rev, Revision):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if rev not in self:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(rev))<EOL><DEDENT>self._files.remove(rev)<EOL>if not permanent:<EOL><INDENT>rev.changelist = self._connection.default<EOL><DEDENT> | Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool | f15471:c3:m14 |
def revert(self, unchanged_only=False): | if self._reverted:<EOL><INDENT>raise errors.ChangelistError('<STR_LIT>')<EOL><DEDENT>change = self._change<EOL>if self._change == <NUM_LIT:0>:<EOL><INDENT>change = '<STR_LIT:default>'<EOL><DEDENT>cmd = ['<STR_LIT>', '<STR_LIT:-c>', str(change)]<EOL>if unchanged_only:<EOL><INDENT>cmd.append('<STR_LIT>')<EOL><DEDENT>files = [f.depotFile for f in self._files]<EOL>if files:<EOL><INDENT>cmd += files<EOL>self._connection.run(cmd)<EOL><DEDENT>self._files = []<EOL>self._reverted = True<EOL> | Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError` | f15471:c3:m15 |
def save(self): | self._connection.run(['<STR_LIT>', '<STR_LIT>'], stdin=format(self), marshal_output=False)<EOL>self._dirty = False<EOL> | Saves the state of the changelist | f15471:c3:m16 |
def submit(self): | if self._dirty:<EOL><INDENT>self.save()<EOL><DEDENT>self._connection.run(['<STR_LIT>', '<STR_LIT:-c>', str(self._change)], marshal_output=False)<EOL> | Submits a chagelist to the depot | f15471:c3:m17 |
def delete(self): | try:<EOL><INDENT>self.revert()<EOL><DEDENT>except errors.ChangelistError:<EOL><INDENT>pass<EOL><DEDENT>self._connection.run(['<STR_LIT>', '<STR_LIT>', str(self._change)])<EOL> | Reverts all files in this changelist then deletes the changelist from perforce | f15471:c3:m18 |
@property<EOL><INDENT>def client(self):<DEDENT> | return self._p4dict['<STR_LIT>']<EOL> | Perforce client this changelist is under | f15471:c3:m20 |
@property<EOL><INDENT>def description(self):<DEDENT> | return self._p4dict['<STR_LIT:description>'].strip()<EOL> | Changelist description | f15471:c3:m22 |
@property<EOL><INDENT>def isDirty(self):<DEDENT> | return self._dirty<EOL> | Does this changelist have unsaved changes | f15471:c3:m26 |
@property<EOL><INDENT>def time(self):<DEDENT> | return datetime.datetime.strptime(self._p4dict['<STR_LIT:date>'], DATE_FORMAT)<EOL> | Creation time of this changelist | f15471:c3:m27 |
@staticmethod<EOL><INDENT>def create(description='<STR_LIT>', connection=None):<DEDENT> | connection = connection or Connection()<EOL>description = description.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>form = NEW_FORMAT.format(client=str(connection.client), description=description)<EOL>result = connection.run(['<STR_LIT>', '<STR_LIT>'], stdin=form, marshal_output=False)<EOL>return Changelist(int(result.split()[<NUM_LIT:1>]), connection)<EOL> | Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:returns: :class:`.Changelist` | f15471:c3:m28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.