Unapply interception on input target in cleaning it.

    :param routine target: target from where removing an interception
        function. is_joinpoint(target) must be True.
    :param ctx: target ctx.
517211
def _unapply_interception(target, ctx=None):
    

    # try to get the right ctx
    if ctx is None:
        ctx = find_ctx(elt=target)

    # get previous target
    intercepted, old_ctx = get_intercepted(target)

    # if ctx is None and old_ctx is not None, update ctx with old_ctx
    if ctx is None and old_ctx is not None:
        ctx = old_ctx

    if intercepted is None:
        raise JoinpointError('{0} must be intercepted'.format(target))

    # flag to deleting of joinpoint_function
    del_joinpoint_function = False

    # if old target is a not modifiable resource
    if isbuiltin(intercepted):
        module = getmodule(intercepted)
        found = False

        # update references to target to not modifiable element in module
        for name, member in getmembers(module):
            if member is target:
                setattr(module, name, intercepted)
                found = True

        # if no reference found, raise an Exception
        if not found:
            raise JoinpointError(
                "Impossible to unapply interception on not modifiable element \
                {0}. Must be contained in module {1}".format(target, module)
            )

    elif ctx is None:
        # get joinpoint function
        joinpoint_function = _get_function(target)
        # update old code on target
        joinpoint_function.__code__ = intercepted.__code__
        # ensure to delete joinpoint_function
        del_joinpoint_function = True

    else:
        # flag for joinpoint recovering
        recover = False
        # get interception name in order to update/delete interception from ctx
        intercepted_name = intercepted.__name__
        # should we change of target or is it inherited ?
        if isclass(ctx):
            base_interception, _ = super_method(name=intercepted_name, ctx=ctx)
        else:
            base_interception = getattr(ctx.__class__, intercepted_name, None)
        # if base interception does not exist
        if base_interception is None:  # recover intercepted
            recover = True

        else:
            # get joinpoint_function
            joinpoint_function = _get_function(target)
            # get base function
            if is_intercepted(base_interception):
                base_intercepted, _ = get_intercepted(base_interception)
            else:
                base_intercepted = _get_function(base_interception)
            # is interception inherited ?
            if base_intercepted is joinpoint_function:
                pass  # do nothing
            # is intercepted inherited
            elif base_intercepted is intercepted:
                # del interception
                delattr(ctx, intercepted_name)
                del_joinpoint_function = True
            else:  # base function is something else
                recover = True

        if recover:  # if recover is required
            # new content to put in ctx
            new_content = intercepted
            if ismethod(target):  # in creating eventually a new method
                args = [new_content, ctx]
                if PY2:  # if py2, specify the ctx class
                    # and unbound method type
                    if target.__self__ is None:
                        args = [new_content, None, ctx]
                    else:  # or instance method
                        args.append(ctx.__class__)
                # instantiate a new method
                new_content = MethodType(*args)
            # update ctx with intercepted
            setattr(ctx, intercepted_name, new_content)
            joinpoint_function = _get_function(target)
            del_joinpoint_function = True

    if del_joinpoint_function:
        # delete _INTERCEPTED and _INTERCEPTED_CTX from joinpoint_function
        if hasattr(joinpoint_function, _INTERCEPTED):
            delattr(joinpoint_function, _INTERCEPTED)
            if hasattr(joinpoint_function, _INTERCEPTED_CTX):
                delattr(joinpoint_function, _INTERCEPTED_CTX)
        del joinpoint_function
1020414
def _interception(self, joinpoint):
        

        if self.pre_cond is not None:
            self.pre_cond(joinpoint)

        result = joinpoint.proceed()

        if self.post_cond is not None:
            joinpoint.exec_ctx[Condition.RESULT] = result
            self.post_cond(joinpoint)

        return result
625716
def deleteOverlapping(self, targetList):
        '''
        
        '''
        start = self.pointList[0][0]
        stop = self.pointList[-1][0]
        
        if self.netLeftShift < 0:
            start += self.netLeftShift
            
        if self.netRightShift > 0:
            stop += self.netRightShift
            
        targetList = _deletePoints(targetList, start, stop)
        
        return targetList
167161
def atexit_unregister(func, *args, **kwargs):
    
    try:
        atexit.unregister(func, *args, **kwargs)
    except AttributeError:
        # This code runs in Python 2.7 *only*
        # Only replace with a noop, don't delete during iteration
        for i in range(len(atexit._exithandlers)):
            if atexit._exithandlers[i] == (func, args, kwargs):
                atexit._exithandlers[i] = (lambda: None, [], {})
                break
742435
def get_unpack_filter(cls, unpackable_target):
    
    # TODO: we may be able to make use of glob matching in the engine to avoid doing this filtering.
    return cls._calculate_unpack_filter(includes=unpackable_target.payload.include_patterns,
                                        excludes=unpackable_target.payload.exclude_patterns,
                                        spec=unpackable_target.address.spec)
47130
def _hijack_target(self):
        """"""

        if self._target.is_class_or_module():
            setattr(self._target.obj, self._method_name, self)
        elif self._attr.kind == 'property':
            proxy_property = ProxyProperty(
                double_name(self._method_name),
                self._original_method,
            )
            setattr(self._target.obj.__class__, self._method_name, proxy_property)
            self._target.obj.__dict__[double_name(self._method_name)] = self
        else:
            self._target.obj.__dict__[self._method_name] = self

        if self._method_name in ['__call__', '__enter__', '__exit__']:
            self._target.hijack_attr(self._method_name)
967615
def apply_pointcut(self, target, function=None, ctx=None):
        

        try:
            __file__ = getfile(target)
        except TypeError:
            __file__ = '<string>'

        if function is None:
            function = _get_function(target)

        # flag which indicates that the function is not a pure python function
        # and has to be wrapped
        wrap_function = not hasattr(function, '__code__')

        try:
            # get params from target
            args, varargs, kwargs, _ = getargspec(function)
        except TypeError:
            # in case of error, wrap the function
            wrap_function = True

        if wrap_function:
            # if function is not pure python, create a generic one
            # with assignments
            assigned = []
            for wrapper_assignment in WRAPPER_ASSIGNMENTS:
                if hasattr(function, wrapper_assignment):
                    assigned.append(wrapper_assignment)
            # and updates
            updated = []
            for wrapper_update in WRAPPER_UPDATES:
                if hasattr(function, wrapper_update):
                    updated.append(wrapper_update)

            @wraps(function, assigned=assigned, updated=updated)
            def wrapper(*args, **kwargs):
                """Default wrapper."""

            function = wrapper

            # get params from target wrapper
            args, varargs, kwargs, _ = getargspec(function)

        # get params from target
        name = function.__name__

        # if target has not name, use 'function'
        if name == Joinpoint.__LAMBDA_NAME__:
            name = Joinpoint.__INTERCEPTION__

        # get join method for reducing concatenation time execution
        join = "".join

        # default indentation
        indent = '    '

        newcodestr = "def {0}(".format(name)
        if args:
            newcodestr = join((newcodestr, "{0}".format(args[0])))
        for arg in args[1:]:
            newcodestr = join((newcodestr, ", {0}".format(arg)))

        if varargs is not None:
            if args:
                newcodestr = join((newcodestr, ", "))
            newcodestr = join((newcodestr, "*{0}".format(varargs)))

        if kwargs is not None:
            if args or varargs is not None:
                newcodestr = join((newcodestr, ", "))
            newcodestr = join((newcodestr, "**{0}".format(kwargs)))

        newcodestr = join((newcodestr, "):\n"))

        # unique id which will be used for advicesexecutor and kwargs
        generated_id = repr(time()).replace('.', '_')

        # if kwargs is None
        if kwargs is None and args:
            kwargs = "kwargs_{0}".format(generated_id)  # generate a name
            # initialize a new dict with args
            newcodestr = join(
                (newcodestr, "{0}{1} = {{\n".format(indent, kwargs)))
            for arg in args:
                newcodestr = join(
                    (newcodestr, "{0}{0}'{1}': {1},\n".format(indent, arg))
                )
            newcodestr = join((newcodestr, "{0}}}\n".format(indent)))

        else:
            # fill args in kwargs
            for arg in args:
                newcodestr = join(
                    (newcodestr, "{0}{1}['{2}'] = {2}\n".format(
                        indent, kwargs, arg))
                )

        # advicesexecutor name
        joinpoint = "joinpoint_{0}".format(generated_id)

        if varargs:
            newcodestr = join(
                (newcodestr, "{0}{1}.args = {2}\n".format(
                    indent, joinpoint, varargs))
            )

        # set kwargs in advicesexecutor
        if kwargs is not None:
            newcodestr = join(
                (newcodestr, "{0}{1}.kwargs = {2}\n".format(
                    indent, joinpoint, kwargs))
            )

        # return advicesexecutor proceed result
        start = "start_{0}".format(generated_id)
        newcodestr = join(
            (newcodestr, "{0}return {1}()\n".format(indent, start))
        )
        # compile newcodestr
        code = compile(newcodestr, __file__, 'single')

        _globals = {}

        # define the code with the new function
        exec(code, _globals)

        # get new code
        newco = _globals[name].__code__

        # get new consts list
        newconsts = list(newco.co_consts)

        if PY3:
            newcode = list(newco.co_code)
        else:
            newcode = map(ord, newco.co_code)

        consts_values = {joinpoint: self, start: self.start}

        # change LOAD_GLOBAL to LOAD_CONST
        index = 0
        newcodelen = len(newcode)
        while index < newcodelen:
            if newcode[index] == LOAD_GLOBAL:
                oparg = newcode[index + 1] + (newcode[index + 2] << 8)
                name = newco.co_names[oparg]
                if name in consts_values:
                    const_value = consts_values[name]
                    if const_value in newconsts:
                        pos = newconsts.index(const_value)
                    else:
                        pos = len(newconsts)
                        newconsts.append(consts_values[name])
                    newcode[index] = LOAD_CONST
                    newcode[index + 1] = pos & 0xFF
                    newcode[index + 2] = pos >> 8
                    if name == start:
                        break  # stop when start is encountered
            index += 1

        # get code string
        codestr = bytes(newcode) if PY3 else join(map(chr, newcode))

        # get vargs
        vargs = [
            newco.co_argcount, newco.co_nlocals, newco.co_stacksize,
            newco.co_flags, codestr, tuple(newconsts), newco.co_names,
            newco.co_varnames, newco.co_filename, newco.co_name,
            newco.co_firstlineno, newco.co_lnotab,
            getattr(function.__code__, 'co_freevars', ()),
            newco.co_cellvars
        ]
        if PY3:
            vargs.insert(1, newco.co_kwonlyargcount)

        # instanciate a new code object
        codeobj = type(newco)(*vargs)
        # instanciate a new function
        if function is None or isbuiltin(function):
            interception_fn = FunctionType(codeobj, {})

        else:
            interception_fn = type(function)(
                codeobj,
                {} if function.__globals__ is None else function.__globals__,
                function.__name__,
                function.__defaults__,
                function.__closure__
            )

        # set wrapping assignments
        for wrapper_assignment in WRAPPER_ASSIGNMENTS:
            try:
                value = getattr(function, wrapper_assignment)
            except AttributeError:
                pass
            else:
                setattr(interception_fn, wrapper_assignment, value)
        # update wrapping updating
        for wrapper_update in WRAPPER_UPDATES:
            try:
                value = getattr(function, wrapper_update)
            except AttributeError:
                pass
            else:
                getattr(interception_fn, wrapper_update).update(value)

        # set interception, target function and ctx
        self._interception, self.target, self.ctx = _apply_interception(
            target=target, interception_fn=interception_fn, ctx=ctx
        )

        return self._interception
275550
def require_single_root_target(self):
    
    target_roots = self.context.target_roots
    if len(target_roots) == 0:
      raise TaskError('No target specified.')
    elif len(target_roots) > 1:
      raise TaskError('Multiple targets specified: {}'
                      .format(', '.join([repr(t) for t in target_roots])))
    return target_roots[0]
732061
def unregisterStdOut(func):
    
    try:
        sys.stdout.hooks.remove(weakref.ref(func))
    except (AttributeError, ValueError):
        pass
739103
def remove_go(self, target):
        
        with self.lock:
            if not self._go:
                try:
                    self.job_queue.remove(target)
                except ValueError:
                    pass
321620
final void initInvocationTarget() throws Exception {
        Member previousTargetMember = targetMember;
        T target = getInvocationTarget();
        if (target == null) {
            remote = false;
            throw newTargetNullException();
        }

        targetMember = toTargetMember(target);
        if (targetMember != null) {
            targetAddress = targetMember.getAddress();
        } else {
            targetAddress = toTargetAddress(target);
        }
        memberListVersion = context.clusterService.getMemberListVersion();

        if (targetMember == null) {
            if (previousTargetMember != null) {
                // If a target member was found earlier but current target member is null
                // then it means a member left.
                throw new MemberLeftException(previousTargetMember);
            }
            if (!(isJoinOperation(op) || isWanReplicationOperation(op))) {
                throw new TargetNotMemberException(target, op.getPartitionId(), op.getClass().getName(), op.getServiceName());
            }
        }

        if (op instanceof TargetAware) {
            ((TargetAware) op).setTarget(targetAddress);
        }

        remote = !context.thisAddress.equals(targetAddress);
    }
667464
def reflect_filter(sources, model, cache=None):
    '''
    '''
    targets = [reflect(source, model, cache=cache) for source in sources]
    # Some objects may not be available in target DB (not published), so we
    # have to exclude None from the list.
    return [target for target in targets if target is not None]
62158
def uninstallFrom(self, target):
    

    #did this class powerup on any interfaces? powerdown if so.
    target.powerDown(self)


    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target==target):
        if dc.installee is self:
            dc.deleteFromStore()

    for item in installedUniqueRequirements(self, target):
        uninstallFrom(item, target)

    callback = getattr(self, "uninstalled", None)
    if callback is not None:
        callback()
1203897
function(opSet, target) {
      var self = this;
      Parse._objectEach(opSet, function(change, key) {
        target[key] = change._estimate(target[key], self, key);
        if (target[key] === Parse.Op._UNSET) {
          delete target[key];
        }
      });
    }
486617
@MainThread
    private void handleUnRegistration(Object targetObj) {
        if (targetObj == null) {
            throw new NullPointerException("Target cannot be null");
        }

        EventTarget target = null;

        for (Iterator<EventTarget> iterator = targets.iterator(); iterator.hasNext(); ) {
            EventTarget listTarget = iterator.next();
            if (listTarget.targetObj == targetObj) {
                iterator.remove();
                target = listTarget;
                target.targetObj = null;
                break;
            }
        }

        if (target == null) {
            Utils.logE(targetObj, "Was not registered");
        }

        Utils.log(targetObj, "Unregistered");
    }
490885
def join(self, target, key=None):
        
        chantypes = self.server.features.get("CHANTYPES", "#")
        if not target or target[0] not in chantypes:
            # Among other things, this prevents accidentally sending the
            # "JOIN 0" command which actually removes you from all channels
            _log.warning("Refusing to join channel that does not start "
                         "with one of '%s': %s", chantypes, target)
            return False

        if self.server.in_channel(target):
            _log.warning("Ignoring request to join channel '%s' because we "
                         "are already in that channel.", target)
            return False

        _log.info("Joining channel %s ...", target)
        self.send("JOIN", target, *([key] if key else []))
        return True
901823
def unhook(object, type=nil, method=nil)
      raise ArgumentError.new('Object method provided for a Proc') if object.is_a?(Proc) && method
      @lock.synchronize do
        case object
        when Proc
          if(type)
            @hooks[type][:procs].delete(object)
            @hooks[type].delete(:procs) if @hooks[type][:procs].empty?
          else
            @hooks.each_value do |h|
              h[:procs].delete(object)
              h.delete(:procs) if h[:procs].empty?
            end
          end
        else
          if(method.nil? && type.nil?)
            @hooks.each_value{|v|v.delete_if{|k,z| k == object.class}}
          else
            raise ArgumentError.new('Type must be provided') if type.nil?
            const = Splib.find_const(type)
            type = const unless const.nil?
            method = method.to_sym if method
            name = object.class
            raise NameError.new('Uninitialized hook type given') unless @hooks[type]
            raise StandardError.new('No hooks found for given object') unless @hooks[type][name]
            if(method)
              @hooks[type][name].delete_if{|x|x[:method] == method}
              @hooks[type].delete(name) if @hooks[type][name].empty?
            else
              @hooks[type].delete(name)
            end
          end          
        end
        @hooks.delete_if{|k,v|v.empty?}
      end
    end